Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): reconcile plugin sdk runtime contracts
Alfredo Lopez82c4a02774e0
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex c78677b12..25186a050 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.422",+ "version": "0.1.423","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.422",+ "version": "0.1.423","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 39923958d..42d242d1f 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.422",+ "version": "0.1.423","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 18db7c00b..901c4a68e 100644--- a/control-api/src/db.ts+++ b/control-api/src/db.ts@@ -2286,6 +2286,188 @@ 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.+ */+async function reconcilePluginWorkloadSdkRuntimeContracts(db: DbClient): Promise<void> {+ await db.query(`+ CREATE OR REPLACE FUNCTION governed_trace_safe_agent_run_metadata(event_kind TEXT, value JSONB)+ RETURNS BOOLEAN+ LANGUAGE sql+ IMMUTABLE+ SET search_path = pg_catalog, public+ AS $$+ SELECT CASE+ WHEN event_kind <> 'token_usage' THEN governed_trace_safe_metadata(value)+ ELSE jsonb_typeof(value) = 'object'+ AND octet_length(value::text) <= 16384+ AND value ?& ARRAY[+ 'request_ref', 'provider', 'model', 'source_kind',+ 'input_tokens', 'output_tokens', 'cache_read_tokens', 'cache_write_tokens',+ 'cache_tokens_reported'+ ]+ AND NOT EXISTS (+ SELECT 1+ FROM jsonb_object_keys(value) AS key_name+ WHERE key_name NOT IN (+ 'request_ref', 'provider', 'model', 'source_kind',+ 'input_tokens', 'output_tokens', 'cache_read_tokens',+ 'cache_write_tokens', 'cache_tokens_reported', 'iteration', 'prompt_bridge'+ )+ )+ AND jsonb_typeof(value->'request_ref') = 'string'+ AND (value->>'request_ref') ~ '^[0-9a-f]{64}$'+ AND jsonb_typeof(value->'provider') = 'string'+ AND jsonb_typeof(value->'model') = 'string'+ AND jsonb_typeof(value->'source_kind') = 'string'+ AND value->>'source_kind' IN ('channel', 'desktop', 'workflow', 'cron', 'unknown', 'plugin_workload_sdk')+ AND jsonb_typeof(value->'input_tokens') = 'number'+ AND (value->>'input_tokens') ~ '^(0|[1-9][0-9]*)$'+ AND jsonb_typeof(value->'output_tokens') = 'number'+ AND (value->>'output_tokens') ~ '^(0|[1-9][0-9]*)$'+ AND jsonb_typeof(value->'cache_read_tokens') = 'number'+ AND (value->>'cache_read_tokens') ~ '^(0|[1-9][0-9]*)$'+ AND jsonb_typeof(value->'cache_write_tokens') = 'number'+ AND (value->>'cache_write_tokens') ~ '^(0|[1-9][0-9]*)$'+ AND jsonb_typeof(value->'cache_tokens_reported') = 'boolean'+ AND (+ NOT (value ? 'iteration')+ OR (+ jsonb_typeof(value->'iteration') = 'number'+ AND (value->>'iteration') ~ '^(0|[1-9][0-9]*)$'+ )+ )+ AND (+ NOT (value ? 'prompt_bridge')+ OR (+ jsonb_typeof(value->'prompt_bridge') = 'object'+ AND NOT EXISTS (+ SELECT 1+ FROM jsonb_object_keys(value->'prompt_bridge') AS key_name+ WHERE key_name NOT IN (+ 'invocation_id', 'attempt_generation', 'target_ref',+ 'fallback_used', 'attempt_count', 'provider_attempt_id',+ 'provider_attempt_index'+ )+ )+ AND value->'prompt_bridge' ?& ARRAY[+ 'invocation_id', 'attempt_generation', 'target_ref',+ 'fallback_used', 'attempt_count', 'provider_attempt_id',+ 'provider_attempt_index'+ ]+ 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]*$'+ AND (value->'prompt_bridge'->>'provider_attempt_index') ~ '^[1-4]$'+ AND jsonb_typeof(value->'prompt_bridge'->'target_ref') = 'string'+ AND char_length(value->'prompt_bridge'->>'target_ref') BETWEEN 1 AND 256+ AND jsonb_typeof(value->'prompt_bridge'->'fallback_used') = 'boolean'+ AND jsonb_typeof(value->'prompt_bridge'->'attempt_count') = 'number'+ AND (value->'prompt_bridge'->>'attempt_count') ~ '^[1-4]$'+ )+ )+ END;+ $$;++ ALTER FUNCTION governed_trace_safe_metadata(JSONB)+ SET search_path = pg_catalog, public;+ ALTER FUNCTION governed_trace_safe_agent_run_metadata(TEXT, JSONB)+ SET search_path = pg_catalog, public;++ 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;+ GRANT EXECUTE ON FUNCTION governed_trace_safe_agent_run_metadata(TEXT, JSONB)+ TO control_api_runtime;++ ALTER TABLE plugin_workload_sdk_invocations+ ALTER COLUMN contract_version SET DEFAULT 1;++ DO $$+ DECLARE ambiguous_count INTEGER;+ BEGIN+ SELECT COUNT(*)+ INTO ambiguous_count+ FROM plugin_workload_sdk_invocations invocations+ WHERE invocations.contract_version = 2+ AND invocations.status = 'in_progress'+ AND invocations.lease_expires_at IS NULL+ AND 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')+ );+ IF ambiguous_count > 0 THEN+ RAISE EXCEPTION+ 'cannot reconcile % v2 invocations without leases with a physical provider attempt',+ ambiguous_count;+ END IF;+ END+ $$;++ CREATE TEMP TABLE plugin_workload_sdk_runtime_reconciled_invocations (+ invocation_id UUID PRIMARY KEY,+ attempt_generation INTEGER NOT NULL+ ) ON COMMIT DROP;++ INSERT INTO plugin_workload_sdk_runtime_reconciled_invocations (invocation_id, attempt_generation)+ SELECT id, attempt_generation+ FROM plugin_workload_sdk_invocations+ WHERE contract_version = 2+ AND 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+ );++ UPDATE plugin_workload_sdk_invocation_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_progress';++ ALTER TABLE plugin_workload_sdk_invocations+ DROP CONSTRAINT IF EXISTS plugin_workload_sdk_invocations_v2_lease_check;+ ALTER TABLE plugin_workload_sdk_invocations+ ADD CONSTRAINT plugin_workload_sdk_invocations_v2_lease_check+ CHECK (+ contract_version = 1+ OR status <> 'in_progress'+ OR lease_expires_at IS NOT NULL+ );++ ALTER TABLE plugin_workload_sdk_provider_attempts+ DROP CONSTRAINT IF EXISTS plugin_workload_sdk_provider_attempts_status_check;+ ALTER TABLE plugin_workload_sdk_provider_attempts+ ADD CONSTRAINT plugin_workload_sdk_provider_attempts_status_check+ CHECK (status IN ('reserved','in_progress','complete','failed','provider_unavailable','skipped'));+ `)+}+// Exported (read-only) so the migration-order invariant test can assert the// array is monotonic by version-string. Applied strictly in array order and// tracked by full version-string in `schema_migrations`, so a non-monotonic@@ -5144,6 +5326,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [version: '0089_plugin_workload_sdk_credential_ticket_runtime_access',apply: addPluginWorkloadSdkCredentialTicketRuntimeAccess,},+ {+ version: '0090_plugin_workload_sdk_runtime_contract_reconciliation',+ apply: reconcilePluginWorkloadSdkRuntimeContracts,+ },]async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {diff --git a/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.ts b/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.tsindex addd96a49..f7f6f6dd1 100644--- a/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.ts+++ b/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.ts@@ -70,16 +70,16 @@ describe('plugin workload SDK protocol migration', () => {expect(contractEntries).toEqual([['plugin_workload_sdk_credential_ticket_jtis', 'legacy_dml']])})- it('registers the credential-ticket ACL repair as migration 0089', () => {+ it('registers the credential-ticket ACL repair as migration 0089 before the runtime reconciliation', () => {const dbPath = join(dirname(fileURLToPath(import.meta.url)), '../src/db.ts')const source = readFileSync(dbPath, 'utf8')expect(source).toMatch(/version: '0089_plugin_workload_sdk_credential_ticket_runtime_access',\s+apply: addPluginWorkloadSdkCredentialTicketRuntimeAccess/)- expect(- source.indexOf("version: '0089_plugin_workload_sdk_credential_ticket_runtime_access'")- ).toBe(source.lastIndexOf("version: '"))+ expect(source).toMatch(+ /version: '0090_plugin_workload_sdk_runtime_contract_reconciliation',\s+apply: reconcilePluginWorkloadSdkRuntimeContracts/+ )})it('preserves only complete ordered active policies while adding the attempt ledger', async () => {diff --git a/control-api/test/db.pluginWorkloadSdkRuntimeContract.realPostgres.integration.test.ts b/control-api/test/db.pluginWorkloadSdkRuntimeContract.realPostgres.integration.test.tsnew file mode 100644index 000000000..72226da7b--- /dev/null+++ b/control-api/test/db.pluginWorkloadSdkRuntimeContract.realPostgres.integration.test.ts@@ -0,0 +1,495 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { randomBytes, randomUUID } from 'node:crypto'+import { Pool, type PoolClient } from 'pg'+import { initDb } from '../src/db.js'+import {+ type PromptBridgeFinalizationInput,+ finalizePromptBridgeInTransaction,+} from '../src/services/pluginWorkloadSdkFinalization.js'++const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL+const describeRealPostgres = adminUrl ? describe : describe.skip++function databaseUrl(baseUrl: string, database: string): string {+ const url = new URL(baseUrl)+ url.pathname = `/${database}`+ return url.toString()+}++async function begin(client: PoolClient): Promise<void> {+ await client.query('BEGIN')+}++async function commit(client: PoolClient): Promise<void> {+ await client.query('COMMIT')+}++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: Pool+ let dbPool: Pool++ beforeAll(async () => {+ adminPool = new Pool({ connectionString: adminUrl })+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)+ dbPool = new Pool({ connectionString })+ await initDb({ connect: () => dbPool.connect() })+ })++ afterAll(async () => {+ await dbPool?.end()+ if (adminPool) {+ await adminPool.query(+ `SELECT pg_terminate_backend(pid)+ FROM pg_stat_activity+ WHERE datname = $1+ AND pid <> pg_backend_pid()`,+ [database]+ )+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)+ await adminPool.end()+ }+ })++ async function seedAttempt(+ client: PoolClient,+ options: { contractVersion: 1 | 2; lease: boolean; status?: 'in_progress' | 'failed' } = {+ contractVersion: 2,+ lease: true,+ }+ ): Promise<PromptBridgeFinalizationInput> {+ const invocationId = randomUUID()+ const providerAttemptId = randomUUID()+ const recipeNamespace = 'sandbox-recipes'+ const recipeName = `runtime-contract-${invocationId}`+ const target = {+ targetRef: 'primary-openai',+ provider: 'openai',+ model: 'gpt-4o-mini',+ credentialSlot: 'openai-api-key',+ }+ const leaseSql = options.lease ? "now() + interval '5 minutes'" : 'NULL'+ const status = options.status ?? 'in_progress'+ await client.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, $2, $3, 'integration-test', 'promptBridge', '{}',+ $4, $5, $6, 'authorized', $7, 1, ${leaseSql})`,+ [+ invocationId,+ recipeNamespace,+ recipeName,+ randomBytes(32).toString('hex'),+ randomBytes(32).toString('hex'),+ status,+ options.contractVersion,+ ]+ )+ await client.query(+ `INSERT INTO plugin_workload_sdk_invocation_attempts+ (invocation_id, recipe_namespace, recipe_name, attempt_generation,+ method, target_refs, status, lease_expires_at)+ VALUES ($1, $2, $3, 1, 'promptBridge', $4::jsonb, $5, ${leaseSql})`,+ [invocationId, recipeNamespace, recipeName, JSON.stringify([target.targetRef]), status]+ )+ await client.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,+ lease_expires_at)+ VALUES ($1, $2, $3, $4, 1, 1, $5, $6, $7, $8, 'in_progress',+ now() + interval '5 minutes')`,+ [+ providerAttemptId,+ invocationId,+ recipeNamespace,+ recipeName,+ target.targetRef,+ target.provider,+ target.model,+ target.credentialSlot,+ ]+ )+ return {+ invocationId,+ recipeNamespace,+ recipeName,+ hostRef: 'mcp-host/integration',+ attemptGeneration: 1,+ providerAttemptId,+ providerAttemptIndex: 1,+ status: 'complete',+ target,+ reason: 'integration_complete',+ usage: {+ llmSecretName: 'openai-api-key',+ callerRef: 'integration-test',+ fallbackUsed: false,+ attemptCount: 1,+ inputTokens: 23,+ outputTokens: 11,+ },+ }+ }++ async function restoreHistoricalRuntimeState(): Promise<void> {+ await dbPool.query(`+ CREATE OR REPLACE FUNCTION governed_trace_safe_agent_run_metadata(event_kind TEXT, value JSONB)+ RETURNS BOOLEAN+ LANGUAGE sql+ IMMUTABLE+ AS $$+ SELECT event_kind <> 'token_usage'+ OR (+ jsonb_typeof(value) = 'object'+ AND value->>'source_kind' IN ('channel', 'desktop', 'workflow', 'cron', 'unknown')+ AND NOT (value ? 'prompt_bridge')+ );+ $$;+ ALTER TABLE plugin_workload_sdk_invocations+ ALTER COLUMN contract_version SET DEFAULT 2;+ ALTER TABLE plugin_workload_sdk_invocations+ DROP CONSTRAINT IF EXISTS plugin_workload_sdk_invocations_v2_lease_check;+ ALTER TABLE plugin_workload_sdk_provider_attempts+ DROP CONSTRAINT IF EXISTS plugin_workload_sdk_provider_attempts_status_check;+ ALTER TABLE plugin_workload_sdk_provider_attempts+ ADD CONSTRAINT plugin_workload_sdk_provider_attempts_status_check+ CHECK (status IN ('reserved','in_progress','complete','failed','provider_unavailable'));+ DELETE FROM schema_migrations+ WHERE version = '0090_plugin_workload_sdk_runtime_contract_reconciliation';+ `)+ }++ function validPayload(invocationId = randomUUID(), providerAttemptId = randomUUID()) {+ return {+ request_ref: 'a'.repeat(64),+ provider: 'openai',+ model: 'gpt-4o-mini',+ source_kind: 'plugin_workload_sdk',+ input_tokens: 23,+ output_tokens: 11,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ cache_tokens_reported: false,+ prompt_bridge: {+ invocation_id: invocationId,+ attempt_generation: 1,+ target_ref: 'primary-openai',+ fallback_used: false,+ attempt_count: 1,+ provider_attempt_id: providerAttemptId,+ provider_attempt_index: 1,+ },+ }+ }++ it('repairs the historical runtime contracts, finalizes usage, and is idempotent', async () => {+ await restoreHistoricalRuntimeState()++ const historicalClient = await dbPool.connect()+ let redInput: PromptBridgeFinalizationInput+ try {+ await begin(historicalClient)+ redInput = await seedAttempt(historicalClient, { contractVersion: 2, lease: true })+ await expect(finalizePromptBridgeInTransaction(redInput, historicalClient)).rejects.toThrow(+ /agent_run_events_check/+ )+ await historicalClient.query('ROLLBACK')+ } finally {+ historicalClient.release()+ }++ const rejected = await dbPool.query<{ accepted: boolean }>(+ `SELECT governed_trace_safe_agent_run_metadata('token_usage', $1::jsonb) AS accepted`,+ [JSON.stringify(validPayload(redInput!.invocationId, redInput!.providerAttemptId))]+ )+ expect(rejected.rows[0]?.accepted).toBe(false)++ const skippedAttempt = {+ id: randomUUID(),+ invocationId: randomUUID(),+ }+ await expect(+ dbPool.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', 'historical-skip', 1, 1,+ 'primary-openai', 'openai', 'gpt-4o-mini', 'openai-api-key', 'skipped')`,+ [skippedAttempt.id, skippedAttempt.invocationId]+ )+ ).rejects.toThrow(/plugin_workload_sdk_provider_attempts_status_check/)++ const ambiguousInvocationId = randomUUID()+ const ambiguousProviderAttemptId = randomUUID()+ const ambiguousClient = await dbPool.connect()+ try {+ await ambiguousClient.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', 'ambiguous-v2-no-lease', 'integration-test',+ 'promptBridge', '{}', $2, $3, 'in_progress', 'authorized', 2, 1, NULL)`,+ [ambiguousInvocationId, randomBytes(32).toString('hex'), randomBytes(32).toString('hex')]+ )+ await ambiguousClient.query(+ `INSERT INTO plugin_workload_sdk_invocation_attempts+ (invocation_id, recipe_namespace, recipe_name, attempt_generation,+ method, target_refs, status, lease_expires_at)+ VALUES ($1, 'sandbox-recipes', 'ambiguous-v2-no-lease', 1,+ 'promptBridge', '["primary-openai"]'::jsonb, 'in_progress', NULL)`,+ [ambiguousInvocationId]+ )+ await ambiguousClient.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,+ lease_expires_at)+ VALUES ($1, $2, 'sandbox-recipes', 'ambiguous-v2-no-lease', 1, 1,+ 'primary-openai', 'openai', 'gpt-4o-mini', 'openai-api-key',+ 'in_progress', now() + interval '5 minutes')`,+ [ambiguousProviderAttemptId, ambiguousInvocationId]+ )+ } finally {+ ambiguousClient.release()+ }++ await expect(initDb({ connect: () => dbPool.connect() })).rejects.toThrow(+ /cannot reconcile .* v2 invocations without leases with a physical provider attempt/+ )+ const ambiguousState = await dbPool.query<{+ contract_version: number+ status: string+ lease_expires_at: Date | null+ }>(+ `SELECT contract_version, status, lease_expires_at+ FROM plugin_workload_sdk_invocations+ WHERE id = $1`,+ [ambiguousInvocationId]+ )+ expect(ambiguousState.rows[0]).toMatchObject({+ contract_version: 2,+ status: 'in_progress',+ lease_expires_at: null,+ })+ await dbPool.query('DELETE FROM plugin_workload_sdk_provider_attempts WHERE id = $1', [+ ambiguousProviderAttemptId,+ ])+ await dbPool.query(+ 'DELETE FROM plugin_workload_sdk_invocation_attempts WHERE invocation_id = $1',+ [ambiguousInvocationId]+ )+ await dbPool.query('DELETE FROM plugin_workload_sdk_invocations WHERE id = $1', [+ ambiguousInvocationId,+ ])++ const legacyClient = await dbPool.connect()+ const legacyInvocationId = randomUUID()+ try {+ await legacyClient.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', 'legacy-v2-no-lease', 'integration-test',+ 'promptBridge', '{}', $2, $3, 'in_progress', 'authorized', 2, 1, NULL)`,+ [legacyInvocationId, randomBytes(32).toString('hex'), randomBytes(32).toString('hex')]+ )+ await legacyClient.query(+ `INSERT INTO plugin_workload_sdk_invocation_attempts+ (invocation_id, recipe_namespace, recipe_name, attempt_generation,+ method, target_refs, status, lease_expires_at)+ VALUES ($1, 'sandbox-recipes', 'legacy-v2-no-lease', 1,+ 'promptBridge', '["primary-openai"]'::jsonb, 'in_progress', NULL)`,+ [legacyInvocationId]+ )+ } finally {+ legacyClient.release()+ }++ await initDb({ connect: () => dbPool.connect() })++ const repaired = await dbPool.query<{+ contract_version: number+ status: string+ authorization_decision: string+ }>(+ `SELECT contract_version, status, authorization_decision+ FROM plugin_workload_sdk_invocations+ WHERE id = $1`,+ [legacyInvocationId]+ )+ expect(repaired.rows[0]).toEqual({+ contract_version: 1,+ status: 'failed',+ authorization_decision: 'migration_interrupted',+ })++ const accepted = await dbPool.query<{ accepted: boolean }>(+ `SELECT governed_trace_safe_agent_run_metadata('token_usage', $1::jsonb) AS accepted`,+ [JSON.stringify(validPayload())]+ )+ const rejectedTopLevel = await dbPool.query<{ accepted: boolean }>(+ `SELECT governed_trace_safe_agent_run_metadata('token_usage', $1::jsonb) AS accepted`,+ [JSON.stringify({ ...validPayload(), unexpected: true })]+ )+ const rejectedNested = 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, unexpected: true },+ }),+ ]+ )+ const rejectedUuid = 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: 'a'.repeat(36),+ },+ }),+ ]+ )+ const rejectedCount = 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_count: 5 },+ }),+ ]+ )+ 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)++ const repairedSkippedId = randomUUID()+ await dbPool.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', 'repaired-skip', 1, 1,+ 'primary-openai', 'openai', 'gpt-4o-mini', 'openai-api-key', 'skipped')`,+ [repairedSkippedId, randomUUID()]+ )++ const exactClient = await dbPool.connect()+ let exactInput: PromptBridgeFinalizationInput+ try {+ await begin(exactClient)+ exactInput = await seedAttempt(exactClient, { contractVersion: 2, lease: true })+ const result = await finalizePromptBridgeInTransaction(exactInput, exactClient)+ await commit(exactClient)+ expect(result).toMatchObject({+ status: 'complete',+ outcome: 'exact',+ usageAccepted: true,+ idempotent: false,+ })+ } finally {+ exactClient.release()+ }++ const counts = await dbPool.query(+ `SELECT+ (SELECT COUNT(*) FROM usage_events WHERE request_id = $1::uuid)::int AS usage_count,+ (SELECT COUNT(*) FROM agent_run_events WHERE source_event_id = $1::text)::int AS trace_count,+ (SELECT COUNT(*) FROM governed_event_stream stream+ JOIN agent_run_events event ON event.event_id = stream.event_id+ WHERE event.source_event_id = $1::text)::int AS stream_count,+ (SELECT COUNT(*) FROM plugin_workload_sdk_spend_outcomes+ WHERE provider_attempt_id = $1::uuid)::int AS spend_count`,+ [exactInput!.providerAttemptId]+ )+ expect(counts.rows[0]).toEqual({+ usage_count: 1,+ trace_count: 1,+ stream_count: 1,+ spend_count: 1,+ })++ const contractState = await dbPool.query<{+ default_value: string | null+ lease_check: string+ attempt_check: string+ }>(+ `SELECT+ (SELECT column_default+ FROM information_schema.columns+ WHERE table_schema = 'public'+ AND table_name = 'plugin_workload_sdk_invocations'+ AND column_name = 'contract_version') AS default_value,+ (SELECT pg_get_constraintdef(oid)+ FROM pg_constraint+ WHERE 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`+ )+ 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'")++ const functionState = await dbPool.query<{+ validator_config: string[] | null+ metadata_config: string[] | null+ control_validator: boolean+ trace_validator: boolean+ workflow_validator: boolean+ control_metadata: boolean+ trace_metadata: boolean+ workflow_metadata: boolean+ }>(+ `SELECT+ validator.proconfig AS validator_config,+ metadata.proconfig AS metadata_config,+ has_function_privilege('control_api_runtime', 'public.governed_trace_safe_agent_run_metadata(text,jsonb)', 'EXECUTE') AS control_validator,+ 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('control_api_runtime', 'public.governed_trace_safe_metadata(jsonb)', 'EXECUTE') AS control_metadata,+ has_function_privilege('trace_maintenance_runtime', 'public.governed_trace_safe_metadata(jsonb)', 'EXECUTE') AS trace_metadata,+ 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(functionState.rows[0]?.validator_config).toContain('search_path=pg_catalog, public')+ expect(functionState.rows[0]?.metadata_config).toContain('search_path=pg_catalog, public')+ expect(functionState.rows[0]).toMatchObject({+ control_validator: true,+ trace_validator: false,+ workflow_validator: false,+ control_metadata: true,+ trace_metadata: true,+ workflow_metadata: false,+ })++ const beforeSecondRun = await dbPool.query<{ count: string }>(+ `SELECT COUNT(*)::text AS count FROM schema_migrations+ WHERE version = '0090_plugin_workload_sdk_runtime_contract_reconciliation'`+ )+ await initDb({ connect: () => dbPool.connect() })+ const afterSecondRun = await dbPool.query<{ count: string }>(+ `SELECT COUNT(*)::text AS count FROM schema_migrations+ WHERE version = '0090_plugin_workload_sdk_runtime_contract_reconciliation'`+ )+ expect(beforeSecondRun.rows[0]?.count).toBe('1')+ expect(afterSecondRun.rows[0]?.count).toBe('1')+ })+})diff --git a/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts b/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.tsnew file mode 100644index 000000000..921a32bed--- /dev/null+++ b/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts@@ -0,0 +1,86 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++const clientQuery = vi.fn()+const clientRelease = vi.fn()+const mockConnect = vi.fn()+const mockPoolCtor = vi.fn(function MockPool() {+ return { connect: mockConnect, query: vi.fn() }+})++vi.mock('pg', () => ({ Pool: mockPoolCtor }))++describe('Plugin Workload SDK runtime-contract reconciliation migration', () => {+ beforeEach(() => {+ vi.resetModules()+ vi.clearAllMocks()+ mockConnect.mockResolvedValue({ query: clientQuery, release: clientRelease })+ clientQuery.mockResolvedValue({ rows: [], rowCount: 0 })+ })++ it('applies an additive migration after 0089 for already-migrated databases', async () => {+ const { CONTROL_API_MIGRATIONS, initDb } = await import('../src/db.js')+ const migration = CONTROL_API_MIGRATIONS.find(+ candidate => candidate.version === '0090_plugin_workload_sdk_runtime_contract_reconciliation'+ )+ expect(migration).toBeDefined()+ expect(CONTROL_API_MIGRATIONS.at(-2)?.version).toBe(+ '0089_plugin_workload_sdk_credential_ticket_runtime_access'+ )++ clientQuery.mockImplementation(async (sql: string) => {+ if (sql.includes('SELECT version FROM schema_migrations')) {+ const appliedVersions = CONTROL_API_MIGRATIONS.filter(+ candidate => candidate.version !== migration?.version+ ).map(candidate => ({ version: candidate.version }))+ return { rows: appliedVersions, rowCount: appliedVersions.length }+ }+ return { rows: [], rowCount: 0 }+ })++ await initDb()++ const migrationSql = clientQuery.mock.calls+ .map(([sql]) => String(sql))+ .find(sql =>+ sql.includes('CREATE OR REPLACE FUNCTION governed_trace_safe_agent_run_metadata')+ )+ expect(migrationSql).toBeDefined()+ expect(migrationSql).toContain("'cache_tokens_reported'")+ expect(migrationSql).toContain("'prompt_bridge'")+ expect(migrationSql).toContain("'plugin_workload_sdk'")+ expect(migrationSql).toContain("'provider_attempt_id'")+ expect(migrationSql).toContain("jsonb_typeof(value->'prompt_bridge') = 'object'")+ expect(migrationSql).toContain('SET search_path = pg_catalog, public')+ expect(migrationSql).toContain('ALTER COLUMN contract_version SET DEFAULT 1')+ expect(migrationSql).toContain('plugin_workload_sdk_invocations_v2_lease_check')+ expect(migrationSql).toContain('plugin_workload_sdk_provider_attempts_status_check')+ expect(migrationSql).toContain("'skipped'")+ expect(migrationSql).toContain('cannot reconcile % v2 invocations without leases')++ const recordCalls = clientQuery.mock.calls.filter(+ ([, params]) => Array.isArray(params) && params[0] === migration?.version+ )+ expect(recordCalls).toHaveLength(1)+ })++ it('keeps the migration fail-closed for unknown top-level and nested metadata', async () => {+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')+ const migration = CONTROL_API_MIGRATIONS.find(+ candidate => candidate.version === '0090_plugin_workload_sdk_runtime_contract_reconciliation'+ )+ expect(migration).toBeDefined()++ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })+ await migration!.apply({ query })+ const migrationSql = String(query.mock.calls[0]?.[0])++ 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("value->'prompt_bridge' ?& ARRAY[")+ expect(migrationSql).toContain(+ 'FROM PUBLIC, control_api_runtime, trace_maintenance_runtime, workflow_recipes_runtime'+ )+ expect(migrationSql).toContain("FROM jsonb_object_keys(value->'prompt_bridge') AS key_name")+ })+})