Skip to content

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

TypeScript

fix(control-api): address 0090 deploy-safety and test-integrity review

Alfredo Lopez099485da8d51
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index 37268af4b..9bc2a3592 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -2295,11 +2295,17 @@ async function applyGfsPermissionStoreSchema(db: DbClient): Promise<void> {
*/
async function reconcilePluginWorkloadSdkRuntimeContracts(db: DbClient): Promise<void> {
await db.query(`
- -- Bound the wait for the table locks so a long-running reader can never turn
- -- this migration into an indefinite lock queue (a queued ACCESS EXCLUSIVE
- -- request blocks every new reader behind it). Fail loud and let the migration
- -- Job be retried instead of silently stalling the deploy.
- SET LOCAL lock_timeout = '5s';
+ -- Bound the wait for the table locks so a stuck concurrent writer cannot make
+ -- this migration hang indefinitely. EXCLUSIVE conflicts with the ROW EXCLUSIVE
+ -- that ordinary INSERT/UPDATE/DELETE take (e.g. the trace-retention prune's
+ -- DELETE FROM agent_run_events), so if such a writer holds its lock past this
+ -- timeout the LOCK/DDL below fails loudly (exit 1) rather than stalling. 60s
+ -- sits well above the bounded prune wake-transaction and well below the deploy's
+ -- 300s kubectl-wait budget, so a transient writer is tolerated but a genuinely
+ -- stuck one surfaces fast. NOTE: the migration Job runs with backoffLimit 0, so a
+ -- timeout aborts the deploy and the deploy must be re-run; raising the Job's
+ -- backoffLimit (deploy script, out of this PR's scope) would let it self-retry.
+ SET LOCAL lock_timeout = '60s';
-- Runtime writers do not take the initDb advisory lock. Hold the table locks
-- in the same logical order as finalization (invocation -> receipt ->
@@ -2450,20 +2456,21 @@ async function reconcilePluginWorkloadSdkRuntimeContracts(db: DbClient): Promise
END
$$;
- -- History is clean: reinstall the named constraint. ADD ... NOT VALID is a
- -- metadata-only change (brief ACCESS EXCLUSIVE, no scan); VALIDATE re-checks
- -- the rows under SHARE UPDATE EXCLUSIVE. Both are cheap now that the scan
- -- above already proved every row passes.
+ -- History is clean: the fail-closed scan above ran under the EXCLUSIVE table
+ -- lock (plain readers proceed) and already proved every row passes, emitting a
+ -- triage sample on failure. Reinstall the named constraint with a single
+ -- validating ADD CONSTRAINT: it takes ACCESS EXCLUSIVE and scans once. A
+ -- NOT VALID + separate VALIDATE would buy nothing here -- applyPendingMigrations
+ -- holds this transaction open until COMMIT, so the ADD's ACCESS EXCLUSIVE (and
+ -- the reader blocking it implies) is held through any later VALIDATE anyway; the
+ -- split would just scan the table a second time under the same lock profile.
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;
- ALTER TABLE agent_run_events
- VALIDATE CONSTRAINT agent_run_events_check;
+ CHECK (governed_trace_safe_agent_run_metadata(event_type, payload_metadata) IS TRUE);
ALTER TABLE plugin_workload_sdk_invocations
ALTER COLUMN contract_version SET DEFAULT 1;
@@ -2538,9 +2545,14 @@ async function reconcilePluginWorkloadSdkRuntimeContracts(db: DbClient): Promise
);
GET DIAGNOSTICS fenced_count = ROW_COUNT;
+ -- Belt-and-braces: under the EXCLUSIVE lock held above nothing can change the
+ -- captured set between the snapshot and this UPDATE, and the ambiguity check
+ -- already aborted on any physical attempt, so fenced_count always equals
+ -- expected_count. This guard is defence-in-depth and is not expected to fire.
IF fenced_count <> expected_count THEN
RAISE EXCEPTION
- 'plugin workload SDK invocation state changed during reconciliation; retry safely';
+ 'plugin workload SDK invocation state changed during reconciliation (fenced % of % captured); aborting the migration',
+ fenced_count, expected_count;
END IF;
END
$$;
@@ -2578,6 +2590,13 @@ async function reconcilePluginWorkloadSdkRuntimeContracts(db: DbClient): Promise
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'));
+
+ -- Reset the statement-scoped lock timeout set at the top of this migration.
+ -- applyPendingMigrations runs every pending migration in one transaction, so
+ -- without this a later 0091+ applied in the same batch would silently inherit
+ -- the 60s timeout. 0090 is currently last (so this is latent today), but keep
+ -- the transaction state hygienic for whatever ships next.
+ SET LOCAL lock_timeout = '0';
`)
}
diff --git a/control-api/test/db.pluginWorkloadSdkRuntimeContract.realPostgres.integration.test.ts b/control-api/test/db.pluginWorkloadSdkRuntimeContract.realPostgres.integration.test.ts
index 554865ec3..0ee107196 100644
--- a/control-api/test/db.pluginWorkloadSdkRuntimeContract.realPostgres.integration.test.ts
+++ b/control-api/test/db.pluginWorkloadSdkRuntimeContract.realPostgres.integration.test.ts
@@ -136,18 +136,80 @@ describeRealPostgres('Plugin Workload SDK runtime-contract upgrade on real Postg
}
async function restoreHistoricalRuntimeState(): Promise<void> {
+ // The validator body below is the VERBATIM
+ // governed_trace_safe_agent_run_metadata definition shipped by migration
+ // 0065_governed_session_replay_and_prompt_history (control-api/src/db.ts).
+ // It is intentionally permissive where 0090 hardens: prompt_bridge is
+ // allowed, invocation_id/provider_attempt_id only need to match the lax
+ // '^[0-9a-f-]{36}$' shape, provider_attempt_index/attempt_count are
+ // uncapped, target_ref has no length cap, and there is no allowlist for
+ // nested prompt_bridge keys. Installing the real historical validator (not
+ // a strawman) lets the test seed rows 0065 accepted and 0090 must reject.
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')
- );
+ 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 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-]{36}$'
+ AND (value->'prompt_bridge'->>'provider_attempt_id') ~ '^[0-9a-f-]{36}$'
+ AND (value->'prompt_bridge'->>'attempt_generation') ~ '^[1-9][0-9]*$'
+ AND (value->'prompt_bridge'->>'provider_attempt_index') ~ '^[1-9][0-9]*$'
+ AND jsonb_typeof(value->'prompt_bridge'->'target_ref') = 'string'
+ AND jsonb_typeof(value->'prompt_bridge'->'fallback_used') = 'boolean'
+ AND jsonb_typeof(value->'prompt_bridge'->'attempt_count') = 'number'
+ )
+ )
+ END;
$$;
ALTER FUNCTION governed_trace_safe_metadata(JSONB) RESET search_path;
ALTER FUNCTION governed_trace_safe_agent_run_metadata(TEXT, JSONB) RESET search_path;
@@ -281,57 +343,116 @@ describeRealPostgres('Plugin Workload SDK runtime-contract upgrade on real Postg
workflow_metadata: true,
})
- const historicalInvalidEventId = await seedTraceEvent(
- {
- source_kind: 'unknown',
- input_tokens: 1,
- output_tokens: 1,
- },
- 'historical'
+ // Fidelity proof that the installed fixture is the REAL (permissive) 0065
+ // validator and not a strawman: 0065 accepts the modern prompt_bridge
+ // payload, so finalization succeeds under the historical contract too.
+ const historicalAccepts = await dbPool.query<{ accepted: boolean }>(
+ `SELECT governed_trace_safe_agent_run_metadata('token_usage', $1::jsonb) AS accepted`,
+ [JSON.stringify(validPayload())]
)
+ expect(historicalAccepts.rows[0]?.accepted).toBe(true)
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/
+ const historicalInput = await seedAttempt(historicalClient, {
+ contractVersion: 2,
+ lease: true,
+ })
+ const historicalResult = await finalizePromptBridgeInTransaction(
+ historicalInput,
+ historicalClient
)
+ expect(historicalResult).toMatchObject({ status: 'complete', usageAccepted: true })
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)
+ // One seed per rule that 0090 hardens over 0065. Every payload MUST be
+ // insertable under the historical CHECK (proving 0065 accepted it) and MUST
+ // make the 0090 reconciliation abort fail-closed, leaving schema_migrations
+ // without 0090 and the row intact.
+ const hardenedRuleSeeds: Array<{ label: string; payload: Record<string, unknown> }> = [
+ {
+ // Passes the lax '^[0-9a-f-]{36}$' shape, fails the canonical
+ // 8-4-4-4-12 UUID regex enforced by 0090.
+ label: 'non-canonical 36-char invocation_id',
+ payload: {
+ ...validPayload(),
+ prompt_bridge: {
+ ...validPayload().prompt_bridge,
+ invocation_id: 'abcdefabcdefabcdefabcdefabcdefabcdef',
+ },
+ },
+ },
+ {
+ // 0065 allowed any positive integer; 0090 caps the index at 4.
+ label: 'provider_attempt_index above the 1-4 cap',
+ payload: {
+ ...validPayload(),
+ prompt_bridge: { ...validPayload().prompt_bridge, provider_attempt_index: 5 },
+ },
+ },
+ {
+ // 0065 only required a string; 0090 caps target_ref at 256 chars.
+ label: 'target_ref longer than 256 chars',
+ payload: {
+ ...validPayload(),
+ prompt_bridge: { ...validPayload().prompt_bridge, target_ref: 'x'.repeat(257) },
+ },
+ },
+ {
+ // 0065 had no nested-key allowlist; 0090 rejects unknown keys.
+ label: 'unexpected nested prompt_bridge key',
+ payload: {
+ ...validPayload(),
+ prompt_bridge: { ...validPayload().prompt_bridge, unexpected_key: true },
+ },
+ },
+ ]
+
+ for (const seed of hardenedRuleSeeds) {
+ // Throws (failing the test loudly) if the historical 0065 CHECK rejects
+ // the payload -- i.e. if the fixture ever regresses into a strawman.
+ const seededEventId = await seedTraceEvent(seed.payload, 'historical')
+
+ await expect(
+ initDb({ connect: () => dbPool.connect() }),
+ `0090 must abort on historical row: ${seed.label}`
+ ).rejects.toThrow(
+ /cannot reconcile .* historical agent_run_events rows with invalid payload metadata/
+ )
- 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 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`,
+ [seededEventId]
+ )
+ expect(failedMigrationState.rows[0], seed.label).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', [
+ seededEventId,
+ ])
+ await historicalCleanupClient.query(
+ 'DELETE FROM governed_event_stream WHERE event_id = $1',
+ [seededEventId]
+ )
+ await commit(historicalCleanupClient)
+ } finally {
+ historicalCleanupClient.release()
+ }
}
const skippedAttempt = {
diff --git a/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts b/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts
index a80e7677e..43c345803 100644
--- a/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts
+++ b/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts
@@ -57,6 +57,14 @@ describe('Plugin Workload SDK runtime-contract reconciliation migration', () =>
expect(migrationSql).toContain("'skipped'")
expect(migrationSql).toContain('cannot reconcile % v2 invocations without leases')
expect(migrationSql).toContain('LOCK TABLE')
+ // Deploy-critical lock knobs: EXCLUSIVE (not SHARE ROW EXCLUSIVE / ACCESS
+ // EXCLUSIVE) keeps plain readers alive during the scan, and the 60s
+ // lock_timeout bounds the wait below the deploy's kubectl budget. A silent
+ // regression of either knob turns the migration into a deploy outage.
+ expect(migrationSql).toContain('IN EXCLUSIVE MODE')
+ expect(migrationSql).toContain("SET LOCAL lock_timeout = '60s'")
+ // The hardened cap on prompt_bridge provider_attempt_index / attempt_count.
+ expect(migrationSql).toContain("~ '^[1-4]$'")
expect(migrationSql).toContain('agent_run_events_check')
expect(migrationSql).toContain('IS DISTINCT FROM TRUE')
expect(migrationSql).toContain('IS TRUE)')