@mastra/core
Version:
1 lines • 31 kB
Source Map (JSON)
{"version":3,"file":"scheduler-C-nOBraJ.cjs","names":["MastraBase","RegisteredLogger","computeNextFire"],"sources":["../src/workflows/scheduler/scheduler.ts"],"sourcesContent":["import { MastraBase } from '../../base';\nimport type { PubSub } from '../../events/pubsub';\nimport { RegisteredLogger } from '../../logger/constants';\nimport type { Schedule, ScheduleTrigger, SchedulesStorage } from '../../storage/domains/schedules/base';\nimport { computeNextFire } from './cron';\nimport type { ScheduledWorkflowTrigger, SchedulerConfig } from './types';\n\nconst TOPIC_WORKFLOWS = 'workflows';\nexport const TOPIC_AGENT_SCHEDULES = 'agent-schedules';\nconst DEFAULT_TICK_INTERVAL_MS = 10_000;\nconst DEFAULT_BATCH_SIZE = 100;\nconst DEFAULT_MISSES_BEFORE_DELETE = 3;\nconst DEFAULT_STALE_SKIPS_BEFORE_ESCALATION = 5;\n/** Longest delay `setTimeout` accepts; larger values fire immediately. */\nconst MAX_TIMER_DELAY_MS = 2 ** 31 - 1;\n\n/**\n * Drives cron-based workflow triggers.\n *\n * On each tick the scheduler:\n * 1. Loads schedules whose `nextFireAt <= now` from storage.\n * 2. Computes the next fire time from the cron expression.\n * 3. Atomically advances `nextFireAt` via compare-and-swap. Only one\n * instance across many polling the same storage can claim a fire.\n * 4. Publishes a `workflow.start` event on the `workflows` pubsub topic.\n * 5. Records the trigger in the schedule's history.\n *\n * The scheduler does **not** execute workflows. The existing\n * `WorkflowEventProcessor` consumes `workflow.start` events and runs them.\n */\nexport class Scheduler extends MastraBase {\n #schedulesStore: SchedulesStorage;\n #pubsub: PubSub;\n #config: Required<Pick<SchedulerConfig, 'tickIntervalMs' | 'batchSize'>> & SchedulerConfig;\n\n #timerHandle?: ReturnType<typeof setTimeout>;\n #inflightTick?: Promise<void>;\n #loop?: Promise<void>;\n #wakeRequested = false;\n /** Whether the last tick saw due schedules, or failed to list them. */\n #lastTickBusy = false;\n #started = false;\n #stopping = false;\n\n /**\n * Per-schedule count of consecutive ticks where the target workflow was\n * not registered with the host Mastra instance. Reset when the workflow\n * resolves or the schedule is deleted. Used to ride out deploy/startup\n * ordering races before reclaiming a ghost row.\n */\n #missingWorkflowCounts = new Map<string, number>();\n\n /**\n * Consecutive ticks each schedule has been skipped because the local target\n * definition is stale (see `#ensureTargetCurrent`). Doubles as the\n * \"already logged\" marker so a straggler doesn't re-log every tick, and as\n * the counter that escalates a skip that is never being picked up by anyone.\n *\n * Scoped to the fire window (`nextFireAt`) the skips were observed against.\n * A window that advances is proof some other instance claimed and fired the\n * previous one, so the count restarts rather than accumulating across\n * unrelated fires — otherwise a long-lived straggler would escalate even\n * though every fire is being served correctly by a current-build instance.\n */\n #staleDefinitionCounts = new Map<string, { fireAt: number; count: number }>();\n\n constructor({\n schedulesStore,\n pubsub,\n config,\n }: {\n schedulesStore: SchedulesStorage;\n pubsub: PubSub;\n config?: SchedulerConfig;\n }) {\n super({ component: RegisteredLogger.WORKFLOW, name: 'Scheduler' });\n this.#schedulesStore = schedulesStore;\n this.#pubsub = pubsub;\n this.#config = {\n ...config,\n tickIntervalMs: config?.tickIntervalMs ?? DEFAULT_TICK_INTERVAL_MS,\n batchSize: config?.batchSize ?? DEFAULT_BATCH_SIZE,\n };\n }\n\n /** Start the tick loop. Runs an immediate tick first. */\n async start(): Promise<void> {\n if (this.#started) return;\n this.#started = true;\n this.#stopping = false;\n // Fresh process / fresh grace window — old miss counts shouldn't carry\n // over into a new start() since the workflow registry may now look\n // different.\n this.#missingWorkflowCounts.clear();\n this.#staleDefinitionCounts.clear();\n\n try {\n // Run one tick immediately so newly-due schedules don't wait, then arm\n // the timer for the next one.\n this.#wakeRequested = true;\n await this.#runLoop();\n } catch (err) {\n // Reset state so a future start() can retry. Without this, a failed\n // warm-up tick would leave #started=true with no timer armed and\n // every subsequent start() call would silently no-op.\n this.#started = false;\n this.#stopping = false;\n throw err;\n }\n }\n\n /** Stop the tick loop and wait for any in-flight tick to finish. */\n async stop(): Promise<void> {\n if (!this.#started) return;\n this.#stopping = true;\n\n this.#clearTimer();\n\n if (this.#loop) {\n try {\n await this.#loop;\n } catch {\n // tick errors are already logged; swallow during shutdown\n }\n }\n if (this.#inflightTick) {\n try {\n await this.#inflightTick;\n } catch {\n // tick errors are already logged; swallow during shutdown\n }\n }\n\n this.#started = false;\n this.#stopping = false;\n }\n\n /** True when the scheduler is currently running its tick loop. */\n get isRunning(): boolean {\n return this.#started;\n }\n\n /**\n * Run a single tick. Public for tests; production callers should rely\n * on the timer started by `start()`.\n */\n async tick(): Promise<void> {\n await this.#runTick();\n }\n\n /**\n * Tick now and re-arm the timer. Call when a schedule was created, resumed\n * or moved earlier, since the scheduler may be sleeping until a later fire.\n */\n wake(): void {\n if (!this.#started || this.#stopping) return;\n this.#wakeRequested = true;\n if (this.#loop) return;\n this.#clearTimer();\n // Swallow rejections so a tick failure can't surface as an unhandled\n // rejection and crash the host process. #processTick already logs its\n // own errors; this is a belt-and-braces log for anything that escapes.\n void this.#runLoop().catch(err => {\n this.logger.error('Scheduler tick crashed', { error: err });\n });\n }\n\n // -------- Internals --------\n\n /**\n * Tick, then sleep until the earliest active schedule is due instead of\n * polling storage on a fixed interval. A wake that lands mid-loop ticks\n * again before the timer is armed.\n */\n #runLoop(): Promise<void> {\n const loop = this.#loopOnce().finally(() => {\n if (this.#loop === loop) this.#loop = undefined;\n });\n this.#loop = loop;\n return loop;\n }\n\n async #loopOnce(): Promise<void> {\n let delay: number | undefined;\n do {\n this.#wakeRequested = false;\n try {\n await this.#runTick();\n } catch (err) {\n // A crashed tick must not stop the scheduler: retry at the tick interval.\n this.logger.error('Scheduler tick crashed', { error: err });\n this.#lastTickBusy = true;\n }\n if (this.#stopping || !this.#started) return;\n delay = await this.#nextDelay();\n } while (this.#wakeRequested && !this.#stopping && this.#started);\n if (this.#stopping || !this.#started) return;\n\n this.#clearTimer();\n // No active schedules: stay idle until `wake()`.\n if (delay === undefined) return;\n this.#timerHandle = setTimeout(() => {\n this.#timerHandle = undefined;\n this.wake();\n }, delay);\n // Don't keep the process alive solely because it has active schedules.\n // Optional call: on runtimes where setTimeout returns a number\n // (e.g. Cloudflare Workers) there is no unref and nothing to release.\n this.#timerHandle.unref?.();\n }\n\n /**\n * How long to sleep before the next tick. Keeps the fixed interval while\n * schedules are due (fires, retries, skipped targets), on storage errors,\n * and for a scheduler explicitly enabled with `enabled: true` (a dedicated\n * scheduler that must find rows written by processes it shares no pubsub\n * with). Otherwise waits for the earliest active `nextFireAt` and relies on\n * `wake()` for new schedules; with no active schedules it returns undefined\n * and no timer is armed, so an idle app never touches storage.\n */\n async #nextDelay(): Promise<number | undefined> {\n const interval = this.#config.tickIntervalMs;\n if (this.#config.enabled === true || this.#lastTickBusy) return interval;\n let next: Schedule[];\n try {\n // Every adapter returns due rows ordered by nextFireAt, so asking for one\n // row with an unbounded `now` is a bounded earliest-fire lookup.\n next = await this.#schedulesStore.listDueSchedules(Number.MAX_SAFE_INTEGER, 1);\n } catch (err) {\n this.logger.error('Failed to look up the next scheduled fire', { error: err });\n return interval;\n }\n if (next.length === 0) return undefined;\n return Math.max(interval, Math.min(next[0]!.nextFireAt - Date.now(), MAX_TIMER_DELAY_MS));\n }\n\n #clearTimer(): void {\n if (this.#timerHandle) {\n clearTimeout(this.#timerHandle);\n this.#timerHandle = undefined;\n }\n }\n\n async #runTick(): Promise<void> {\n if (this.#stopping || this.#inflightTick) return;\n const promise = this.#processTick().finally(() => {\n this.#inflightTick = undefined;\n });\n this.#inflightTick = promise;\n await promise;\n }\n\n async #processTick(): Promise<void> {\n let due: Schedule[];\n this.#lastTickBusy = true;\n try {\n due = await this.#schedulesStore.listDueSchedules(Date.now(), this.#config.batchSize);\n } catch (err) {\n this.logger.error('Failed to list due schedules', { error: err });\n return;\n }\n this.#lastTickBusy = due.length > 0;\n\n for (const schedule of due) {\n if (this.#stopping) break;\n await this.#fireSchedule(schedule);\n }\n }\n\n /**\n * Check whether a schedule's target is registered with the host\n * Mastra instance. Returns `true` if no predicate is configured (we can't\n * verify, so assume the consumer will reject) or if the target resolves.\n *\n * When the target is missing, we increment an in-memory counter and\n * delete the schedule after `missesBeforeDelete` consecutive misses. The\n * grace window protects against deploy/startup ordering races where the\n * scheduler ticks before workflows/agents finish registering on a fresh\n * process. Returns `false` to tell `#fireSchedule` to skip publishing for\n * this tick.\n */\n async #ensureTargetReady(schedule: Schedule): Promise<boolean> {\n const predicate = this.#config.isTargetReady;\n if (!predicate) return true;\n\n if (await predicate(schedule.target)) {\n this.#missingWorkflowCounts.delete(schedule.id);\n return true;\n }\n\n const targetSummary =\n schedule.target.type === 'workflow'\n ? { workflowId: schedule.target.workflowId }\n : { agentId: schedule.target.agentId };\n\n const limit = this.#config.missesBeforeDelete ?? DEFAULT_MISSES_BEFORE_DELETE;\n const prev = this.#missingWorkflowCounts.get(schedule.id) ?? 0;\n const next = prev + 1;\n\n if (next < limit) {\n this.#missingWorkflowCounts.set(schedule.id, next);\n if (prev === 0) {\n this.logger.warn('Schedule target is not registered; skipping until it appears', {\n scheduleId: schedule.id,\n targetType: schedule.target.type,\n ...targetSummary,\n missesBeforeDelete: limit,\n });\n }\n return false;\n }\n\n // Hit the grace limit — reclaim the row.\n this.logger.error('Deleting schedule whose target has not been registered', {\n scheduleId: schedule.id,\n targetType: schedule.target.type,\n ...targetSummary,\n consecutiveMisses: next,\n });\n try {\n await this.#schedulesStore.deleteSchedule(schedule.id);\n } catch (err) {\n this.logger.error('Failed to delete ghost schedule', {\n scheduleId: schedule.id,\n targetType: schedule.target.type,\n ...targetSummary,\n error: err,\n });\n // Keep the counter so we try again next tick rather than reset and\n // start the grace window over.\n return false;\n }\n this.#missingWorkflowCounts.delete(schedule.id);\n return false;\n }\n\n /**\n * Stale-build fence (#19169). Scheduled runs execute `localOnly` in the\n * claiming process against its own workflow registry, so an instance whose\n * local target definition differs from the one recorded on the schedule\n * row must not claim the fire — it would silently run an outdated step\n * graph. Returning `false` skips the CAS claim entirely, leaving\n * `nextFireAt` untouched so an instance with a matching definition can\n * claim the fire on its own tick.\n *\n * Fails open when no predicate is configured or when the predicate\n * throws — fencing is a safety net, not a reason to stop firing.\n */\n #ensureTargetCurrent(schedule: Schedule): boolean {\n const predicate = this.#config.isTargetCurrent;\n if (!predicate) return true;\n\n let current: boolean;\n try {\n current = predicate(schedule.target);\n } catch (err) {\n this.logger.error('isTargetCurrent predicate threw; treating target as current', {\n scheduleId: schedule.id,\n error: err,\n });\n return true;\n }\n\n if (current) {\n this.#staleDefinitionCounts.delete(schedule.id);\n return true;\n }\n\n // Only count skips against the same unclaimed fire window. If `nextFireAt`\n // has moved on, an instance with a matching definition claimed the last\n // fire and this is a fresh window, not a continuing stall.\n const prevEntry = this.#staleDefinitionCounts.get(schedule.id);\n const prev = prevEntry?.fireAt === schedule.nextFireAt ? prevEntry.count : 0;\n const next = prev + 1;\n this.#staleDefinitionCounts.set(schedule.id, { fireAt: schedule.nextFireAt, count: next });\n\n const targetSummary =\n schedule.target.type === 'workflow'\n ? { workflowId: schedule.target.workflowId }\n : { agentId: schedule.target.agentId };\n const limit = this.#config.staleSkipsBeforeEscalation ?? DEFAULT_STALE_SKIPS_BEFORE_ESCALATION;\n\n if (prev === 0) {\n this.logger.warn(\n 'Local target definition differs from the schedule row; leaving fire for an instance running the current build',\n { scheduleId: schedule.id, targetType: schedule.target.type, ...targetSummary },\n );\n } else if (next === limit) {\n // Nobody has claimed this fire for `limit` consecutive ticks, which\n // means no running instance matches the row (bad rollout, or a hash the\n // reconciler wrote that no build reproduces). We deliberately do NOT\n // force the fire — running a stale graph is the bug this fence exists to\n // prevent — but a schedule that silently never runs is just as bad, so\n // escalate to an alertable error and leave a trail in schedule history.\n this.logger.error(\n 'Schedule has been skipped repeatedly because no local target definition matches the schedule row; it will not fire until an instance running the recorded build is available',\n { scheduleId: schedule.id, targetType: schedule.target.type, ...targetSummary, consecutiveStaleSkips: next },\n );\n void this.#recordStaleSkip(schedule, next);\n }\n\n return false;\n }\n\n /**\n * Best-effort history entry for an escalated stale skip so the stall is\n * visible to anyone inspecting the schedule, not just in process logs.\n */\n async #recordStaleSkip(schedule: Schedule, consecutiveStaleSkips: number): Promise<void> {\n try {\n await this.#schedulesStore.recordTrigger({\n scheduleId: schedule.id,\n runId: `sched_${schedule.id}_${schedule.nextFireAt}`,\n scheduledFireAt: schedule.nextFireAt,\n actualFireAt: Date.now(),\n outcome: 'failed',\n error: `Skipped: no local target definition matches the schedule row after ${consecutiveStaleSkips} consecutive ticks`,\n triggerKind: 'schedule-fire',\n });\n } catch (err) {\n this.logger.warn('Failed to record stale-definition skip', { scheduleId: schedule.id, error: err });\n }\n }\n\n async #fireSchedule(schedule: Schedule): Promise<void> {\n if (!(await this.#ensureTargetReady(schedule))) return;\n if (!this.#ensureTargetCurrent(schedule)) return;\n\n const actualFireAt = Date.now();\n\n let newNextFireAt: number;\n let completed: boolean;\n try {\n ({ nextFireAt: newNextFireAt, completed } = computeNextFire(schedule, actualFireAt));\n } catch (err) {\n this.logger.error('Failed to compute next fire time for schedule', {\n scheduleId: schedule.id,\n cron: schedule.cron,\n error: err,\n });\n this.#notifyError(err, schedule.id);\n return;\n }\n\n // Deterministic runId so concurrent ticks across processes derive the same id.\n const runId = `sched_${schedule.id}_${schedule.nextFireAt}`;\n\n let claimed = false;\n try {\n claimed = await this.#schedulesStore.updateScheduleNextFire(\n schedule.id,\n schedule.nextFireAt,\n newNextFireAt,\n actualFireAt,\n runId,\n completed ? 'completed' : undefined,\n );\n } catch (err) {\n this.logger.error('Failed to claim due schedule fire', {\n scheduleId: schedule.id,\n runId,\n error: err,\n });\n this.#notifyError(err, schedule.id);\n return;\n }\n\n if (!claimed) {\n // Another instance won the race, the row was paused/disabled, or the\n // expected nextFireAt no longer matches. Skip publishing.\n return;\n }\n\n this.logger.info('Claimed schedule occurrence', {\n scheduleId: schedule.id,\n runId,\n scheduledFireAt: schedule.nextFireAt,\n });\n\n let triggerStatus: ScheduleTrigger['outcome'] = 'published';\n let triggerError: string | undefined;\n\n try {\n for (let attempt = 0; attempt < 3; attempt++) {\n try {\n await this.#publishTargetStart(schedule, runId);\n break;\n } catch (err) {\n if (attempt === 2) throw err;\n await new Promise(resolve => setTimeout(resolve, 100 * 2 ** attempt));\n }\n }\n this.logger.info('Published schedule occurrence', {\n scheduleId: schedule.id,\n runId,\n scheduledFireAt: schedule.nextFireAt,\n });\n } catch (err) {\n triggerStatus = 'failed';\n triggerError = err instanceof Error ? err.message : String(err);\n this.logger.error('Failed to publish target.start for schedule', {\n scheduleId: schedule.id,\n runId,\n targetType: schedule.target.type,\n scheduledFireAt: schedule.nextFireAt,\n publicationOutcome: 'unknown',\n automaticReplay: false,\n error: err,\n });\n this.#notifyError(err, schedule.id);\n }\n\n // For workflow targets we record the trigger now with the claim id —\n // the workflow event processor will reuse the same runId. For\n // agent targets the AgentScheduleWorker records the trigger itself\n // after the agent run starts, so it can write the real agent runId.\n if (schedule.target.type === 'workflow' || triggerStatus === 'failed') {\n try {\n await this.#schedulesStore.recordTrigger({\n scheduleId: schedule.id,\n runId,\n scheduledFireAt: schedule.nextFireAt,\n actualFireAt,\n outcome: triggerStatus,\n error: triggerError,\n triggerKind: 'schedule-fire',\n });\n } catch (err) {\n this.logger.error('Failed to record schedule trigger', {\n scheduleId: schedule.id,\n runId,\n error: err,\n });\n }\n }\n }\n\n /**\n * Invoke the user-supplied onError hook in isolation. A throwing hook\n * must not abort the scheduler tick loop, so we swallow + log any error\n * the callback itself raises.\n */\n #notifyError(error: unknown, scheduleId: string): void {\n if (!this.#config.onError) return;\n try {\n this.#config.onError(error, { scheduleId });\n } catch (callbackError) {\n this.logger.error('Scheduler onError handler threw', {\n scheduleId,\n error: callbackError,\n });\n }\n }\n\n async #publishTargetStart(schedule: Schedule, claimId: string): Promise<void> {\n switch (schedule.target.type) {\n case 'workflow': {\n const { workflowId, inputData, initialState, requestContext, resourceId, definitionHash } = schedule.target;\n // Claim/execute affinity (#19169). When this process also consumes\n // workflow events, keep the fire local so the instance that proved\n // the target ready and current is the one that runs it. A\n // scheduler-only process has no local consumer, so it must publish\n // to the shared topic — the `scheduleDefinitionHash` below is what\n // protects that hop, letting a stale consumer refuse the fire\n // instead of executing its own outdated graph.\n const localOnly = this.#config.canExecuteLocally?.() === true;\n await this.#pubsub.publish(\n TOPIC_WORKFLOWS,\n {\n type: 'workflow.start',\n runId: claimId,\n data: {\n workflowId,\n runId: claimId,\n prevResult: { status: 'success', output: inputData ?? {} },\n requestContext: requestContext ?? {},\n initialState: initialState ?? {},\n ...(resourceId ? { resourceId } : {}),\n // Only stamped when the row carries a hash, so legacy and\n // imperative schedules stay unfenced (fail open).\n ...(definitionHash ? { scheduleDefinitionHash: definitionHash } : {}),\n scheduleTrigger: {\n scheduleId: schedule.id,\n scheduledFireAt: schedule.nextFireAt,\n triggerKind: 'schedule-fire',\n } satisfies ScheduledWorkflowTrigger,\n },\n },\n localOnly ? { localOnly: true } : undefined,\n );\n return;\n }\n case 'agent': {\n await this.#pubsub.publish(TOPIC_AGENT_SCHEDULES, {\n type: 'agent-schedule.fire',\n runId: claimId,\n data: {\n scheduleId: schedule.id,\n claimId,\n scheduledFireAt: schedule.nextFireAt,\n target: schedule.target,\n ...(schedule.runAt != null ? { oneOff: true } : {}),\n },\n });\n return;\n }\n default: {\n throw new Error(`Unsupported schedule target type: ${(schedule.target as { type: string }).type}`);\n }\n }\n }\n}\n\n/**\n * @deprecated Renamed to {@link Scheduler}. The scheduler now drives both\n * workflow and agent schedules, so the `Workflow`-prefixed name is no longer\n * accurate. This alias will be removed in a future major release.\n */\nexport const WorkflowScheduler = Scheduler;\n\n/**\n * @deprecated Renamed to {@link Scheduler}. This alias will be removed in a\n * future major release.\n */\nexport type WorkflowScheduler = Scheduler;\n"],"mappings":";;;;AAOA,MAAM,kBAAkB;AACxB,MAAa,wBAAwB;AACrC,MAAM,2BAA2B;AACjC,MAAM,qBAAqB;AAC3B,MAAM,+BAA+B;AACrC,MAAM,wCAAwC;;AAE9C,MAAM,qBAAqB,KAAK,KAAK;;;;;;;;;;;;;;;AAg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