diff --git a/apps/sim/app/api/schedules/execute/route.ts b/apps/sim/app/api/schedules/execute/route.ts index bff1dbad8ec..b8ae3455f4c 100644 --- a/apps/sim/app/api/schedules/execute/route.ts +++ b/apps/sim/app/api/schedules/execute/route.ts @@ -1,11 +1,4 @@ -import { - asyncJobs, - db, - workflow, - workflowDeploymentVersion, - workflowExecutionLogs, - workflowSchedule, -} from '@sim/db' +import { asyncJobs, db, workflowExecutionLogs, workflowSchedule } from '@sim/db' import { createLogger } from '@sim/logger' import { sha256Hex } from '@sim/security/hash' import { toError } from '@sim/utils/errors' @@ -14,7 +7,7 @@ import { generateId } from '@sim/utils/id' import { isRecordLike } from '@sim/utils/object' import { randomInt } from '@sim/utils/random' import { Cron } from 'croner' -import { and, asc, eq, gt, inArray, isNull, lt, lte, or, sql } from 'drizzle-orm' +import { and, asc, eq, gt, inArray, isNull, lte, or, sql } from 'drizzle-orm' import { type NextRequest, NextResponse } from 'next/server' import type { ExecuteSchedulesResponse } from '@/lib/api/contracts/schedules' import { verifyCronAuth } from '@/lib/auth/internal' @@ -55,6 +48,10 @@ import { buildCarrierReconciledMetadata, carrierNotReconciledSql, } from '@/lib/workflows/schedules/carrier-metadata' +import { + type ClaimedWorkflowSchedule, + claimDueWorkflowSchedules, +} from '@/lib/workflows/schedules/claim' import { notifyScheduleAutoDisabled } from '@/lib/workflows/schedules/disable-notifications' import { SCHEDULE_EXECUTION_CONCURRENCY_LIMIT, @@ -85,34 +82,13 @@ const WORKFLOW_CHUNK_SIZE = 100 */ const STALE_SCHEDULE_RECOVERY_NOTIFY_LIMIT = 25 const MAX_TICK_DURATION_MS = 3 * 60 * 1000 -const STALE_SCHEDULE_CLAIM_MS = getExecutionReservationTtlMs() +/** Lease for a schedule carrier that records neither its max duration nor its execution timeout. */ +const FALLBACK_SCHEDULE_EXECUTION_LEASE_MS = getExecutionReservationTtlMs() const STALE_SCHEDULE_RECOVERY_BATCH_SIZE = 100 const DATABASE_SCHEDULE_START_TURN_WAIT_MS = 1_000 type DatabaseScheduleStartResult = 'started' | 'capacity_full' | 'not_pending' let databaseScheduleStartTurn: Promise | null = null -const dueFilter = (queuedAt: Date) => - and( - isNull(workflowSchedule.archivedAt), - lte(workflowSchedule.nextRunAt, queuedAt), - sql`${workflowSchedule.status} NOT IN ('disabled', 'completed')`, - or( - isNull(workflowSchedule.lastQueuedAt), - lt(workflowSchedule.lastQueuedAt, workflowSchedule.nextRunAt), - lt(workflowSchedule.lastQueuedAt, new Date(queuedAt.getTime() - STALE_SCHEDULE_CLAIM_MS)) - ) - ) - -const activeWorkflowDeploymentFilter = () => - sql`${workflowSchedule.deploymentVersionId} = (select ${workflowDeploymentVersion.id} from ${workflowDeploymentVersion} where ${workflowDeploymentVersion.workflowId} = ${workflowSchedule.workflowId} and ${workflowDeploymentVersion.isActive} = true)` - -const workflowScheduleFilter = (queuedAt: Date) => - and( - dueFilter(queuedAt), - sql`(${workflowSchedule.sourceType} = 'workflow' OR ${workflowSchedule.sourceType} IS NULL)`, - activeWorkflowDeploymentFilter() - ) - async function runWithDatabaseScheduleStartTurn( operation: () => Promise ): Promise { @@ -160,63 +136,9 @@ function getNextRunFromCronExpression( return cron.nextRun() } -async function claimWorkflowSchedules(queuedAt: Date, limit: number) { - if (limit <= 0) return [] - - return db.transaction(async (tx) => { - const rows = await tx - .select({ - id: workflowSchedule.id, - workspaceId: workflow.workspaceId, - }) - .from(workflowSchedule) - .innerJoin(workflow, eq(workflowSchedule.workflowId, workflow.id)) - .where(workflowScheduleFilter(queuedAt)) - .for('update', { skipLocked: true }) - .limit(limit) - - if (rows.length === 0) return [] - const workspaceIdsByScheduleId = new Map(rows.map((row) => [row.id, row.workspaceId])) - - const claimedRows = await tx - .update(workflowSchedule) - .set({ lastQueuedAt: queuedAt, updatedAt: queuedAt }) - .where( - and( - workflowScheduleFilter(queuedAt), - inArray( - workflowSchedule.id, - rows.map((row) => row.id) - ) - ) - ) - .returning({ - id: workflowSchedule.id, - workflowId: workflowSchedule.workflowId, - blockId: workflowSchedule.blockId, - cronExpression: workflowSchedule.cronExpression, - lastRanAt: workflowSchedule.lastRanAt, - failedCount: workflowSchedule.failedCount, - infraRetryCount: workflowSchedule.infraRetryCount, - nextRunAt: workflowSchedule.nextRunAt, - lastQueuedAt: workflowSchedule.lastQueuedAt, - timezone: workflowSchedule.timezone, - deploymentVersionId: workflowSchedule.deploymentVersionId, - deploymentOperationId: workflowSchedule.deploymentOperationId, - sourceType: workflowSchedule.sourceType, - }) - - return claimedRows.map((row) => ({ - ...row, - workspaceId: workspaceIdsByScheduleId.get(row.id) ?? null, - })) - }) -} - -type ClaimedSchedule = Awaited>[number] type JobQueue = Awaited> type DatabaseScheduleExecutionTarget = Pick< - ClaimedSchedule, + ClaimedWorkflowSchedule, 'id' | 'workflowId' | 'cronExpression' | 'timezone' > type ScheduleRecoveryMetadata = Pick< @@ -402,7 +324,7 @@ function getScheduleExecutionLeaseMs( return payload.executionTimeoutMs + RESERVATION_TTL_BUFFER_MS } - return STALE_SCHEDULE_CLAIM_MS + return FALLBACK_SCHEDULE_EXECUTION_LEASE_MS } function isStaleScheduleClaim( @@ -456,7 +378,7 @@ function unreconciledTerminalScheduleExecutionJobsFilter() { } function staleScheduleExecutionJobsFilter(now: Date) { - const legacyMaxDurationSeconds = STALE_SCHEDULE_CLAIM_MS / 1000 + const legacyMaxDurationSeconds = FALLBACK_SCHEDULE_EXECUTION_LEASE_MS / 1000 const cleanupGraceSeconds = RESERVATION_TTL_BUFFER_MS / 1000 return and( activeScheduleExecutionJobsFilter(), @@ -801,7 +723,7 @@ async function reconcileExistingScheduleJob(params: { } async function deferClaimedScheduleAfterQueueFailure( - schedule: ClaimedSchedule, + schedule: ClaimedWorkflowSchedule, requestId: string, expectedLastQueuedAt: Date, error: unknown, @@ -853,7 +775,7 @@ async function deferClaimedScheduleAfterQueueFailure( } async function handleClaimedScheduleSetupFailure( - schedule: ClaimedSchedule, + schedule: ClaimedWorkflowSchedule, requestId: string, expectedLastQueuedAt: Date, error: unknown, @@ -1350,7 +1272,7 @@ async function resumePendingDatabaseScheduleJobs( } async function processScheduleItem( - schedule: ClaimedSchedule, + schedule: ClaimedWorkflowSchedule, queuedAt: Date, requestId: string, jobQueue: JobQueue, @@ -1608,8 +1530,8 @@ async function processScheduleItem( /** * The queue may have accepted the job before the response was lost, and * the job id is deterministic, so retrying could double-dispatch the - * occurrence. Leave the claim in place and let the next tick reconcile - * against whatever carrier actually exists. + * occurrence. Keep the claim: once it outlasts the claim recheck window, a + * tick re-claims the schedule and reconciles against whatever carrier exists. */ if (acceptance !== 'rejected') return await handleClaimedScheduleSetupFailure( @@ -1784,7 +1706,7 @@ export async function runScheduleTick(requestId: string): Promise + new Date(instant.getTime() - minutes * 60_000) + +/** One schedule per claim state the tick has to tell apart. */ +const scheduleIds = { + unclaimed: generateId(), + claimedForEarlierOccurrence: generateId(), + claimHeldPastRecheck: generateId(), + claimInFlight: generateId(), + claimRecheckedRecently: generateId(), + notYetDue: generateId(), +} + +const checks: { name: string; status: string; durationMs: number; error?: string }[] = [] + +function check(name: string, run: () => Promise) { + it(name, async () => { + const started = performance.now() + try { + await run() + checks.push({ name, status: 'passed', durationMs: performance.now() - started }) + } catch (error) { + checks.push({ + name, + status: 'failed', + durationMs: performance.now() - started, + error: getErrorMessage(error), + }) + throw error + } + }) +} + +beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: ownerId, + name: 'Schedule claim fixture', + email: `${ownerId}@schedule-claim.invalid`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await insertWorkspaceFixture(db, { + id: workspaceId, + ownerId, + billedAccountUserId: ownerId, + name: 'Schedule claim', + }) + await db.insert(workflow).values({ + id: workflowId, + workspaceId, + userId: ownerId, + name: 'Schedule claim fixture', + isDeployed: true, + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + await db.insert(workflowDeploymentVersion).values({ + id: liveVersionId, + workflowId, + version: 1, + isActive: true, + state: { blocks: {}, edges: [], loops: {}, parallels: {} }, + }) + + const schedule = ( + id: string, + nextRunAt: Date, + lastQueuedAt: Date | null, + updatedAt = minutesBefore(queuedAt, 2) + ) => ({ + id, + workflowId, + deploymentVersionId: liveVersionId, + blockId: id, + triggerType: 'schedule', + cronExpression: '*/5 * * * *', + timezone: 'UTC', + status: 'active', + failedCount: 0, + nextRunAt, + lastQueuedAt, + createdAt: occurrence, + updatedAt, + }) + await db + .insert(workflowSchedule) + .values([ + schedule(scheduleIds.unclaimed, occurrence, null), + schedule(scheduleIds.claimedForEarlierOccurrence, occurrence, minutesBefore(occurrence, 5)), + schedule( + scheduleIds.claimHeldPastRecheck, + occurrence, + minutesBefore(queuedAt, 11), + minutesBefore(queuedAt, 11) + ), + schedule(scheduleIds.claimInFlight, occurrence, minutesBefore(queuedAt, 2)), + schedule(scheduleIds.claimRecheckedRecently, occurrence, minutesBefore(queuedAt, 30)), + schedule(scheduleIds.notYetDue, minutesBefore(queuedAt, -1), null), + ]) +}) + +afterAll(async () => { + const reportPath = + process.env.SCHEDULE_CLAIM_REPORT_PATH ?? resolve('test-results/schedule-claim.json') + await mkdir(dirname(reportPath), { recursive: true }) + await writeFile(reportPath, JSON.stringify({ checks }, null, 2)) + await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId)) + await db.delete(user).where(eq(user.id, ownerId)) +}) + +check( + 'claims due schedules and re-examines a stale current-occurrence claim without replacing it', + async () => { + const claimed = await claimDueWorkflowSchedules(queuedAt, 100) + const claimById = new Map( + claimed.filter((row) => row.workflowId === workflowId).map((row) => [row.id, row]) + ) + + expect([...claimById.keys()].sort()).toEqual( + [ + scheduleIds.unclaimed, + scheduleIds.claimedForEarlierOccurrence, + scheduleIds.claimHeldPastRecheck, + ].sort() + ) + expect(claimById.get(scheduleIds.unclaimed)?.lastQueuedAt).toEqual(queuedAt) + expect(claimById.get(scheduleIds.claimedForEarlierOccurrence)?.lastQueuedAt).toEqual(queuedAt) + expect(claimById.get(scheduleIds.claimHeldPastRecheck)?.lastQueuedAt).toEqual( + minutesBefore(queuedAt, 11) + ) + + const rows = await db + .select({ + id: workflowSchedule.id, + lastQueuedAt: workflowSchedule.lastQueuedAt, + updatedAt: workflowSchedule.updatedAt, + }) + .from(workflowSchedule) + .where(inArray(workflowSchedule.id, Object.values(scheduleIds))) + const stored = new Map(rows.map((row) => [row.id, row])) + + expect(stored.get(scheduleIds.claimHeldPastRecheck)?.updatedAt).toEqual(queuedAt) + expect(stored.get(scheduleIds.claimInFlight)).toMatchObject({ + lastQueuedAt: minutesBefore(queuedAt, 2), + updatedAt: minutesBefore(queuedAt, 2), + }) + expect(stored.get(scheduleIds.claimRecheckedRecently)).toMatchObject({ + lastQueuedAt: minutesBefore(queuedAt, 30), + updatedAt: minutesBefore(queuedAt, 2), + }) + } +) diff --git a/apps/sim/lib/workflows/schedules/claim.ts b/apps/sim/lib/workflows/schedules/claim.ts new file mode 100644 index 00000000000..b70ff14c112 --- /dev/null +++ b/apps/sim/lib/workflows/schedules/claim.ts @@ -0,0 +1,101 @@ +import { db, workflow, workflowDeploymentVersion, workflowSchedule } from '@sim/db' +import { and, eq, inArray, isNull, lt, lte, or, sql } from 'drizzle-orm' + +/** + * How long a schedule may hold the claim on its current occurrence before a tick re-examines it. + * It has to outlast one tick's handoff; re-examining is safe because the tick resolves the + * occurrence through its carrier's deterministic job id rather than dispatching it again blindly. + */ +const SCHEDULE_CLAIM_RECHECK_MS = 10 * 60 * 1000 + +/** + * A claim held on the current occurrence (`lastQueuedAt >= nextRunAt`) is the run's identity: the + * worker's claim-guarded writes match it exactly, so a re-examination keeps it and moves only + * `updatedAt`, which serves as the re-check clock. + */ +const holdsCurrentOccurrenceClaim = sql`${workflowSchedule.lastQueuedAt} >= ${workflowSchedule.nextRunAt}` + +const dueFilter = (queuedAt: Date) => + and( + isNull(workflowSchedule.archivedAt), + lte(workflowSchedule.nextRunAt, queuedAt), + sql`${workflowSchedule.status} NOT IN ('disabled', 'completed')`, + or( + isNull(workflowSchedule.lastQueuedAt), + lt(workflowSchedule.lastQueuedAt, workflowSchedule.nextRunAt), + lt(workflowSchedule.updatedAt, new Date(queuedAt.getTime() - SCHEDULE_CLAIM_RECHECK_MS)) + ) + ) + +const activeWorkflowDeploymentFilter = () => + sql`${workflowSchedule.deploymentVersionId} = (select ${workflowDeploymentVersion.id} from ${workflowDeploymentVersion} where ${workflowDeploymentVersion.workflowId} = ${workflowSchedule.workflowId} and ${workflowDeploymentVersion.isActive} = true)` + +const workflowScheduleFilter = (queuedAt: Date) => + and( + dueFilter(queuedAt), + sql`(${workflowSchedule.sourceType} = 'workflow' OR ${workflowSchedule.sourceType} IS NULL)`, + activeWorkflowDeploymentFilter() + ) + +/** + * Claims up to `limit` due workflow schedules on their live deployment, including any whose claim + * on the current occurrence has gone {@link SCHEDULE_CLAIM_RECHECK_MS} without a re-examination. + * Concurrent ticks skip each other's locked rows. + */ +export async function claimDueWorkflowSchedules(queuedAt: Date, limit: number) { + if (limit <= 0) return [] + + return db.transaction(async (tx) => { + const rows = await tx + .select({ + id: workflowSchedule.id, + workspaceId: workflow.workspaceId, + }) + .from(workflowSchedule) + .innerJoin(workflow, eq(workflowSchedule.workflowId, workflow.id)) + .where(workflowScheduleFilter(queuedAt)) + .for('update', { skipLocked: true }) + .limit(limit) + + if (rows.length === 0) return [] + const workspaceIdsByScheduleId = new Map(rows.map((row) => [row.id, row.workspaceId])) + + const claimedRows = await tx + .update(workflowSchedule) + .set({ + lastQueuedAt: sql`CASE WHEN ${holdsCurrentOccurrenceClaim} THEN ${workflowSchedule.lastQueuedAt} ELSE ${sql.param(queuedAt, workflowSchedule.lastQueuedAt)} END`, + updatedAt: queuedAt, + }) + .where( + and( + workflowScheduleFilter(queuedAt), + inArray( + workflowSchedule.id, + rows.map((row) => row.id) + ) + ) + ) + .returning({ + id: workflowSchedule.id, + workflowId: workflowSchedule.workflowId, + blockId: workflowSchedule.blockId, + cronExpression: workflowSchedule.cronExpression, + lastRanAt: workflowSchedule.lastRanAt, + failedCount: workflowSchedule.failedCount, + infraRetryCount: workflowSchedule.infraRetryCount, + nextRunAt: workflowSchedule.nextRunAt, + lastQueuedAt: workflowSchedule.lastQueuedAt, + timezone: workflowSchedule.timezone, + deploymentVersionId: workflowSchedule.deploymentVersionId, + deploymentOperationId: workflowSchedule.deploymentOperationId, + sourceType: workflowSchedule.sourceType, + }) + + return claimedRows.map((row) => ({ + ...row, + workspaceId: workspaceIdsByScheduleId.get(row.id) ?? null, + })) + }) +} + +export type ClaimedWorkflowSchedule = Awaited>[number]