Skip to content

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

TypeScript

fix(control-api): add workflow_schedules.concurrency_policy column

Jose Ramirezde0f5aa604ce
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 86e53095b..092d6afee 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.737",
+ "version": "0.1.738",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.737",
+ "version": "0.1.738",
"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 d584b970e..2b01bf382 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.737",
+ "version": "0.1.738",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index 8b9a08d4a..25747f974 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -1783,6 +1783,30 @@ async function applyWorkflowRunRetentionColumnsMigration(db: DbClient): Promise<
`)
}
+/**
+ * Mirror of `spec.triggers.schedule.concurrencyPolicy` (and the legacy
+ * `spec.scheduling.concurrencyPolicy`), written by the WRC schedule sync and
+ * enforced by the control-api schedule worker. The default matches the CRD
+ * default (`Forbid`). The CHECK is part of the column definition, so
+ * `ADD COLUMN IF NOT EXISTS` skips the column and its constraint together on a
+ * re-run; the body is idempotent.
+ */
+async function applyWorkflowScheduleConcurrencyPolicyMigration(db: DbClient): Promise<void> {
+ await db.query(`
+ -- The schedule worker takes FOR UPDATE row locks on workflow_schedules every
+ -- sweep and the ALTER needs ACCESS EXCLUSIVE: bound the wait so a stuck
+ -- holder fails the migration Job loudly instead of hanging it (same 60s
+ -- budget and rationale as the plugin workload SDK reconciliation migration).
+ SET LOCAL lock_timeout = '60s';
+ ALTER TABLE workflow_schedules
+ ADD COLUMN IF NOT EXISTS concurrency_policy TEXT NOT NULL DEFAULT 'Forbid'
+ CONSTRAINT workflow_schedules_concurrency_policy_check
+ CHECK (concurrency_policy IN ('Forbid', 'Replace', 'Allow'));
+ -- Pending migrations share one transaction: do not leak the timeout.
+ SET LOCAL lock_timeout = '0';
+ `)
+}
+
async function applyWorkflowTriggerSharedFoundationSchema(db: DbClient): Promise<void> {
await db.query(`
CREATE TABLE IF NOT EXISTS workflow_approval_trigger_intents (
@@ -6349,6 +6373,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [
version: '0128_password_work_ownership',
apply: applyPasswordWorkOwnershipSchema,
},
+ {
+ version: '0129_workflow_schedules_concurrency_policy',
+ apply: applyWorkflowScheduleConcurrencyPolicyMigration,
+ },
]
async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {
diff --git a/control-api/test/db.realPostgresMigration.integration.test.ts b/control-api/test/db.realPostgresMigration.integration.test.ts
index 01c8cc72d..af965ef74 100644
--- a/control-api/test/db.realPostgresMigration.integration.test.ts
+++ b/control-api/test/db.realPostgresMigration.integration.test.ts
@@ -1992,6 +1992,66 @@ describeRealPostgres('control-api real Postgres migrations', () => {
expect(stored.rows).toEqual([{ sequence_no: auditId, subject: 'host:1st:mcp-host/chatllm' }])
})
+ it('adds workflow_schedules.concurrency_policy idempotently with a Forbid default', async () => {
+ const { initDb } = await import('../src/db.js')
+ const connector = { connect: () => dbPool.connect() }
+ const version = '0129_workflow_schedules_concurrency_policy'
+
+ await initDb(connector)
+ // Forget the record so initDb re-runs the body over the existing column.
+ await dbPool.query('DELETE FROM schema_migrations WHERE version = $1', [version])
+ await initDb(connector)
+
+ const recorded = await dbPool.query<{ count: string }>(
+ 'SELECT count(*)::text AS count FROM schema_migrations WHERE version = $1',
+ [version]
+ )
+ expect(recorded.rows[0]?.count).toBe('1')
+
+ const column = await dbPool.query<{
+ column_default: string | null
+ is_nullable: string
+ data_type: string
+ }>(
+ `SELECT column_default, is_nullable, data_type
+ FROM information_schema.columns
+ WHERE table_schema = 'public'
+ AND table_name = 'workflow_schedules'
+ AND column_name = 'concurrency_policy'`
+ )
+ expect(column.rows).toEqual([
+ { column_default: "'Forbid'::text", is_nullable: 'NO', data_type: 'text' },
+ ])
+
+ const checks = await dbPool.query<{ conname: string }>(
+ `SELECT conname
+ FROM pg_constraint
+ WHERE conrelid = 'public.workflow_schedules'::regclass
+ AND conname = 'workflow_schedules_concurrency_policy_check'`
+ )
+ expect(checks.rows).toHaveLength(1)
+
+ const client = await dbPool.connect()
+ try {
+ await client.query('BEGIN')
+ const inserted = await client.query<{ concurrency_policy: string }>(
+ `INSERT INTO workflow_schedules (recipe_namespace, recipe_name, cron_expression, next_fire_at)
+ VALUES ('p3-forbid-ns', 'p3-forbid-recipe', '*/5 * * * *', now())
+ RETURNING concurrency_policy`
+ )
+ expect(inserted.rows[0]?.concurrency_policy).toBe('Forbid')
+ await expect(
+ client.query(
+ `UPDATE workflow_schedules SET concurrency_policy = 'Sometimes'
+ WHERE recipe_namespace = 'p3-forbid-ns' AND recipe_name = 'p3-forbid-recipe'`
+ )
+ ).rejects.toThrow(/workflow_schedules_concurrency_policy_check/)
+ } finally {
+ await client.query('ROLLBACK')
+ client.release()
+ }
+ })
+
it('recognizes deployed entity-change aliases without replaying migration DDL', async () => {
const { CONTROL_API_MIGRATIONS, initDb } = await import('../src/db.js')
const connector = { connect: () => dbPool.connect() }
diff --git a/control-api/test/db.workflowScheduleConcurrencyPolicyMigration.test.ts b/control-api/test/db.workflowScheduleConcurrencyPolicyMigration.test.ts
new file mode 100644
index 000000000..461db1007
--- /dev/null
+++ b/control-api/test/db.workflowScheduleConcurrencyPolicyMigration.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, it, vi } from 'vitest'
+
+// Mock pg exactly like the other db.*.test.ts specs so importing ../src/db.js
+// does not spin up a real Pool as a module side effect.
+vi.mock('pg', () => ({
+ Pool: vi.fn(function MockPool() {
+ return { connect: vi.fn(), query: vi.fn() }
+ }),
+}))
+
+const VERSION = '0129_workflow_schedules_concurrency_policy'
+
+type QueryResult = { rows: unknown[]; rowCount: number }
+
+function recordingQuery(appliedVersions: string[]) {
+ return vi.fn(
+ async (sql: string): Promise<QueryResult> =>
+ sql.includes('SELECT version FROM schema_migrations')
+ ? {
+ rows: appliedVersions.map(version => ({ version })),
+ rowCount: appliedVersions.length,
+ }
+ : { rows: [], rowCount: 0 }
+ )
+}
+
+describe('0129_workflow_schedules_concurrency_policy migration', () => {
+ it('is registered after the baseline and after 0128_password_work_ownership', async () => {
+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')
+ const versions = CONTROL_API_MIGRATIONS.map(migration => migration.version)
+ const baseline = versions.indexOf('0001_control_api_baseline')
+ const previous = versions.indexOf('0128_password_work_ownership')
+ const current = versions.indexOf(VERSION)
+ expect(baseline).toBeGreaterThanOrEqual(0)
+ expect(previous).toBeGreaterThan(baseline)
+ expect(current).toBeGreaterThan(previous)
+ })
+
+ it('adds a NOT NULL concurrency_policy column defaulting to Forbid with a named CHECK', async () => {
+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')
+ const migration = CONTROL_API_MIGRATIONS.find(candidate => candidate.version === VERSION)
+ expect(migration).toBeDefined()
+ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })
+
+ await migration!.apply({ query })
+
+ expect(query).toHaveBeenCalledTimes(1)
+ const sql = String(query.mock.calls[0]?.[0])
+ expect(sql).toContain('ALTER TABLE workflow_schedules')
+ expect(sql).toContain(
+ "ADD COLUMN IF NOT EXISTS concurrency_policy TEXT NOT NULL DEFAULT 'Forbid'"
+ )
+ expect(sql).toContain('CONSTRAINT workflow_schedules_concurrency_policy_check')
+ expect(sql).toContain("CHECK (concurrency_policy IN ('Forbid', 'Replace', 'Allow'))")
+ expect(sql).not.toMatch(/CREATE TABLE|DROP |UPDATE workflow_schedules/)
+ // Bounded lock wait, reset before the next pending migration in the shared
+ // transaction (precedent: reconcilePluginWorkloadSdkRuntimeContracts).
+ expect(sql.indexOf("SET LOCAL lock_timeout = '60s'")).toBeLessThan(
+ sql.indexOf('ALTER TABLE workflow_schedules')
+ )
+ expect(sql.indexOf("SET LOCAL lock_timeout = '0'")).toBeGreaterThan(
+ sql.indexOf('CHECK (concurrency_policy')
+ )
+ })
+
+ it('is idempotent: one guarded ADD COLUMN and no standalone ADD CONSTRAINT', async () => {
+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')
+ const migration = CONTROL_API_MIGRATIONS.find(candidate => candidate.version === VERSION)
+ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })
+
+ await migration!.apply({ query })
+ await migration!.apply({ query })
+
+ expect(query).toHaveBeenCalledTimes(2)
+ expect(String(query.mock.calls[1]?.[0])).toBe(String(query.mock.calls[0]?.[0]))
+ // The CHECK is part of the column definition, so `IF NOT EXISTS` skips it
+ // together with the column on a re-run. A standalone `ADD CONSTRAINT`
+ // would fail with "already exists" the second time.
+ expect(String(query.mock.calls[0]?.[0])).not.toMatch(/ADD CONSTRAINT/)
+ })
+
+ it('initDb applies it exactly once on a cluster that recorded every earlier migration', async () => {
+ const { CONTROL_API_MIGRATIONS, initDb } = await import('../src/db.js')
+ const earlier = CONTROL_API_MIGRATIONS.map(migration => migration.version).filter(
+ version => version !== VERSION
+ )
+ const query = recordingQuery(earlier)
+ const release = vi.fn()
+
+ await initDb({ connect: vi.fn().mockResolvedValue({ query, release }) } as never)
+
+ const sqls = query.mock.calls.map(([sql]) => String(sql))
+ expect(sqls.filter(sql => sql.includes('concurrency_policy'))).toHaveLength(1)
+ expect(sqls).not.toContainEqual(
+ expect.stringContaining('CREATE TABLE IF NOT EXISTS workflow_schedules')
+ )
+ expect(query).toHaveBeenCalledWith(
+ expect.stringContaining('INSERT INTO schema_migrations(version)'),
+ [VERSION]
+ )
+ expect(release).toHaveBeenCalledOnce()
+ })
+
+ it('initDb does not re-run it once recorded', async () => {
+ const { CONTROL_API_MIGRATIONS, initDb } = await import('../src/db.js')
+ const query = recordingQuery(CONTROL_API_MIGRATIONS.map(migration => migration.version))
+ const release = vi.fn()
+
+ await initDb({ connect: vi.fn().mockResolvedValue({ query, release }) } as never)
+
+ expect(query.mock.calls.map(([sql]) => String(sql))).not.toContainEqual(
+ expect.stringContaining('concurrency_policy')
+ )
+ })
+})