Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(control-api): skip scheduled ticks under Forbid while a run is live

Jose Ramirez025573b2e0aa
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 092d6afee..e202849e8 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.738",
+ "version": "0.1.739",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.738",
+ "version": "0.1.739",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index 2b01bf382..38771b118 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.738",
+ "version": "0.1.739",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/observability/metrics.ts b/control-api/src/observability/metrics.ts
index 21c338f14..b7bd9d2ba 100644
--- a/control-api/src/observability/metrics.ts
+++ b/control-api/src/observability/metrics.ts
@@ -399,7 +399,13 @@ export const workflowScheduleWorkerRunsTotal = getOrCreateCounter({
export const workflowScheduleWorkerFiresTotal = getOrCreateCounter({
name: 'wrc_schedule_worker_fires_total',
help: 'Count of individual schedule fires translated into workflow_runs rows.',
- labelNames: ['result'] as const as Array<'result'>, // ok | error
+ labelNames: ['result'] as const as Array<'result'>, // ok | error | actor_not_allowed | concurrency_forbidden
+})
+
+export const workflowScheduleWorkerConcurrencyForbiddenSustainedTotal = getOrCreateCounter({
+ name: 'wrc_schedule_worker_concurrency_forbidden_sustained_total',
+ help: 'Schedules that reached the sustained consecutive-skip threshold under concurrencyPolicy Forbid (once per streak).',
+ labelNames: [] as string[],
})
export const workflowScheduleWorkerDurationSeconds = getOrCreateHistogram({
diff --git a/control-api/src/services/workflowScheduleWorkerService.ts b/control-api/src/services/workflowScheduleWorkerService.ts
index 3136cc53d..e930261f6 100644
--- a/control-api/src/services/workflowScheduleWorkerService.ts
+++ b/control-api/src/services/workflowScheduleWorkerService.ts
@@ -9,6 +9,9 @@
* 2. Drain matured rows from `workflow_schedules` (`enabled = true AND next_fire_at <= now()`),
* using `FOR UPDATE SKIP LOCKED` as defense-in-depth against manual re-entry.
* 3. For each matured row:
+ * 0. Apply the policy gates in order: `allowed_actors`, then
+ * `concurrency_policy` (see "Concurrency policy" below). A gated tick
+ * advances `next_fire_at` without creating a run.
* a. Insert a workflow_runs row via workflowRunService.createRun()
* with actor_type='scheduled' and a deterministic idempotency_key
* so double-firing the same window is a no-op.
@@ -28,12 +31,42 @@
* The unique index `idx_wr_idempotency (recipe_namespace, recipe_name, idempotency_key)`
* converts a double-fire (same schedule, same window) into a silent ON CONFLICT DO NOTHING.
* The existing workflow_runs row is returned and the schedule still advances.
+ *
+ * Concurrency policy (`workflow_schedules.concurrency_policy`, mirrored by the
+ * WRC from `spec.triggers.schedule.concurrencyPolicy`; CRD default `Forbid`):
+ * • Forbid: a matured tick is skipped while a LIVE non-terminal run of the
+ * same recipe exists, whatever its trigger source. Live means
+ * - `Pending` created less than FORBID_PENDING_ACTIVE_BOUND_SECONDS ago, or
+ * - `Running` started less than
+ * min(max_duration_seconds ?? cap, cap) + FORBID_RUNNING_GRACE_SECONDS
+ * ago, with cap = FORBID_RUNNING_MAX_DURATION_CAP_SECONDS.
+ * Nothing terminalises a `Pending` row whose child CR never got created,
+ * and the WRC only reaps `Running` rows that carry max_duration_seconds, so
+ * without these bounds one stuck row would block the schedule forever.
+ * Past the bound the row no longer blocks (a liveness escape hatch: a stuck
+ * but unreaped run can then overlap one new run).
+ * The skip is recorded (result reason `concurrency_forbidden`, metric
+ * label, info log with the blocking run id and age) and `next_fire_at`
+ * advances to the first window after max(next_fire_at, now), so skipped
+ * windows are dropped, never replayed as a burst. After
+ * FORBID_SUSTAINED_SKIP_THRESHOLD consecutive skips of one schedule a warn
+ * log and a counter fire once per streak (in-memory, see
+ * `forbiddenSkipStreaks`). A NULL / unknown policy is treated as Forbid.
+ * • Allow: no check; runs may overlap (the pre-existing behaviour).
+ * • Replace: NOT implemented. It behaves exactly like Allow.
+ * Consistency: the active-run check and the run INSERT execute on the same
+ * client inside the batch transaction, while this session holds the
+ * cluster-wide advisory lock and the schedule row is locked FOR UPDATE, so
+ * two replicas cannot both pass the check for one schedule. Other trigger
+ * paths (on-demand, autonomous) do not take this lock: a run they commit
+ * after the check is not seen. Forbid gates scheduled fires only.
*/
import { CronExpressionParser } from 'cron-parser'
import type { DbClient } from '../db.js'
import { pool } from '../db.js'
import { rootLogger } from '../observability/logger.js'
import {
+ workflowScheduleWorkerConcurrencyForbiddenSustainedTotal,
workflowScheduleWorkerDurationSeconds,
workflowScheduleWorkerFiresTotal,
workflowScheduleWorkerRunsTotal,
@@ -51,6 +84,67 @@ const DEFAULT_BATCH_SIZE = 50
type TriggerAllowedActor = 'user' | 'autonomous' | 'scheduled'
+/** Mirrors `spec.triggers.schedule.concurrencyPolicy`; CHECK-constrained in the DB. */
+type ScheduleConcurrencyPolicy = 'Forbid' | 'Replace' | 'Allow'
+
+/**
+ * A `Pending` run blocks a Forbid schedule only while it is younger than this.
+ * The WRC claims Pending rows on NOTIFY and re-polls orphans every
+ * `WRC_RUN_POLL_MS` (30 s default, workflow-recipes/src/config.ts), reclaiming
+ * rows idle for 1 min (dbRunProcessor FIND_ORPHAN_RUNS). 15 min is ~30 poll
+ * cycles, far beyond a healthy claim, yet lets a five-minute schedule
+ * recover within three windows when createChildRecipe keeps failing and
+ * nothing ever moves the row out of Pending.
+ */
+export const FORBID_PENDING_ACTIVE_BOUND_SECONDS = 15 * 60
+
+/**
+ * Ceiling on a `Running` run's own max_duration_seconds, and the value used
+ * when it is NULL. Equals the WRC's hard limit on
+ * `spec.runRetention.maxRunDurationSeconds` (workflow-recipes/src/config.ts
+ * DEFAULT_WORKFLOW_MAX_RUN_DURATION_SECONDS, enforced in workflowLimits.ts;
+ * the env override can only lower it). The CRD default (604800) is above it,
+ * hence the clamp.
+ */
+export const FORBID_RUNNING_MAX_DURATION_CAP_SECONDS = 24 * 60 * 60
+
+/**
+ * Slack after a `Running` run's deadline before it stops blocking. The WRC
+ * reaper (checkStuckRuns) runs every WRC_RUN_POLL_MS and only fails runs owned
+ * by its own instance, so a run whose owner died must first be reclaimed by
+ * the 1-min orphan sweep. 5 min = 10 poll cycles covers that handover.
+ */
+export const FORBID_RUNNING_GRACE_SECONDS = 5 * 60
+
+/** Consecutive Forbid skips of one schedule before a warn log + counter fire. */
+export const FORBID_SUSTAINED_SKIP_THRESHOLD = 6
+
+/** A live non-terminal run (see the CHECK on `workflow_runs.phase`). */
+interface ActiveRecipeRun {
+ run_id: string
+ phase: 'Pending' | 'Running'
+ created_at: Date
+ started_at: Date | null
+}
+
+/**
+ * Consecutive Forbid skips per schedule_id, for the sustained-skip warning.
+ * In-memory and per replica by design: the count restarts when the advisory
+ * lock moves to another replica or the process restarts, so a warning can be
+ * delayed by up to FORBID_SUSTAINED_SKIP_THRESHOLD ticks after a failover,
+ * never duplicated. `expectedFireAt` is the next_fire_at this replica wrote
+ * with its last skip; if the row arrives with any other slot (another replica
+ * fired or skipped it, or the batch rolled back) the streak restarts at 1.
+ * Entries are deleted when the schedule fires, so the map is bounded by the
+ * number of schedules that are currently being skipped.
+ */
+const forbiddenSkipStreaks = new Map<string, { count: number; expectedFireAt: string }>()
+
+/** Test-only: forget every streak so cases do not leak into each other. */
+export function resetConcurrencyForbiddenStreaksForTests(): void {
+ forbiddenSkipStreaks.clear()
+}
+
interface ScheduleRow {
schedule_id: string
recipe_namespace: string
@@ -78,19 +172,29 @@ interface ScheduleRow {
* the WRC schedule sync. NULL means the archive cron's global grace applies.
*/
ttl_seconds_after_finished: number | null
+ /**
+ * Denormalized copy of `spec.triggers.schedule.concurrencyPolicy` written by
+ * the WRC schedule sync (column default 'Forbid'). NULL / unknown values are
+ * treated as 'Forbid', the CRD default.
+ */
+ concurrency_policy: ScheduleConcurrencyPolicy | null
}
export interface ScheduleFireResult {
scheduleId: string
runId: string | null
fired: boolean
- reason: 'ok' | 'error' | 'invalid_cron' | 'actor_not_allowed'
+ reason: 'ok' | 'error' | 'invalid_cron' | 'actor_not_allowed' | 'concurrency_forbidden'
+ /** Set when `reason === 'concurrency_forbidden'`: the run that blocked the tick. */
+ activeRunId?: string
error?: string
}
export interface ScheduleWorkerSweepResult {
fired: number
actorNotAllowed: number
+ /** Ticks skipped because `concurrency_policy = 'Forbid'` and a live run existed. */
+ concurrencyForbidden: number
skippedLock: boolean
errors: number
}
@@ -109,6 +213,7 @@ export async function processMaturedSchedules(
const summary: ScheduleWorkerSweepResult = {
fired: 0,
actorNotAllowed: 0,
+ concurrencyForbidden: 0,
skippedLock: false,
errors: 0,
}
@@ -139,6 +244,11 @@ export async function processMaturedSchedules(
// so dashboards can surface silenced schedules.
summary.actorNotAllowed += 1
workflowScheduleWorkerFiresTotal.inc({ result: 'actor_not_allowed' }, 1)
+ } else if (r.reason === 'concurrency_forbidden') {
+ // Policy-driven skip — expected under `Forbid` while a run is live.
+ // Not an error; a distinct label keeps it visible on dashboards.
+ summary.concurrencyForbidden += 1
+ workflowScheduleWorkerFiresTotal.inc({ result: 'concurrency_forbidden' }, 1)
} else {
summary.errors += 1
workflowScheduleWorkerFiresTotal.inc({ result: 'error' }, 1)
@@ -146,12 +256,21 @@ export async function processMaturedSchedules(
}
workflowScheduleWorkerRunsTotal.inc({ result: 'ok' }, 1)
- if (summary.fired > 0 || summary.errors > 0) {
+ // Skip-only sweeps are logged too: a schedule silenced by a policy gate
+ // must not look like an idle worker.
+ if (
+ summary.fired > 0 ||
+ summary.errors > 0 ||
+ summary.actorNotAllowed > 0 ||
+ summary.concurrencyForbidden > 0
+ ) {
rootLogger.info(
{
event: 'workflow_schedule_worker_run',
fired: summary.fired,
errors: summary.errors,
+ actorNotAllowed: summary.actorNotAllowed,
+ concurrencyForbidden: summary.concurrencyForbidden,
},
'schedule worker sweep complete'
)
@@ -191,11 +310,13 @@ export async function processMaturedSchedules(
* Drain and fire a single batch of matured schedules inside ONE transaction so
* `FOR UPDATE SKIP LOCKED` actually holds row-level locks for the duration of
* the batch (in autocommit mode the locks would be released immediately after
- * the SELECT, defeating the concurrency guard). `fireOneSchedule` never throws
- * — malformed cron expressions or insert errors surface as
- * `{fired:false, reason:'invalid_cron'|'error'}` — so committing at the end is
- * safe. A catastrophic DB error (lost connection, deadlock on COMMIT) triggers
- * a best-effort ROLLBACK before re-raising.
+ * the SELECT, defeating the concurrency guard). `fireOneSchedule` surfaces
+ * malformed cron expressions and insert errors as
+ * `{fired:false, reason:'invalid_cron'|'error'}`, so committing at the end is
+ * safe. The one exception is the concurrency-policy active-run lookup: its
+ * error propagates so the whole batch rolls back and no run is ever created
+ * without the check. A catastrophic DB error (lost connection, deadlock on
+ * COMMIT) also triggers a best-effort ROLLBACK before re-raising.
*/
async function fireOneBatch(client: DbClient, batchSize: number): Promise<ScheduleFireResult[]> {
await client.query('BEGIN')
@@ -203,7 +324,8 @@ async function fireOneBatch(client: DbClient, batchSize: number): Promise<Schedu
const selected = await client.query(
`SELECT schedule_id, recipe_namespace, recipe_name, team_id,
cron_expression, timezone, next_fire_at, input_template,
- allowed_actors, max_duration_seconds, ttl_seconds_after_finished
+ allowed_actors, max_duration_seconds, ttl_seconds_after_finished,
+ concurrency_policy
FROM workflow_schedules
WHERE enabled = TRUE
AND next_fire_at <= now()
@@ -237,6 +359,7 @@ async function fireOneBatch(client: DbClient, batchSize: number): Promise<Schedu
/**
* Fire a single schedule: insert workflow_runs row + advance next_fire_at.
+ * Gate order: cron parse → allowed_actors → concurrency_policy → createRun.
* Must run with the caller holding the row lock from the enclosing SELECT.
*/
async function fireOneSchedule(client: DbClient, row: ScheduleRow): Promise<ScheduleFireResult> {
@@ -311,6 +434,17 @@ async function fireOneSchedule(client: DbClient, row: ScheduleRow): Promise<Sche
}
}
+ // concurrencyPolicy gate. Runs on the batch client inside the transaction
+ // that holds the advisory lock and the schedule row lock, so the check and
+ // the createRun() below are consistent across control-api replicas. Only
+ // Forbid checks; Allow and the unimplemented Replace fire unconditionally.
+ if (resolveConcurrencyPolicy(row.concurrency_policy) === 'Forbid') {
+ const activeRun = await findActiveRunForRecipe(client, row.recipe_namespace, row.recipe_name)
+ if (activeRun) {
+ return skipForbiddenTick(client, row, currentFire, activeRun)
+ }
+ }
+
const idempotencyKey = `schedule/${row.schedule_id}/${currentFire.toISOString()}`
try {
@@ -339,6 +473,7 @@ async function fireOneSchedule(client: DbClient, row: ScheduleRow): Promise<Sche
WHERE schedule_id = $2`,
[nextFire, row.schedule_id]
)
+ forbiddenSkipStreaks.delete(row.schedule_id)
return {
scheduleId: row.schedule_id,
@@ -368,6 +503,115 @@ async function fireOneSchedule(client: DbClient, row: ScheduleRow): Promise<Sche
}
}
+function resolveConcurrencyPolicy(value: unknown): ScheduleConcurrencyPolicy {
+ return value === 'Allow' || value === 'Replace' ? value : 'Forbid'
+}
+
+/**
+ * Oldest LIVE non-terminal run of the recipe, or null. Scheduled and on-demand
+ * runs are both stamped with the recipe's own (namespace, name); the run-scoped
+ * child CR lives in `child_recipe_name`, so this matches every run of the
+ * recipe regardless of trigger source. "Live" applies the stale-run bounds
+ * documented in the header (Pending by age, Running by deadline + grace). A
+ * query error propagates so the batch rolls back and no run is created
+ * without the check (fail closed). Exported for the real-Postgres lane
+ * (`services.workflowScheduleForbid.realPostgres.integration.test.ts`).
+ */
+export async function findActiveRunForRecipe(
+ client: DbClient,
+ recipeNamespace: string,
+ recipeName: string
+): Promise<ActiveRecipeRun | null> {
+ const result = await client.query(
+ `SELECT run_id, phase, created_at, started_at
+ FROM workflow_runs
+ WHERE recipe_namespace = $1
+ AND recipe_name = $2
+ AND (
+ (phase = 'Pending'
+ AND created_at > now() - make_interval(secs => $3))
+ OR (phase = 'Running'
+ AND COALESCE(started_at, created_at) > now() - make_interval(secs => LEAST(COALESCE(max_duration_seconds, $4), $4) + $5))
+ )
+ ORDER BY created_at ASC
+ LIMIT 1`,
+ [
+ recipeNamespace,
+ recipeName,
+ FORBID_PENDING_ACTIVE_BOUND_SECONDS,
+ FORBID_RUNNING_MAX_DURATION_CAP_SECONDS,
+ FORBID_RUNNING_GRACE_SECONDS,
+ ]
+ )
+ return (result.rows[0] as ActiveRecipeRun | undefined) ?? null
+}
+
+/**
+ * Record a Forbid skip: advance to the first window after max(current slot,
+ * now) so a backlog accumulated while the run was live is dropped, never
+ * replayed; log the blocking run and its age; track the consecutive-skip
+ * streak and warn once when it reaches FORBID_SUSTAINED_SKIP_THRESHOLD.
+ */
+async function skipForbiddenTick(
+ client: DbClient,
+ row: ScheduleRow,
+ currentFire: Date,
+ activeRun: ActiveRecipeRun
+): Promise<ScheduleFireResult> {
+ const now = Date.now()
+ const skipNextFire = computeNextFire(
+ row.cron_expression,
+ row.timezone,
+ new Date(Math.max(currentFire.getTime(), now))
+ )
+ await client.query(
+ `UPDATE workflow_schedules
+ SET next_fire_at = $1,
+ updated_at = now()
+ WHERE schedule_id = $2`,
+ [skipNextFire, row.schedule_id]
+ )
+
+ const previous = forbiddenSkipStreaks.get(row.schedule_id)
+ const consecutiveSkips =
+ previous && previous.expectedFireAt === currentFire.toISOString() ? previous.count + 1 : 1
+ forbiddenSkipStreaks.set(row.schedule_id, {
+ count: consecutiveSkips,
+ expectedFireAt: skipNextFire.toISOString(),
+ })
+
+ const activeSince = new Date(activeRun.started_at ?? activeRun.created_at)
+ const fields = {
+ scheduleId: row.schedule_id,
+ recipe: `${row.recipe_namespace}/${row.recipe_name}`,
+ skippedFireAt: currentFire.toISOString(),
+ nextFireAt: skipNextFire.toISOString(),
+ activeRunId: activeRun.run_id,
+ activeRunPhase: activeRun.phase,
+ activeRunAgeSeconds: Math.max(0, Math.floor((now - activeSince.getTime()) / 1000)),
+ consecutiveSkips,
+ }
+ rootLogger.info(
+ { event: 'workflow_schedule_worker_concurrency_forbidden', ...fields },
+ 'schedule tick skipped: concurrencyPolicy Forbid and a run of this recipe is still active'
+ )
+ if (consecutiveSkips === FORBID_SUSTAINED_SKIP_THRESHOLD) {
+ workflowScheduleWorkerConcurrencyForbiddenSustainedTotal.inc(1)
+ rootLogger.warn(
+ { event: 'workflow_schedule_worker_concurrency_forbidden_sustained', ...fields },
+ 'schedule has skipped consecutive ticks under concurrencyPolicy Forbid; check the blocking run'
+ )
+ }
+
+ return {
+ scheduleId: row.schedule_id,
+ runId: null,
+ fired: false,
+ reason: 'concurrency_forbidden',
+ activeRunId: activeRun.run_id,
+ }
+}
+
/**
* Compute the next fire time AFTER `from`. Exported for unit-test precision —
* the worker tests assert the cadence math rather than re-parsing cron strings.
diff --git a/control-api/test/services.workflowScheduleForbid.realPostgres.integration.test.ts b/control-api/test/services.workflowScheduleForbid.realPostgres.integration.test.ts
new file mode 100644
index 000000000..86b414f1d
--- /dev/null
+++ b/control-api/test/services.workflowScheduleForbid.realPostgres.integration.test.ts
@@ -0,0 +1,235 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { randomBytes } from 'node:crypto'
+import { Pool } from 'pg'
+import { initDb } from '../src/db.js'
+import { findActiveRunForRecipe } from '../src/services/workflowScheduleWorkerService.js'
+import { endPoolAndWaitForClients } from './helpers/realPostgresTeardown.js'
+import './realPostgres.requirement.ts'
+import { waitForDatabaseConnectionsToClose } from './realPostgresCleanup.ts'
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+
+const NS = 'p3-forbid'
+const OTHER_NS = 'p3-forbid-other'
+
+type Fixture = {
+ recipe: string
+ namespace?: string
+ phase: 'Pending' | 'Running' | 'Succeeded'
+ /** Recipe whose run this row is (defaults to `recipe`). */
+ runOf?: string
+ /** Run-scoped child CR name; never the identity the lookup matches on. */
+ childRecipeName?: string
+ createdMinutesAgo: number
+ startedMinutesAgo: number | null
+ maxDurationSeconds: number | null
+}
+
+/**
+ * One isolated recipe per case so the lookup's LIMIT 1 cannot hide a row.
+ * `blocks` = the Forbid gate would skip the tick; otherwise it would fire.
+ */
+const cases: Array<{ name: string; blocks: boolean; fixture: Fixture }> = [
+ {
+ name: 'a Running run of the same recipe blocks',
+ blocks: true,
+ fixture: {
+ recipe: 'running-same',
+ phase: 'Running',
+ childRecipeName: 'running-same-run-0001',
+ createdMinutesAgo: 3,
+ startedMinutesAgo: 2,
+ maxDurationSeconds: null,
+ },
+ },
+ {
+ name: 'a Succeeded run of the same recipe does not block',
+ blocks: false,
+ fixture: {
+ recipe: 'succeeded-same',
+ phase: 'Succeeded',
+ createdMinutesAgo: 3,
+ startedMinutesAgo: 2,
+ maxDurationSeconds: null,
+ },
+ },
+ {
+ name: 'a Running run of another recipe does not block, even when its child CR has our name',
+ blocks: false,
+ fixture: {
+ recipe: 'other-recipe-target',
+ runOf: 'some-other-recipe',
+ phase: 'Running',
+ childRecipeName: 'other-recipe-target',
+ createdMinutesAgo: 3,
+ startedMinutesAgo: 2,
+ maxDurationSeconds: null,
+ },
+ },
+ {
+ name: 'a Running run of the same name in another namespace does not block',
+ blocks: false,
+ fixture: {
+ recipe: 'same-name-other-ns',
+ namespace: OTHER_NS,
+ phase: 'Running',
+ createdMinutesAgo: 3,
+ startedMinutesAgo: 2,
+ maxDurationSeconds: null,
+ },
+ },
+ {
+ name: 'a fresh Pending run blocks',
+ blocks: true,
+ fixture: {
+ recipe: 'pending-fresh',
+ phase: 'Pending',
+ createdMinutesAgo: 1,
+ startedMinutesAgo: null,
+ maxDurationSeconds: null,
+ },
+ },
+ {
+ name: 'a Pending run older than the 15 min bound does not block',
+ blocks: false,
+ fixture: {
+ recipe: 'pending-stale',
+ phase: 'Pending',
+ createdMinutesAgo: 16,
+ startedMinutesAgo: null,
+ maxDurationSeconds: null,
+ },
+ },
+ {
+ name: 'a Running run inside max_duration_seconds + grace blocks',
+ blocks: true,
+ fixture: {
+ recipe: 'running-within-grace',
+ phase: 'Running',
+ createdMinutesAgo: 13,
+ startedMinutesAgo: 12,
+ maxDurationSeconds: 600,
+ },
+ },
+ {
+ name: 'a Running run past max_duration_seconds + grace does not block',
+ blocks: false,
+ fixture: {
+ recipe: 'running-stale',
+ phase: 'Running',
+ createdMinutesAgo: 17,
+ startedMinutesAgo: 16,
+ maxDurationSeconds: 600,
+ },
+ },
+ {
+ name: 'a Running run with NULL max_duration_seconds blocks inside the 24 h cap',
+ blocks: true,
+ fixture: {
+ recipe: 'running-null-within-cap',
+ phase: 'Running',
+ createdMinutesAgo: 23 * 60 + 1,
+ startedMinutesAgo: 23 * 60,
+ maxDurationSeconds: null,
+ },
+ },
+ {
+ name: 'a Running run with NULL max_duration_seconds does not block past the cap + grace',
+ blocks: false,
+ fixture: {
+ recipe: 'running-null-past-cap',
+ phase: 'Running',
+ createdMinutesAgo: 24 * 60 + 7,
+ startedMinutesAgo: 24 * 60 + 6,
+ maxDurationSeconds: null,
+ },
+ },
+ {
+ name: 'a max_duration_seconds above the cap is clamped to it',
+ blocks: false,
+ fixture: {
+ recipe: 'running-oversized-max',
+ phase: 'Running',
+ createdMinutesAgo: 25 * 60 + 1,
+ startedMinutesAgo: 25 * 60,
+ maxDurationSeconds: 604_800,
+ },
+ },
+ {
+ name: 'a Running run with NULL started_at is aged from created_at',
+ blocks: true,
+ fixture: {
+ recipe: 'running-null-started',
+ phase: 'Running',
+ createdMinutesAgo: 2,
+ startedMinutesAgo: null,
+ maxDurationSeconds: null,
+ },
+ },
+]
+
+describeRealPostgres('workflow schedule Forbid active-run lookup (real Postgres)', () => {
+ const database = `wf_schedule_forbid_${randomBytes(6).toString('hex')}`
+ let adminPool: Pool
+ let pool: Pool
+ const runIds = new Map<string, string>()
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE "${database}"`)
+ const url = new URL(adminUrl!)
+ url.pathname = `/${database}`
+ pool = new Pool({ connectionString: url.toString() })
+ // The real migrated schema, not a hand-written copy of workflow_runs.
+ await initDb({ connect: () => pool.connect() })
+
+ for (const { fixture } of cases) {
+ const inserted = await pool.query<{ run_id: string }>(
+ `INSERT INTO workflow_runs
+ (recipe_namespace, recipe_name, phase, actor_type, trigger_source,
+ child_recipe_name, max_duration_seconds, created_at, started_at)
+ VALUES ($1, $2, $3, 'scheduled', 'schedule', $4, $5,
+ now() - make_interval(mins => $6),
+ CASE WHEN $7::int IS NULL THEN NULL ELSE now() - make_interval(mins => $7::int) END)
+ RETURNING run_id`,
+ [
+ fixture.namespace ?? NS,
+ fixture.runOf ?? fixture.recipe,
+ fixture.phase,
+ fixture.childRecipeName ?? null,
+ fixture.maxDurationSeconds,
+ fixture.createdMinutesAgo,
+ fixture.startedMinutesAgo,
+ ]
+ )
+ runIds.set(fixture.recipe, inserted.rows[0]!.run_id)
+ }
+ }, 180_000)
+
+ afterAll(async () => {
+ try {
+ await endPoolAndWaitForClients(pool)
+ if (!adminPool) return
+ await waitForDatabaseConnectionsToClose(adminPool, database)
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database}"`)
+ } finally {
+ await adminPool?.end()
+ }
+ })
+
+ it.each(cases)('$name', async ({ blocks, fixture }) => {
+ const client = await pool.connect()
+ try {
+ const active = await findActiveRunForRecipe(client, NS, fixture.recipe)
+ if (blocks) {
+ expect(active?.run_id).toBe(runIds.get(fixture.recipe))
+ expect(active?.phase).toBe(fixture.phase)
+ } else {
+ expect(active).toBeNull()
+ }
+ } finally {
+ client.release()
+ }
+ })
+})
diff --git a/control-api/test/services.workflowScheduleWorker.test.ts b/control-api/test/services.workflowScheduleWorker.test.ts
index 54460901d..5d352cfe7 100644
--- a/control-api/test/services.workflowScheduleWorker.test.ts
+++ b/control-api/test/services.workflowScheduleWorker.test.ts
@@ -1,8 +1,18 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { rootLogger } from '../src/observability/logger.js'
+import {
+ workflowScheduleWorkerConcurrencyForbiddenSustainedTotal,
+ workflowScheduleWorkerFiresTotal,
+} from '../src/observability/metrics.js'
// Imports AFTER vi.mock() so the service picks up the fakes.
import {
+ FORBID_PENDING_ACTIVE_BOUND_SECONDS,
+ FORBID_RUNNING_GRACE_SECONDS,
+ FORBID_RUNNING_MAX_DURATION_CAP_SECONDS,
+ FORBID_SUSTAINED_SKIP_THRESHOLD,
computeNextFire,
processMaturedSchedules,
+ resetConcurrencyForbiddenStreaksForTests,
} from '../src/services/workflowScheduleWorkerService.js'
/**
@@ -31,6 +41,7 @@ type ScheduleRow = {
allowed_actors?: Array<'user' | 'autonomous' | 'scheduled'> | null
max_duration_seconds?: number | null
ttl_seconds_after_finished?: number | null
+ concurrency_policy?: 'Forbid' | 'Replace' | 'Allow' | null
}
// ─── Mock state ────────────────────────────────────────────────────────────
@@ -42,6 +53,18 @@ const txEvents: Array<'BEGIN' | 'COMMIT' | 'ROLLBACK'> = []
/** Test-configurable hook that can inject a failure at SELECT time. */
let selectQueryError: Error | null = null
+/** Non-terminal workflow_runs keyed by `${recipe_namespace}/${recipe_name}`. */
+type FakeRun = {
+ run_id: string
+ phase: 'Pending' | 'Running'
+ created_at: Date
+ started_at: Date | null
+ max_duration_seconds: number | null
+}
+const activeRuns = new Map<string, FakeRun>()
+/** Test-configurable hook that can inject a failure into the active-run lookup. */
+let activeRunQueryError: Error | null = null
+
const clientQuery = vi.fn(
async (sql: unknown, params?: unknown[]): Promise<AnyQueryResult | LockQueryResult> => {
const text = typeof sql === 'string' ? sql : ''
@@ -86,6 +109,9 @@ const clientQuery = vi.fn(
if (!/team_id/i.test(text)) {
throw new Error('SELECT must include team_id column')
}
+ if (!/concurrency_policy/i.test(text)) {
+ throw new Error('SELECT must include concurrency_policy column')
+ }
const limit = Number(params?.[0] ?? 0)
const batch = maturedRows.splice(0, limit)
return { rows: batch, rowCount: batch.length }
@@ -104,6 +130,33 @@ const clientQuery = vi.fn(
return { rows: [], rowCount: 1 }
}
+ if (/FROM workflow_runs/i.test(text)) {
+ if (activeRunQueryError) throw activeRunQueryError
+ if (!/phase = 'Pending'/.test(text) || !/phase = 'Running'/.test(text)) {
+ throw new Error('active-run lookup must filter on non-terminal phases')
+ }
+ const run = activeRuns.get(`${String(params?.[0])}/${String(params?.[1])}`)
+ if (!run) return { rows: [], rowCount: 0 }
+ // Minimal emulation of the stale-run bounds ($3 Pending bound, $4 cap,
+ // $5 grace) so the worker's wiring is exercised. The SQL semantics are
+ // proven against real Postgres in
+ // services.workflowScheduleForbid.realPostgres.integration.test.ts.
+ const [pendingBound, cap, grace] = [
+ Number(params?.[2]),
+ Number(params?.[3]),
+ Number(params?.[4]),
+ ]
+ const now = Date.now()
+ const live =
+ run.phase === 'Pending'
+ ? run.created_at.getTime() > now - pendingBound * 1000
+ : (run.started_at ?? run.created_at).getTime() >
+ now - (Math.min(run.max_duration_seconds ?? cap, cap) + grace) * 1000
+ if (!live) return { rows: [], rowCount: 0 }
+ const { run_id, phase, created_at, started_at } = run
+ return { rows: [{ run_id, phase, created_at, started_at }], rowCount: 1 }
+ }
+
return { rows: [], rowCount: null }
}
)
@@ -142,6 +195,7 @@ vi.mock('../src/observability/logger.js', () => ({
vi.mock('../src/observability/metrics.js', () => ({
workflowScheduleWorkerRunsTotal: { inc: vi.fn() },
workflowScheduleWorkerFiresTotal: { inc: vi.fn() },
+ workflowScheduleWorkerConcurrencyForbiddenSustainedTotal: { inc: vi.fn() },
workflowScheduleWorkerDurationSeconds: { observe: vi.fn() },
}))
@@ -154,6 +208,8 @@ describe('processMaturedSchedules', () => {
txEvents.length = 0
lockAcquired = true
selectQueryError = null
+ activeRuns.clear()
+ activeRunQueryError = null
clientQuery.mockClear()
clientRelease.mockClear()
mockConnect.mockClear()
@@ -393,6 +449,367 @@ describe('processMaturedSchedules', () => {
// sweep would skip forever.
expect(clientRelease).toHaveBeenCalledTimes(1)
})
+
+ describe('concurrencyPolicy', () => {
+ const teamId = '11111111-1111-4111-8111-111111111111'
+ const NOW = new Date('2026-04-20T09:00:05Z')
+ const minutesAgo = (minutes: number) => new Date(Date.now() - minutes * 60_000)
+
+ function scheduleRow(overrides: Partial<ScheduleRow> = {}): ScheduleRow {
+ return {
+ schedule_id: 's-forbid',
+ recipe_namespace: 'sandbox-recipes',
+ recipe_name: 'pr-review',
+ team_id: teamId,
+ cron_expression: '*/5 * * * *',
+ timezone: 'UTC',
+ next_fire_at: new Date('2026-04-20T09:00:00Z'),
+ input_template: null,
+ concurrency_policy: 'Forbid',
+ ...overrides,
+ }
+ }
+
+ function setActiveRun(overrides: Partial<FakeRun> = {}, key = 'sandbox-recipes/pr-review') {
+ activeRuns.set(key, {
+ run_id: 'run-active',
+ phase: 'Running',
+ created_at: minutesAgo(3),
+ started_at: minutesAgo(2),
+ max_duration_seconds: null,
+ ...overrides,
+ })
+ }
+
+ function activeRunLookups(): unknown[][] {
+ return clientQuery.mock.calls
+ .filter(([sql]) => /FROM workflow_runs/i.test(String(sql)))
+ .map(([, params]) => (params ?? []) as unknown[])
+ }
+
+ beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['Date'] })
+ vi.setSystemTime(NOW)
+ resetConcurrencyForbiddenStreaksForTests()
+ vi.mocked(rootLogger.info).mockClear()
+ vi.mocked(rootLogger.warn).mockClear()
+ vi.mocked(workflowScheduleWorkerFiresTotal.inc).mockClear()
+ vi.mocked(workflowScheduleWorkerConcurrencyForbiddenSustainedTotal.inc).mockClear()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('skips the tick under Forbid while a Running run of the recipe exists, records the reason, and advances', async () => {
+ setActiveRun()
+ maturedRows.push(scheduleRow())
+
+ const result = await processMaturedSchedules()
+
+ expect(result.fired).toBe(0)
+ expect(result.concurrencyForbidden).toBe(1)
+ expect(result.actorNotAllowed).toBe(0)
+ expect(result.errors).toBe(0)
+ expect(createRunMock).not.toHaveBeenCalled()
+ expect(updatedSchedules).toEqual([
+ { schedule_id: 's-forbid', next_fire_at: new Date('2026-04-20T09:05:00.000Z') },
+ ])
+ expect(workflowScheduleWorkerFiresTotal.inc).toHaveBeenCalledWith(
+ { result: 'concurrency_forbidden' },
+ 1
+ )
+ expect(rootLogger.info).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: 'workflow_schedule_worker_concurrency_forbidden',
+ scheduleId: 's-forbid',
+ recipe: 'sandbox-recipes/pr-review',
+ activeRunId: 'run-active',
+ activeRunPhase: 'Running',
+ activeRunAgeSeconds: 120,
+ consecutiveSkips: 1,
+ skippedFireAt: '2026-04-20T09:00:00.000Z',
+ nextFireAt: '2026-04-20T09:05:00.000Z',
+ }),
+ expect.any(String)
+ )
+ // The skip is not a fire: last_fire_at must not be stamped.
+ const skipUpdate = clientQuery.mock.calls.find(([sql]) =>
+ /UPDATE workflow_schedules/i.test(String(sql))
+ )
+ expect(String(skipUpdate?.[0])).not.toMatch(/last_fire_at/)
+ expect(txEvents).toEqual(['BEGIN', 'COMMIT'])
+ })
+
+ it('emits the sweep summary log for a skip-only sweep', async () => {
+ setActiveRun()
+ maturedRows.push(scheduleRow())
+
+ await processMaturedSchedules()
+
+ expect(rootLogger.info).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: 'workflow_schedule_worker_run',
+ fired: 0,
+ errors: 0,
+ concurrencyForbidden: 1,
+ }),
+ 'schedule worker sweep complete'
+ )
+ })
+
+ it('treats a fresh Pending run as active', async () => {
+ setActiveRun({
+ run_id: 'run-pending',
+ phase: 'Pending',
+ created_at: minutesAgo(1),
+ started_at: null,
+ })
+ maturedRows.push(scheduleRow())
+
+ const result = await processMaturedSchedules()
+
+ expect(result.concurrencyForbidden).toBe(1)
+ expect(createRunMock).not.toHaveBeenCalled()
+ expect(rootLogger.info).toHaveBeenCalledWith(
+ expect.objectContaining({ activeRunId: 'run-pending', activeRunAgeSeconds: 60 }),
+ expect.any(String)
+ )
+ })
+
+ it('stops counting a Pending run as active once it is older than the Pending bound', async () => {
+ // Nothing terminalises a Pending row whose child CR never got created.
+ setActiveRun({ phase: 'Pending', created_at: minutesAgo(16), started_at: null })
+ maturedRows.push(scheduleRow())
+
+ const result = await processMaturedSchedules()
+
+ expect(result.fired).toBe(1)
+ expect(result.concurrencyForbidden).toBe(0)
+ expect(createRunMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('blocks on a Running run still inside max_duration_seconds + grace', async () => {
+ // 600 s deadline passed 2 min ago, but the 5 min reaper grace has not.
+ setActiveRun({ max_duration_seconds: 600, started_at: minutesAgo(12) })
+ maturedRows.push(scheduleRow())
+
+ const result = await processMaturedSchedules()
+
+ expect(result.concurrencyForbidden).toBe(1)
+ expect(createRunMock).not.toHaveBeenCalled()
+ })
+
+ it('stops counting a Running run as active past max_duration_seconds + grace', async () => {
+ setActiveRun({ max_duration_seconds: 600, started_at: minutesAgo(16) })
+ maturedRows.push(scheduleRow())
+
+ const result = await processMaturedSchedules()
+
+ expect(result.fired).toBe(1)
+ expect(createRunMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('bounds a Running run with no or an oversized max_duration_seconds by the 24 h cap', async () => {
+ setActiveRun({ max_duration_seconds: null, started_at: minutesAgo(23 * 60) })
+ maturedRows.push(scheduleRow())
+ expect((await processMaturedSchedules()).concurrencyForbidden).toBe(1)
+
+ // The CRD default (604800) exceeds the controller ceiling: clamp to the cap.
+ setActiveRun({ max_duration_seconds: 604_800, started_at: minutesAgo(24 * 60 + 6) })
+ maturedRows.push(scheduleRow({ next_fire_at: new Date('2026-04-20T09:05:00Z') }))
+ vi.setSystemTime(new Date('2026-04-20T09:05:05Z'))
+ expect((await processMaturedSchedules()).fired).toBe(1)
+ })
+
+ it('binds the named stale-run bounds into the lookup', async () => {
+ maturedRows.push(scheduleRow())
+
+ await processMaturedSchedules()
+
+ expect(FORBID_PENDING_ACTIVE_BOUND_SECONDS).toBe(900)
+ expect(FORBID_RUNNING_MAX_DURATION_CAP_SECONDS).toBe(86_400)
+ expect(FORBID_RUNNING_GRACE_SECONDS).toBe(300)
+ expect(activeRunLookups()).toEqual([['sandbox-recipes', 'pr-review', 900, 86_400, 300]])
+ const lookupSql = String(
+ clientQuery.mock.calls.find(([sql]) => /FROM workflow_runs/i.test(String(sql)))?.[0]
+ )
+ expect(lookupSql).toMatch(/created_at > now\(\) - make_interval\(secs => \$3\)/)
+ expect(lookupSql).toMatch(
+ /COALESCE\(started_at, created_at\) > now\(\) - make_interval\(secs => LEAST\(COALESCE\(max_duration_seconds, \$4\), \$4\) \+ \$5\)/
+ )
+ })
+
+ it('advances past a backlog to the next future window instead of replaying it', async () => {
+ // The worker was down for an hour: next_fire_at is 12 windows behind.
+ setActiveRun()
+ maturedRows.push(scheduleRow({ next_fire_at: new Date('2026-04-20T08:00:00Z') }))
+
+ await processMaturedSchedules()
+
+ // 09:05 (first window after now), not 08:05 (one step after the stale slot).
+ expect(updatedSchedules[0]?.next_fire_at?.toISOString()).toBe('2026-04-20T09:05:00.000Z')
+ })
+
+ it('fires the first tick after the active run finishes', async () => {
+ setActiveRun()
+ maturedRows.push(scheduleRow())
+
+ const skipped = await processMaturedSchedules()
+ expect(skipped.concurrencyForbidden).toBe(1)
+ const advancedTo = updatedSchedules[0]?.next_fire_at
+ expect(advancedTo?.toISOString()).toBe('2026-04-20T09:05:00.000Z')
+
+ // The run reaches a terminal phase; the schedule matures at its new slot.
+ activeRuns.clear()
+ updatedSchedules.length = 0
+ vi.setSystemTime(new Date('2026-04-20T09:05:02Z'))
+ maturedRows.push(scheduleRow({ next_fire_at: advancedTo! }))
+
+ const fired = await processMaturedSchedules()
+
+ expect(fired.fired).toBe(1)
+ expect(fired.concurrencyForbidden).toBe(0)
+ expect(createRunMock).toHaveBeenCalledTimes(1)
+ expect(createRunMock.mock.calls[0]?.[0].idempotency_key).toBe(
+ 'schedule/s-forbid/2026-04-20T09:05:00.000Z'
+ )
+ expect(updatedSchedules[0]?.next_fire_at?.toISOString()).toBe('2026-04-20T09:10:00.000Z')
+ })
+
+ it('warns once after 6 consecutive skips and restarts the streak after a fire', async () => {
+ setActiveRun({ started_at: minutesAgo(1) })
+ let slot = new Date('2026-04-20T09:00:00Z')
+ const tick = async () => {
+ vi.setSystemTime(new Date(slot.getTime() + 5_000))
+ updatedSchedules.length = 0
+ maturedRows.push(scheduleRow({ next_fire_at: slot }))
+ const result = await processMaturedSchedules()
+ slot = updatedSchedules[0]!.next_fire_at!
+ return result
+ }
+
+ for (let i = 1; i < FORBID_SUSTAINED_SKIP_THRESHOLD; i += 1) await tick()
+ expect(rootLogger.warn).not.toHaveBeenCalled()
+
+ await tick() // 6th consecutive skip
+ expect(rootLogger.warn).toHaveBeenCalledTimes(1)
+ expect(rootLogger.warn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: 'workflow_schedule_worker_concurrency_forbidden_sustained',
+ scheduleId: 's-forbid',
+ activeRunId: 'run-active',
+ consecutiveSkips: FORBID_SUSTAINED_SKIP_THRESHOLD,
+ }),
+ expect.any(String)
+ )
+ expect(workflowScheduleWorkerConcurrencyForbiddenSustainedTotal.inc).toHaveBeenCalledTimes(1)
+
+ await tick() // 7th: still skipping, no second warning for the same streak
+ expect(rootLogger.warn).toHaveBeenCalledTimes(1)
+
+ activeRuns.clear()
+ expect((await tick()).fired).toBe(1)
+ setActiveRun()
+ vi.mocked(rootLogger.info).mockClear()
+ await tick()
+ expect(rootLogger.info).toHaveBeenCalledWith(
+ expect.objectContaining({ consecutiveSkips: 1 }),
+ expect.any(String)
+ )
+ })
+
+ it('defaults a null concurrency_policy to Forbid', async () => {
+ setActiveRun()
+ maturedRows.push(scheduleRow({ concurrency_policy: null }))
+
+ const result = await processMaturedSchedules()
+
+ expect(result.concurrencyForbidden).toBe(1)
+ expect(createRunMock).not.toHaveBeenCalled()
+ })
+
+ it('still overlaps under Allow and never looks up active runs', async () => {
+ setActiveRun()
+ maturedRows.push(scheduleRow({ concurrency_policy: 'Allow' }))
+
+ const result = await processMaturedSchedules()
+
+ expect(result.fired).toBe(1)
+ expect(result.concurrencyForbidden).toBe(0)
+ expect(createRunMock).toHaveBeenCalledTimes(1)
+ expect(activeRunLookups()).toHaveLength(0)
+ })
+
+ it('treats Replace exactly like Allow (Replace is not implemented)', async () => {
+ setActiveRun()
+ maturedRows.push(scheduleRow({ concurrency_policy: 'Replace' }))
+
+ const result = await processMaturedSchedules()
+
+ expect(result.fired).toBe(1)
+ expect(result.concurrencyForbidden).toBe(0)
+ expect(createRunMock).toHaveBeenCalledTimes(1)
+ expect(activeRunLookups()).toHaveLength(0)
+ })
+
+ it('does not block on an active run of a different recipe', async () => {
+ setActiveRun({ run_id: 'run-other' }, 'sandbox-recipes/other-recipe')
+ setActiveRun({ run_id: 'run-other-ns' }, 'other-namespace/pr-review')
+ maturedRows.push(scheduleRow())
+
+ const result = await processMaturedSchedules()
+
+ expect(result.fired).toBe(1)
+ expect(activeRunLookups().map(params => params.slice(0, 2))).toEqual([
+ ['sandbox-recipes', 'pr-review'],
+ ])
+ const lookupSql = String(
+ clientQuery.mock.calls.find(([sql]) => /FROM workflow_runs/i.test(String(sql)))?.[0]
+ )
+ expect(lookupSql).toMatch(/recipe_namespace = \$1/)
+ expect(lookupSql).toMatch(/AND recipe_name = \$2/)
+ expect(lookupSql).not.toMatch(/child_recipe_name/)
+ })
+
+ it('runs the active-run check inside the locked batch transaction, before createRun, on the same client', async () => {
+ maturedRows.push(scheduleRow())
+
+ await processMaturedSchedules()
+
+ const calls = clientQuery.mock.calls.map(([sql]) => String(sql))
+ const order = clientQuery.mock.invocationCallOrder
+ const lockAt = calls.findIndex(sql => /pg_try_advisory_lock/i.test(sql))
+ const beginAt = calls.findIndex(sql => /^\s*BEGIN\s*$/i.test(sql))
+ const selectAt = calls.findIndex(sql => /FOR UPDATE SKIP LOCKED/i.test(sql))
+ const lookupAt = calls.findIndex(sql => /FROM workflow_runs/i.test(sql))
+ const commitAt = calls.findIndex(sql => /^\s*COMMIT\s*$/i.test(sql))
+ expect(lockAt).toBeGreaterThanOrEqual(0)
+ expect(beginAt).toBeGreaterThan(lockAt)
+ expect(selectAt).toBeGreaterThan(beginAt)
+ expect(lookupAt).toBeGreaterThan(selectAt)
+ expect(commitAt).toBeGreaterThan(lookupAt)
+ expect(createRunMock).toHaveBeenCalledTimes(1)
+ const createRunOrder = createRunMock.mock.invocationCallOrder[0]!
+ expect(createRunOrder).toBeGreaterThan(order[lookupAt]!)
+ expect(createRunOrder).toBeLessThan(order[commitAt]!)
+ // createRun inserts through the same transaction-scoped client.
+ const runClient = createRunMock.mock.calls[0]?.[1] as { query: unknown }
+ expect(runClient.query).toBe(clientQuery)
+ })
+
+ it('rolls back without firing when the active-run lookup fails', async () => {
+ activeRunQueryError = new Error('canceling statement due to statement timeout')
+ maturedRows.push(scheduleRow())
+
+ await expect(processMaturedSchedules()).rejects.toThrow('statement timeout')
+
+ expect(createRunMock).not.toHaveBeenCalled()
+ expect(updatedSchedules).toHaveLength(0)
+ expect(txEvents).toEqual(['BEGIN', 'ROLLBACK'])
+ expect(clientRelease).toHaveBeenCalledTimes(1)
+ })
+ })
})
describe('computeNextFire', () => {