Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): make plugin SDK reconciliation fail closed
Alfredo Lopeza4751615aed4
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 25186a050..7ca75bea1 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.423",+ "version": "0.1.424","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.423",+ "version": "0.1.424","dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-api/package.json b/control-api/package.jsonindex 42d242d1f..fa5d70b7b 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.423",+ "version": "0.1.424","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.tsindex 901c4a68e..064c84be7 100644--- a/control-api/src/db.ts+++ b/control-api/src/db.ts@@ -2289,19 +2289,32 @@ async function applyGfsPermissionStoreSchema(db: DbClient): Promise<void> {/*** Reconcile all Plugin Workload SDK contracts that were edited in-place after* their migrations had already run on long-lived databases. This is one- * forward-only migration on purpose: re-running 0080 would relabel legitimate- * v2 terminal invocations and re-running 0081 would not repair existing- * constraints created from its earlier body.+ * forward-only migration on purpose: the migration runner never replays a+ * recorded version, so the repair must be an explicit new step rather than a+ * re-run of an historical migration.*/async function reconcilePluginWorkloadSdkRuntimeContracts(db: DbClient): Promise<void> {await db.query(`+ -- Runtime writers do not take the initDb advisory lock. Hold the table+ -- locks in the same logical order as finalization (invocation -> receipt+ -- -> provider attempt) before replacing validators or fencing rows. This+ -- closes the rolling-deploy race in which a writer could change a row+ -- between the ambiguity check and the repair UPDATE.+ LOCK TABLE+ plugin_workload_sdk_invocations,+ plugin_workload_sdk_invocation_attempts,+ plugin_workload_sdk_provider_attempts,+ agent_run_events+ IN SHARE ROW EXCLUSIVE MODE;+CREATE OR REPLACE FUNCTION governed_trace_safe_agent_run_metadata(event_kind TEXT, value JSONB)RETURNS BOOLEANLANGUAGE sqlIMMUTABLESET search_path = pg_catalog, publicAS $$- SELECT CASE+ SELECT COALESCE(CASE+ WHEN event_kind IS NULL THEN FALSEWHEN event_kind <> 'token_usage' THEN governed_trace_safe_metadata(value)ELSE jsonb_typeof(value) = 'object'AND octet_length(value::text) <= 16384@@ -2359,6 +2372,10 @@ async function reconcilePluginWorkloadSdkRuntimeContracts(db: DbClient): Promise'fallback_used', 'attempt_count', 'provider_attempt_id','provider_attempt_index']+ AND jsonb_typeof(value->'prompt_bridge'->'invocation_id') = 'string'+ AND jsonb_typeof(value->'prompt_bridge'->'provider_attempt_id') = 'string'+ AND jsonb_typeof(value->'prompt_bridge'->'attempt_generation') = 'number'+ AND jsonb_typeof(value->'prompt_bridge'->'provider_attempt_index') = 'number'AND (value->'prompt_bridge'->>'invocation_id') ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'AND (value->'prompt_bridge'->>'provider_attempt_id') ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'AND (value->'prompt_bridge'->>'attempt_generation') ~ '^[1-9][0-9]*$'@@ -2370,7 +2387,7 @@ async function reconcilePluginWorkloadSdkRuntimeContracts(db: DbClient): PromiseAND (value->'prompt_bridge'->>'attempt_count') ~ '^[1-4]$'))- END;+ END, FALSE);$$;ALTER FUNCTION governed_trace_safe_metadata(JSONB)@@ -2387,11 +2404,44 @@ async function reconcilePluginWorkloadSdkRuntimeContracts(db: DbClient): PromiseGRANT EXECUTE ON FUNCTION governed_trace_safe_agent_run_metadata(TEXT, JSONB)TO control_api_runtime;+ -- Changing a function body does not recheck rows already accepted by a+ -- CHECK that calls it. Reinstall the named constraint as NOT VALID, scan+ -- every historical row fail-closed, and only then validate the constraint.+ -- No row is rewritten or deleted: an invalid append-only history aborts+ -- the whole migration and requires an explicit data-governance decision.+ ALTER TABLE agent_run_events+ DROP CONSTRAINT IF EXISTS agent_run_events_check;+ ALTER TABLE agent_run_events+ DROP CONSTRAINT IF EXISTS agent_run_events_payload_metadata_check;+ ALTER TABLE agent_run_events+ ADD CONSTRAINT agent_run_events_check+ CHECK (governed_trace_safe_agent_run_metadata(event_type, payload_metadata) IS TRUE)+ NOT VALID;++ DO $$+ DECLARE invalid_count BIGINT;+ BEGIN+ SELECT COUNT(*)+ INTO invalid_count+ FROM agent_run_events+ WHERE governed_trace_safe_agent_run_metadata(event_type, payload_metadata)+ IS DISTINCT FROM TRUE;+ IF invalid_count > 0 THEN+ RAISE EXCEPTION+ 'cannot reconcile % historical agent_run_events rows with invalid payload metadata',+ invalid_count;+ END IF;+ END+ $$;++ ALTER TABLE agent_run_events+ VALIDATE CONSTRAINT agent_run_events_check;+ALTER TABLE plugin_workload_sdk_invocationsALTER COLUMN contract_version SET DEFAULT 1;DO $$- DECLARE ambiguous_count INTEGER;+ DECLARE ambiguous_count BIGINT;BEGINSELECT COUNT(*)INTO ambiguous_count@@ -2426,20 +2476,46 @@ async function reconcilePluginWorkloadSdkRuntimeContracts(db: DbClient): PromiseAND status = 'in_progress'AND lease_expires_at IS NULL;- UPDATE plugin_workload_sdk_invocations- SET contract_version = 1,- status = 'failed',- authorization_decision = CASE- WHEN authorization_decision = 'authorized' THEN 'migration_interrupted'- ELSE authorization_decision- END,- updated_at = now(),- completed_at = COALESCE(completed_at, now()),- lease_expires_at = NULL- WHERE id IN (- SELECT invocation_id- FROM plugin_workload_sdk_runtime_reconciled_invocations- );+ DO $$+ DECLARE expected_count BIGINT;+ DECLARE fenced_count BIGINT;+ BEGIN+ SELECT COUNT(*)+ INTO expected_count+ FROM plugin_workload_sdk_runtime_reconciled_invocations;++ UPDATE plugin_workload_sdk_invocations invocations+ SET contract_version = 1,+ status = 'failed',+ authorization_decision = CASE+ WHEN authorization_decision = 'authorized' THEN 'migration_interrupted'+ ELSE authorization_decision+ END,+ updated_at = now(),+ completed_at = COALESCE(completed_at, now()),+ lease_expires_at = NULL+ WHERE invocations.id IN (+ SELECT invocation_id+ FROM plugin_workload_sdk_runtime_reconciled_invocations+ )+ AND invocations.contract_version = 2+ AND invocations.status = 'in_progress'+ AND invocations.lease_expires_at IS NULL+ AND NOT EXISTS (+ SELECT 1+ FROM plugin_workload_sdk_provider_attempts attempts+ WHERE attempts.invocation_id = invocations.id+ AND attempts.attempt_generation = invocations.attempt_generation+ AND attempts.status IN ('in_progress', 'complete')+ );++ GET DIAGNOSTICS fenced_count = ROW_COUNT;+ IF fenced_count <> expected_count THEN+ RAISE EXCEPTION+ 'plugin workload SDK invocation state changed during reconciliation; retry safely';+ END IF;+ END+ $$;UPDATE plugin_workload_sdk_invocation_attempts attemptsSET status = 'failed',@@ -2450,6 +2526,15 @@ async function reconcilePluginWorkloadSdkRuntimeContracts(db: DbClient): PromiseAND attempts.attempt_generation = reconciled.attempt_generationAND attempts.status = 'in_progress';+ UPDATE plugin_workload_sdk_provider_attempts attempts+ SET status = 'failed',+ completed_at = COALESCE(attempts.completed_at, now()),+ lease_expires_at = NULL+ FROM plugin_workload_sdk_runtime_reconciled_invocations reconciled+ WHERE attempts.invocation_id = reconciled.invocation_id+ AND attempts.attempt_generation = reconciled.attempt_generation+ AND attempts.status IN ('reserved', 'in_progress');+ALTER TABLE plugin_workload_sdk_invocationsDROP CONSTRAINT IF EXISTS plugin_workload_sdk_invocations_v2_lease_check;ALTER TABLE plugin_workload_sdk_invocationsdiff --git a/control-api/test/db.pluginWorkloadSdkRuntimeContract.realPostgres.integration.test.ts b/control-api/test/db.pluginWorkloadSdkRuntimeContract.realPostgres.integration.test.tsindex 72226da7b..554865ec3 100644--- a/control-api/test/db.pluginWorkloadSdkRuntimeContract.realPostgres.integration.test.ts+++ b/control-api/test/db.pluginWorkloadSdkRuntimeContract.realPostgres.integration.test.ts@@ -26,17 +26,14 @@ async function commit(client: PoolClient): Promise<void> {describeRealPostgres('Plugin Workload SDK runtime-contract upgrade on real PostgreSQL', () => {const database = `control_api_sdk_contract_${randomBytes(6).toString('hex')}`- const connectionString = databaseUrl(- adminUrl ?? 'postgresql://[email protected]/postgres',- database- )let adminPool: Poollet dbPool: PoolbeforeAll(async () => {+ if (!adminUrl) throw new Error('CONTROL_API_REAL_PG_ADMIN_URL is required')adminPool = new Pool({ connectionString: adminUrl })await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)- dbPool = new Pool({ connectionString })+ dbPool = new Pool({ connectionString: databaseUrl(adminUrl, database) })await initDb({ connect: () => dbPool.connect() })})@@ -152,6 +149,23 @@ describeRealPostgres('Plugin Workload SDK runtime-contract upgrade on real PostgAND NOT (value ? 'prompt_bridge'));$$;+ ALTER FUNCTION governed_trace_safe_metadata(JSONB) RESET search_path;+ ALTER FUNCTION governed_trace_safe_agent_run_metadata(TEXT, JSONB) RESET search_path;+ REVOKE ALL ON FUNCTION governed_trace_safe_metadata(JSONB)+ FROM PUBLIC, control_api_runtime, trace_maintenance_runtime, workflow_recipes_runtime;+ REVOKE ALL ON FUNCTION governed_trace_safe_agent_run_metadata(TEXT, JSONB)+ FROM PUBLIC, control_api_runtime, trace_maintenance_runtime, workflow_recipes_runtime;+ GRANT EXECUTE ON FUNCTION governed_trace_safe_metadata(JSONB)+ TO control_api_runtime, trace_maintenance_runtime, workflow_recipes_runtime;+ GRANT EXECUTE ON FUNCTION governed_trace_safe_agent_run_metadata(TEXT, JSONB)+ TO control_api_runtime, trace_maintenance_runtime, workflow_recipes_runtime;+ ALTER TABLE agent_run_events+ DROP CONSTRAINT IF EXISTS agent_run_events_check;+ ALTER TABLE agent_run_events+ DROP CONSTRAINT IF EXISTS agent_run_events_payload_metadata_check;+ ALTER TABLE agent_run_events+ ADD CONSTRAINT agent_run_events_check+ CHECK (governed_trace_safe_agent_run_metadata(event_type, payload_metadata));ALTER TABLE plugin_workload_sdk_invocationsALTER COLUMN contract_version SET DEFAULT 2;ALTER TABLE plugin_workload_sdk_invocations@@ -160,12 +174,59 @@ describeRealPostgres('Plugin Workload SDK runtime-contract upgrade on real PostgDROP CONSTRAINT IF EXISTS plugin_workload_sdk_provider_attempts_status_check;ALTER TABLE plugin_workload_sdk_provider_attemptsADD CONSTRAINT plugin_workload_sdk_provider_attempts_status_check- CHECK (status IN ('reserved','in_progress','complete','failed','provider_unavailable'));+ CHECK (status IN ('reserved','in_progress','complete','failed','provider_unavailable'));DELETE FROM schema_migrationsWHERE version = '0090_plugin_workload_sdk_runtime_contract_reconciliation';`)}+ async function seedTraceEvent(+ payloadMetadata: Record<string, unknown>,+ prefix: string+ ): Promise<string> {+ const eventId = randomUUID()+ const client = await dbPool.connect()+ try {+ await begin(client)+ const payloadSha256 = randomBytes(32).toString('hex')+ const occurredAt = new Date()+ await client.query(+ `INSERT INTO agent_run_events+ (event_id, source_kind, source_service, source_event_id, idempotency_key,+ run_id, span_id, origin, event_type, outcome, agent_sub, payload_metadata,+ payload_sha256, occurred_at)+ VALUES ($1, 'control_api_local', 'control-api', $2, $3, $4, 'span-1',+ 'api', 'token_usage', 'succeeded', 'integration-test', $5::jsonb, $6, $7)`,+ [+ eventId,+ `${prefix}-${eventId}`,+ randomBytes(32).toString('hex'),+ randomUUID(),+ JSON.stringify(payloadMetadata),+ payloadSha256,+ occurredAt,+ ]+ )+ await client.query(+ `INSERT INTO governed_event_stream+ (event_family, event_id, schema_version, occurred_at, ingested_at, payload_sha256)+ VALUES ('agent_run', $1, 1, $2, $3, $4)`,+ [eventId, occurredAt, new Date(), payloadSha256]+ )+ await commit(client)+ return eventId+ } catch (error) {+ try {+ await client.query('ROLLBACK')+ } catch {+ // Preserve the original assertion error.+ }+ throw error+ } finally {+ client.release()+ }+ }+function validPayload(invocationId = randomUUID(), providerAttemptId = randomUUID()) {return {request_ref: 'a'.repeat(64),@@ -192,6 +253,43 @@ describeRealPostgres('Plugin Workload SDK runtime-contract upgrade on real Postgit('repairs the historical runtime contracts, finalizes usage, and is idempotent', async () => {await restoreHistoricalRuntimeState()+ const historicalState = await dbPool.query<{+ validator_config: string[] | null+ metadata_config: string[] | null+ trace_validator: boolean+ workflow_validator: boolean+ workflow_metadata: boolean+ }>(+ `SELECT+ validator.proconfig AS validator_config,+ metadata.proconfig AS metadata_config,+ has_function_privilege('trace_maintenance_runtime', 'public.governed_trace_safe_agent_run_metadata(text,jsonb)', 'EXECUTE') AS trace_validator,+ has_function_privilege('workflow_recipes_runtime', 'public.governed_trace_safe_agent_run_metadata(text,jsonb)', 'EXECUTE') AS workflow_validator,+ has_function_privilege('workflow_recipes_runtime', 'public.governed_trace_safe_metadata(jsonb)', 'EXECUTE') AS workflow_metadata+ FROM pg_proc validator+ JOIN pg_proc metadata+ ON metadata.proname = 'governed_trace_safe_metadata'+ AND metadata.proargtypes::text = '3802'+ WHERE validator.proname = 'governed_trace_safe_agent_run_metadata'+ AND validator.proargtypes::text = '25 3802'`+ )+ expect(historicalState.rows[0]).toMatchObject({+ validator_config: null,+ metadata_config: null,+ trace_validator: true,+ workflow_validator: true,+ workflow_metadata: true,+ })++ const historicalInvalidEventId = await seedTraceEvent(+ {+ source_kind: 'unknown',+ input_tokens: 1,+ output_tokens: 1,+ },+ 'historical'+ )+const historicalClient = await dbPool.connect()let redInput: PromptBridgeFinalizationInputtry {@@ -211,6 +309,31 @@ describeRealPostgres('Plugin Workload SDK runtime-contract upgrade on real Postg)expect(rejected.rows[0]?.accepted).toBe(false)+ await expect(initDb({ connect: () => dbPool.connect() })).rejects.toThrow(+ /cannot reconcile .* historical agent_run_events rows with invalid payload metadata/+ )+ const failedMigrationState = await dbPool.query<{ migration_count: string; row_count: string }>(+ `SELECT+ (SELECT COUNT(*)::text FROM schema_migrations+ WHERE version = '0090_plugin_workload_sdk_runtime_contract_reconciliation') AS migration_count,+ (SELECT COUNT(*)::text FROM agent_run_events WHERE event_id = $1) AS row_count`,+ [historicalInvalidEventId]+ )+ expect(failedMigrationState.rows[0]).toEqual({ migration_count: '0', row_count: '1' })+ const historicalCleanupClient = await dbPool.connect()+ try {+ await begin(historicalCleanupClient)+ await historicalCleanupClient.query('DELETE FROM agent_run_events WHERE event_id = $1', [+ historicalInvalidEventId,+ ])+ await historicalCleanupClient.query('DELETE FROM governed_event_stream WHERE event_id = $1', [+ historicalInvalidEventId,+ ])+ await commit(historicalCleanupClient)+ } finally {+ historicalCleanupClient.release()+ }+const skippedAttempt = {id: randomUUID(),invocationId: randomUUID(),@@ -292,6 +415,7 @@ describeRealPostgres('Plugin Workload SDK runtime-contract upgrade on real Postgconst legacyClient = await dbPool.connect()const legacyInvocationId = randomUUID()+ const legacyProviderAttemptId = randomUUID()try {await legacyClient.query(`INSERT INTO plugin_workload_sdk_invocations@@ -310,6 +434,14 @@ describeRealPostgres('Plugin Workload SDK runtime-contract upgrade on real Postg'promptBridge', '["primary-openai"]'::jsonb, 'in_progress', NULL)`,[legacyInvocationId])+ await legacyClient.query(+ `INSERT INTO plugin_workload_sdk_provider_attempts+ (id, invocation_id, recipe_namespace, recipe_name, attempt_generation,+ attempt_index, target_ref, provider, model, credential_slot, status)+ VALUES ($1, $2, 'sandbox-recipes', 'legacy-v2-no-lease', 1, 1,+ 'primary-openai', 'openai', 'gpt-4o-mini', 'openai-api-key', 'reserved')`,+ [legacyProviderAttemptId, legacyInvocationId]+ )} finally {legacyClient.release()}@@ -331,6 +463,17 @@ describeRealPostgres('Plugin Workload SDK runtime-contract upgrade on real Postgstatus: 'failed',authorization_decision: 'migration_interrupted',})+ const repairedProviderAttempt = await dbPool.query<{+ status: string+ completed_at: Date | null+ }>(+ `SELECT status, completed_at+ FROM plugin_workload_sdk_provider_attempts+ WHERE id = $1`,+ [legacyProviderAttemptId]+ )+ expect(repairedProviderAttempt.rows[0]?.status).toBe('failed')+ expect(repairedProviderAttempt.rows[0]?.completed_at).not.toBeNull()const accepted = await dbPool.query<{ accepted: boolean }>(`SELECT governed_trace_safe_agent_run_metadata('token_usage', $1::jsonb) AS accepted`,@@ -370,11 +513,61 @@ describeRealPostgres('Plugin Workload SDK runtime-contract upgrade on real Postg}),])+ const rejectedNullUuid = await dbPool.query<{ accepted: boolean }>(+ `SELECT governed_trace_safe_agent_run_metadata('token_usage', $1::jsonb) AS accepted`,+ [+ JSON.stringify({+ ...validPayload(),+ prompt_bridge: { ...validPayload().prompt_bridge, invocation_id: null },+ }),+ ]+ )+ const rejectedNumericString = await dbPool.query<{ accepted: boolean }>(+ `SELECT governed_trace_safe_agent_run_metadata('token_usage', $1::jsonb) AS accepted`,+ [+ JSON.stringify({+ ...validPayload(),+ prompt_bridge: { ...validPayload().prompt_bridge, attempt_generation: '1' },+ }),+ ]+ )+ const rejectedMissingRequired = await dbPool.query<{ accepted: boolean }>(+ `SELECT governed_trace_safe_agent_run_metadata('token_usage', $1::jsonb) AS accepted`,+ [+ JSON.stringify(+ Object.fromEntries(+ Object.entries(validPayload()).filter(([key]) => key !== 'cache_tokens_reported')+ )+ ),+ ]+ )expect(accepted.rows[0]?.accepted).toBe(true)expect(rejectedTopLevel.rows[0]?.accepted).toBe(false)expect(rejectedNested.rows[0]?.accepted).toBe(false)expect(rejectedUuid.rows[0]?.accepted).toBe(false)expect(rejectedCount.rows[0]?.accepted).toBe(false)+ expect(rejectedNullUuid.rows[0]?.accepted).toBe(false)+ expect(rejectedNumericString.rows[0]?.accepted).toBe(false)+ expect(rejectedMissingRequired.rows[0]?.accepted).toBe(false)++ await expect(+ seedTraceEvent(+ {+ ...validPayload(),+ prompt_bridge: { ...validPayload().prompt_bridge, invocation_id: null },+ },+ 'runtime'+ )+ ).rejects.toThrow(/agent_run_events_check/)+ await expect(+ seedTraceEvent(+ {+ ...validPayload(),+ prompt_bridge: { ...validPayload().prompt_bridge, attempt_generation: '1' },+ },+ 'runtime'+ )+ ).rejects.toThrow(/agent_run_events_check/)const repairedSkippedId = randomUUID()await dbPool.query(@@ -386,6 +579,19 @@ describeRealPostgres('Plugin Workload SDK runtime-contract upgrade on real Postg[repairedSkippedId, randomUUID()])+ const invalidLeaseInvocationId = randomUUID()+ await expect(+ dbPool.query(+ `INSERT INTO plugin_workload_sdk_invocations+ (id, recipe_namespace, recipe_name, caller_ref, method, detail,+ idempotency_key_hash, payload_hash, status, authorization_decision,+ contract_version, attempt_generation, lease_expires_at)+ VALUES ($1, 'sandbox-recipes', 'invalid-v2-lease', 'integration-test',+ 'promptBridge', '{}', $2, $3, 'in_progress', 'authorized', 2, 1, NULL)`,+ [invalidLeaseInvocationId, randomBytes(32).toString('hex'), randomBytes(32).toString('hex')]+ )+ ).rejects.toThrow(/plugin_workload_sdk_invocations_v2_lease_check/)+const exactClient = await dbPool.connect()let exactInput: PromptBridgeFinalizationInputtry {@@ -425,6 +631,7 @@ describeRealPostgres('Plugin Workload SDK runtime-contract upgrade on real Postgdefault_value: string | nulllease_check: stringattempt_check: string+ trace_check: string}>(`SELECT(SELECT column_default@@ -433,15 +640,19 @@ describeRealPostgres('Plugin Workload SDK runtime-contract upgrade on real PostgAND table_name = 'plugin_workload_sdk_invocations'AND column_name = 'contract_version') AS default_value,(SELECT pg_get_constraintdef(oid)- FROM pg_constraint+ FROM pg_constraintWHERE conname = 'plugin_workload_sdk_invocations_v2_lease_check') AS lease_check,(SELECT pg_get_constraintdef(oid)FROM pg_constraint- WHERE conname = 'plugin_workload_sdk_provider_attempts_status_check') AS attempt_check`+ WHERE conname = 'plugin_workload_sdk_provider_attempts_status_check') AS attempt_check,+ (SELECT pg_get_constraintdef(oid)+ FROM pg_constraint+ WHERE conname = 'agent_run_events_check') AS trace_check`)expect(contractState.rows[0]?.default_value).toBe('1')expect(contractState.rows[0]?.lease_check).toContain('lease_expires_at IS NOT NULL')expect(contractState.rows[0]?.attempt_check).toContain("'skipped'")+ expect(contractState.rows[0]?.trace_check).toContain('IS TRUE')const functionState = await dbPool.query<{validator_config: string[] | nulldiff --git a/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts b/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.tsindex 921a32bed..a80e7677e 100644--- a/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts+++ b/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts@@ -56,6 +56,12 @@ describe('Plugin Workload SDK runtime-contract reconciliation migration', () =>expect(migrationSql).toContain('plugin_workload_sdk_provider_attempts_status_check')expect(migrationSql).toContain("'skipped'")expect(migrationSql).toContain('cannot reconcile % v2 invocations without leases')+ expect(migrationSql).toContain('LOCK TABLE')+ expect(migrationSql).toContain('agent_run_events_check')+ expect(migrationSql).toContain('IS DISTINCT FROM TRUE')+ expect(migrationSql).toContain('IS TRUE)')+ expect(migrationSql).toContain('state changed during reconciliation')+ expect(migrationSql).toContain("attempts.status IN ('reserved', 'in_progress')")const recordCalls = clientQuery.mock.calls.filter(([, params]) => Array.isArray(params) && params[0] === migration?.version@@ -77,6 +83,13 @@ describe('Plugin Workload SDK runtime-contract reconciliation migration', () =>expect(migrationSql).toContain('WHERE key_name NOT IN')expect(migrationSql).toContain("'prompt_bridge'")expect(migrationSql).toContain("jsonb_typeof(value->'prompt_bridge') = 'object'")+ expect(migrationSql).toContain(+ "jsonb_typeof(value->'prompt_bridge'->'invocation_id') = 'string'"+ )+ expect(migrationSql).toContain(+ "jsonb_typeof(value->'prompt_bridge'->'attempt_generation') = 'number'"+ )+ expect(migrationSql).toContain('COALESCE(CASE')expect(migrationSql).toContain("value->'prompt_bridge' ?& ARRAY[")expect(migrationSql).toContain('FROM PUBLIC, control_api_runtime, trace_maintenance_runtime, workflow_recipes_runtime'