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
112 changes: 17 additions & 95 deletions apps/sim/app/api/schedules/execute/route.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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'
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<void> | 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<DatabaseScheduleStartResult>
): Promise<DatabaseScheduleStartResult> {
Expand Down Expand Up @@ -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<ReturnType<typeof claimWorkflowSchedules>>[number]
type JobQueue = Awaited<ReturnType<typeof getJobQueue>>
type DatabaseScheduleExecutionTarget = Pick<
ClaimedSchedule,
ClaimedWorkflowSchedule,
'id' | 'workflowId' | 'cronExpression' | 'timezone'
>
type ScheduleRecoveryMetadata = Pick<
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -801,7 +723,7 @@ async function reconcileExistingScheduleJob(params: {
}

async function deferClaimedScheduleAfterQueueFailure(
schedule: ClaimedSchedule,
schedule: ClaimedWorkflowSchedule,
requestId: string,
expectedLastQueuedAt: Date,
error: unknown,
Expand Down Expand Up @@ -853,7 +775,7 @@ async function deferClaimedScheduleAfterQueueFailure(
}

async function handleClaimedScheduleSetupFailure(
schedule: ClaimedSchedule,
schedule: ClaimedWorkflowSchedule,
requestId: string,
expectedLastQueuedAt: Date,
error: unknown,
Expand Down Expand Up @@ -1350,7 +1272,7 @@ async function resumePendingDatabaseScheduleJobs(
}

async function processScheduleItem(
schedule: ClaimedSchedule,
schedule: ClaimedWorkflowSchedule,
queuedAt: Date,
requestId: string,
jobQueue: JobQueue,
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -1784,7 +1706,7 @@ export async function runScheduleTick(requestId: string): Promise<ScheduleTickRe

const dueSchedules = schedulesExhausted
? []
: await claimWorkflowSchedules(queuedAt, workflowClaimLimit)
: await claimDueWorkflowSchedules(queuedAt, workflowClaimLimit)

remainingWorkflowBudget -= dueSchedules.length
if (dueSchedules.length < workflowClaimLimit || remainingWorkflowBudget <= 0) {
Expand Down
4 changes: 2 additions & 2 deletions apps/sim/background/schedule-execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1268,8 +1268,8 @@ export async function executeScheduleJob(
)
} catch (recoveryError: unknown) {
// A secondary failure during error recovery (e.g. a transient DB blip while
// releasing the claim or scheduling an infra retry) must not fault the run. The
// claim expires on its TTL and the next tick re-claims the schedule. Record the
// releasing the claim or scheduling an infra retry) must not fault the run. A
// tick re-examines the held claim after the claim recheck window. Record the
// exception on the span so it stays visible in traces without faulting the run.
logger.error(
`Failed to recover schedule ${payload.scheduleId} after error`,
Expand Down
180 changes: 180 additions & 0 deletions apps/sim/lib/workflows/schedules/claim.integration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import { mkdir, writeFile } from 'node:fs/promises'
import { dirname, resolve } from 'node:path'
import { db } from '@sim/db'
import {
user,
workflow,
workflowDeploymentVersion,
workflowSchedule,
workspace,
} from '@sim/db/schema'
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { eq, inArray } from 'drizzle-orm'
import { afterAll, beforeAll, expect, it } from 'vitest'
import { claimDueWorkflowSchedules } from '@/lib/workflows/schedules/claim'

const ownerId = generateId()
const workspaceId = generateId()
const workflowId = generateId()
const liveVersionId = generateId()

/** Far in the past, so no other suite's schedule is due at this instant. */
const occurrence = new Date('2001-01-01T00:00:00.000Z')
const queuedAt = new Date('2001-01-01T01:00:00.000Z')
const minutesBefore = (instant: Date, minutes: number) =>
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<void>) {
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),
})
}
)
Loading
Loading