Skip to content

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

TypeScript

fix: close stepless prompt bridge accounting contract

Alfredo Lopez57f48c871da0
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index cf93d03be..f9cf646d3 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.413",
+ "version": "0.1.414",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.413",
+ "version": "0.1.414",
"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.json
index b03f0c415..0e21ddc3c 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.413",
+ "version": "0.1.414",
"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 af743711e..b30b13a88 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -15,9 +15,11 @@ import {
addPluginWorkloadSdkProviderColumn,
addPluginWorkloadSdkRevocationEpoch,
addPluginWorkloadSdkRuntimeAccess,
+ addPluginWorkloadSdkSpendOutcomeLedger,
addPluginWorkloadSdkUsageSourceKind,
applyPluginWorkloadSdkSchema,
dropPluginWorkloadSdkSuperAdminApprovedColumn,
+ relaxPluginWorkloadSdkSpendOutcomeHostRef,
} from './services/pluginWorkloadSdkSchema.js'
import { applyRegistryConnectionSchema } from './services/registryConnectionSchema.js'
@@ -5114,6 +5116,14 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [
version: '0083_plugin_workload_sdk_runtime_access',
apply: addPluginWorkloadSdkRuntimeAccess,
},
+ {
+ version: '0084_plugin_workload_sdk_spend_outcome_ledger',
+ apply: addPluginWorkloadSdkSpendOutcomeLedger,
+ },
+ {
+ version: '0085_plugin_workload_sdk_spend_outcome_host_ref_nullable',
+ apply: relaxPluginWorkloadSdkSpendOutcomeHostRef,
+ },
]
async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {
diff --git a/control-api/src/routes/internal/usageEvents.ts b/control-api/src/routes/internal/usageEvents.ts
index 015b87c14..8cb775d23 100644
--- a/control-api/src/routes/internal/usageEvents.ts
+++ b/control-api/src/routes/internal/usageEvents.ts
@@ -164,109 +164,6 @@ function checkClaimBinding(
return null
}
-async function checkSdkOnlyUsageBinding(
- events: unknown[],
- claims: McpHostAccessClaims,
- db: DbClient
-): Promise<BindingViolation | null> {
- const sdkEvents = events.flatMap((event, index) => {
- if (!event || typeof event !== 'object') return []
- const record = event as Record<string, unknown>
- const sdkSource =
- (record.source_kind === 'unknown' || record.source_kind === 'plugin_workload_sdk') &&
- record.channel_type === 'plugin_workload_sdk'
- const workflowSdkSource =
- record.source_kind === 'workflow' && record.channel_type === 'plugin_workload_sdk'
- return sdkSource || workflowSdkSource ? [{ index, record }] : []
- })
- if (sdkEvents.length === 0) return null
-
- const invocationIds = new Set<string>()
- const providerAttemptIds = new Set<string>()
- for (const { index, record } of sdkEvents) {
- const metadata = record.prompt_bridge_metadata
- if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) {
- return { index, reason: 'recipe_token_invalid_sdk_usage_binding' }
- }
- const invocationId = (metadata as { invocation_id?: unknown }).invocation_id
- const generation = (metadata as { attempt_generation?: unknown }).attempt_generation
- const providerAttemptId = (metadata as { provider_attempt_id?: unknown }).provider_attempt_id
- const providerAttemptIndex = (metadata as { provider_attempt_index?: unknown })
- .provider_attempt_index
- if (
- typeof invocationId !== 'string' ||
- !Number.isInteger(generation) ||
- Number(generation) < 1 ||
- typeof providerAttemptId !== 'string' ||
- !Number.isInteger(providerAttemptIndex) ||
- Number(providerAttemptIndex) < 1
- ) {
- return { index, reason: 'recipe_token_invalid_sdk_usage_binding' }
- }
- invocationIds.add(invocationId)
- providerAttemptIds.add(providerAttemptId)
- }
-
- const [receiptResult, providerAttemptResult] = await Promise.all([
- db.query(
- `SELECT invocation_id::text, attempt_generation, method, target_refs, recipe_namespace, recipe_name
- FROM plugin_workload_sdk_invocation_attempts
- WHERE invocation_id = ANY($1::uuid[])`,
- [[...invocationIds]]
- ),
- db.query(
- `SELECT id::text, invocation_id::text, attempt_generation, attempt_index,
- target_ref, provider, model, credential_slot, status,
- recipe_namespace, recipe_name
- FROM plugin_workload_sdk_provider_attempts
- WHERE id = ANY($1::uuid[])`,
- [[...providerAttemptIds]]
- ),
- ])
- const receipts = new Map(
- (receiptResult.rows as Array<Record<string, unknown>>).map(row => [
- `${String(row.invocation_id)}:${Number(row.attempt_generation)}`,
- row,
- ])
- )
- const providerAttempts = new Map(
- (providerAttemptResult.rows as Array<Record<string, unknown>>).map(row => [String(row.id), row])
- )
-
- for (const { index, record } of sdkEvents) {
- const metadata = record.prompt_bridge_metadata as Record<string, unknown>
- const invocationId = String(metadata.invocation_id)
- const generation = Number(metadata.attempt_generation)
- const providerAttemptId = String(metadata.provider_attempt_id)
- const providerAttemptIndex = Number(metadata.provider_attempt_index)
- const targetRef = String(metadata.target_ref ?? '')
- const receipt = receipts.get(`${invocationId}:${generation}`)
- const providerAttempt = providerAttempts.get(providerAttemptId)
- const targetRefs = Array.isArray(receipt?.target_refs) ? receipt.target_refs.map(String) : []
- if (
- !receipt ||
- receipt.method !== 'promptBridge' ||
- receipt.recipe_namespace !== claims.recipeNamespace ||
- receipt.recipe_name !== claims.recipeName ||
- !targetRefs.includes(targetRef) ||
- !providerAttempt ||
- providerAttempt.invocation_id !== invocationId ||
- Number(providerAttempt.attempt_generation) !== generation ||
- Number(providerAttempt.attempt_index) !== providerAttemptIndex ||
- providerAttempt.recipe_namespace !== claims.recipeNamespace ||
- providerAttempt.recipe_name !== claims.recipeName ||
- providerAttempt.target_ref !== targetRef ||
- providerAttempt.provider !== String(record.provider ?? '') ||
- providerAttempt.model !== String(record.model ?? '') ||
- providerAttempt.credential_slot !== String(metadata.credential_slot ?? '') ||
- providerAttempt.status !== 'complete'
- ) {
- return { index, reason: 'recipe_token_invalid_sdk_usage_binding' }
- }
- }
- return null
-}
-
function collectWorkflowUsageCandidates(events: unknown[]): WorkflowUsageCandidate[] {
const candidates: WorkflowUsageCandidate[] = []
for (let i = 0; i < events.length; i++) {
@@ -375,12 +272,14 @@ export function createInternalUsageEventsRouter(): Router {
return res.status(403).json({ error: 'claim_binding_mismatch', ...violation })
}
const transactionResult = await withTraceIngestTransaction(async db => {
- const sdkBinding = await checkSdkOnlyUsageBinding(events, req.mcpHostJwt!, db)
- if (sdkBinding) return { violation: sdkBinding }
const workflowBinding = await checkWorkflowRunBinding(events, req.mcpHostJwt!, db)
if (workflowBinding.violation) return { violation: workflowBinding.violation }
- const ingest = await ingestUsageEventsInTransaction(events, db)
+ const ingest = await ingestUsageEventsInTransaction(events, db, {
+ recipeNamespace: req.mcpHostJwt!.recipeNamespace,
+ recipeName: req.mcpHostJwt!.recipeName,
+ })
+ if (ingest.bindingViolation) return { violation: ingest.bindingViolation }
await projectAcceptedUsageEvents(db, ingest.acceptedEvents, workflowBinding.bindings, {
recipeNamespace: req.mcpHostJwt!.recipeNamespace,
recipeName: req.mcpHostJwt!.recipeName,
diff --git a/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts b/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
index 931757246..8e4020f8c 100644
--- a/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
+++ b/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
@@ -37,6 +37,11 @@ import {
redeemPluginWorkloadSdkCredentialTicketJti,
resolveRecipientProfiles,
} from '../../services/pluginWorkloadSdkDb.js'
+import {
+ PromptBridgeFinalizationError,
+ type PromptBridgeFinalizationInput,
+ finalizePromptBridge,
+} from '../../services/pluginWorkloadSdkFinalization.js'
import { markInvocationStatus } from '../../services/pluginWorkloadSdkInvocationAuditor.js'
import type { McpHostAccessClaims } from '../../utils/auth/mcpHostJwtToken.js'
import { isPlainObject } from '../../utils/isPlainObject.js'
@@ -150,6 +155,102 @@ function validateCallerRef(value: unknown, res: Response): string | null {
return value.trim()
}
+function parsePromptBridgeFinalizationBody(
+ body: Record<string, unknown>,
+ claims: McpHostAccessClaims,
+ res: Response
+): PromptBridgeFinalizationInput | null {
+ const invocationId = typeof body.invocationId === 'string' ? body.invocationId.trim() : ''
+ const providerAttemptId =
+ typeof body.providerAttemptId === 'string' ? body.providerAttemptId.trim() : ''
+ const attemptGeneration = Number.isInteger(body.attemptGeneration)
+ ? Number(body.attemptGeneration)
+ : 0
+ const providerAttemptIndex = Number.isInteger(body.providerAttemptIndex)
+ ? Number(body.providerAttemptIndex)
+ : 0
+ const status = body.status
+ const reason = typeof body.reason === 'string' ? body.reason.trim() : ''
+ const target = isPlainObject(body.target) ? body.target : null
+ const targetRef = typeof target?.targetRef === 'string' ? target.targetRef.trim() : ''
+ const provider = typeof target?.provider === 'string' ? target.provider.trim() : ''
+ const model = typeof target?.model === 'string' ? target.model.trim() : ''
+ const credentialSlot =
+ typeof target?.credentialSlot === 'string' ? target.credentialSlot.trim() : ''
+
+ if (
+ !invocationId ||
+ !providerAttemptId ||
+ attemptGeneration < 1 ||
+ providerAttemptIndex < 1 ||
+ providerAttemptIndex > 4 ||
+ !['complete', 'provider_unavailable'].includes(String(status)) ||
+ !reason ||
+ reason.length > 128 ||
+ !targetRef ||
+ !provider ||
+ !model ||
+ !credentialSlot
+ ) {
+ res.status(400).json({
+ error:
+ 'invocationId, attemptGeneration, providerAttemptId, providerAttemptIndex, status, reason and target are required',
+ })
+ return null
+ }
+
+ const rawUsage = body.usage
+ let usage: PromptBridgeFinalizationInput['usage']
+ if (rawUsage !== undefined) {
+ if (!isPlainObject(rawUsage)) {
+ res.status(400).json({ error: 'usage must be an object' })
+ return null
+ }
+ const llmSecretName =
+ typeof rawUsage.llmSecretName === 'string' ? rawUsage.llmSecretName.trim() : ''
+ const callerRef = typeof rawUsage.callerRef === 'string' ? rawUsage.callerRef.trim() : ''
+ const attemptCount = Number.isInteger(rawUsage.attemptCount) ? Number(rawUsage.attemptCount) : 0
+ const inputTokens = Number.isInteger(rawUsage.inputTokens) ? Number(rawUsage.inputTokens) : -1
+ const outputTokens = Number.isInteger(rawUsage.outputTokens)
+ ? Number(rawUsage.outputTokens)
+ : -1
+ if (
+ !llmSecretName ||
+ !callerRef ||
+ typeof rawUsage.fallbackUsed !== 'boolean' ||
+ attemptCount < 1 ||
+ attemptCount > 4 ||
+ inputTokens < 0 ||
+ outputTokens < 0
+ ) {
+ res.status(400).json({ error: 'usage fields are invalid' })
+ return null
+ }
+ usage = {
+ llmSecretName,
+ callerRef,
+ fallbackUsed: rawUsage.fallbackUsed,
+ attemptCount,
+ inputTokens,
+ outputTokens,
+ }
+ }
+
+ return {
+ invocationId,
+ recipeNamespace: claims.recipeNamespace,
+ recipeName: claims.recipeName,
+ hostRef: claims.hostRefs[0] ?? '',
+ attemptGeneration,
+ providerAttemptId,
+ providerAttemptIndex,
+ status: status as PromptBridgeFinalizationInput['status'],
+ target: { targetRef, provider, model, credentialSlot },
+ reason,
+ ...(usage ? { usage } : {}),
+ }
+}
+
// ─── promptBridge input validation (plan §2.7) ───────────────────────────
interface ParsedPromptBridgeBody {
@@ -906,6 +1007,49 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
})
)
+ // Finalization is the SDK-only promptBridge accounting boundary. It binds
+ // the provider receipt, logical invocation, and exact/unknown spend outcome
+ // in one idempotent transaction; callers must not separately report status
+ // and usage for this lane.
+ router.post(
+ '/mcp-host/plugin-workload-sdk/invocations/:id/finalize',
+ asyncHandler(async (req, res) => {
+ const claims = req.mcpHostJwt!
+ const body = isPlainObject(req.body) ? req.body : {}
+ if (!checkRecipeBinding(body, claims, res)) return
+ const parsed = parsePromptBridgeFinalizationBody(body, claims, res)
+ if (!parsed) return
+ if (parsed.invocationId !== req.params.id) {
+ res.status(400).json({ error: 'invocation id does not match path' })
+ return
+ }
+ try {
+ const result = await finalizePromptBridge(parsed)
+ res.status(result.idempotent ? 200 : 201).json(result)
+ } catch (error) {
+ if (error instanceof PromptBridgeFinalizationError) {
+ const errorCode =
+ error.code === 'conflict'
+ ? 'idempotency_conflict'
+ : error.code === 'binding_mismatch'
+ ? 'provider_policy_denied'
+ : error.code === 'stale_attempt'
+ ? 'provider_unavailable'
+ : error.code === 'not_found'
+ ? 'invalid_request'
+ : error.code
+ res.status(error.httpStatus).json({
+ error: errorCode,
+ message: error.message,
+ retryable: false,
+ })
+ return
+ }
+ throw error
+ }
+ })
+ )
+
router.post(
'/mcp-host/plugin-workload-sdk/provider-attempts/:id/status',
asyncHandler(async (req, res) => {
diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.ts
index 3d1192e45..6e1aa4bd7 100644
--- a/control-api/src/services/pluginWorkloadSdkDb.ts
+++ b/control-api/src/services/pluginWorkloadSdkDb.ts
@@ -1238,6 +1238,9 @@ export async function markPluginWorkloadSdkProviderAttemptStatus(input: {
attemptGeneration: number
status: Exclude<PluginWorkloadSdkProviderAttemptStatus, 'reserved' | 'in_progress'>
}): Promise<boolean> {
+ // Terminal reports are idempotent: a committed response whose HTTP reply
+ // was lost must be safe to repeat. A different terminal outcome still
+ // returns false, so a late failure can never downgrade a completed attempt.
const result = await pool.query(
`UPDATE plugin_workload_sdk_provider_attempts
SET status = $6,
@@ -1248,14 +1251,19 @@ export async function markPluginWorkloadSdkProviderAttemptStatus(input: {
AND recipe_namespace = $3
AND recipe_name = $4
AND attempt_generation = $5
- AND status IN ('reserved', 'in_progress')
- AND EXISTS (
- SELECT 1
- FROM plugin_workload_sdk_invocations inv
- WHERE inv.id = $2
- AND inv.status = 'in_progress'
- AND inv.attempt_generation = $5
- AND inv.lease_expires_at > now()
+ AND (
+ status = $6
+ OR (
+ status IN ('reserved', 'in_progress')
+ AND EXISTS (
+ SELECT 1
+ FROM plugin_workload_sdk_invocations inv
+ WHERE inv.id = $2
+ AND inv.status = 'in_progress'
+ AND inv.attempt_generation = $5
+ AND inv.lease_expires_at > now()
+ )
+ )
)`,
[
input.id,
@@ -1640,16 +1648,28 @@ export async function updateInvocationStatus(
expectedCurrentStatus?: PluginWorkloadSdkInvocationStatus
} = {}
): Promise<boolean> {
- const values: unknown[] = [id, status, opts.completed ?? false, opts.leaseSeconds ?? 0]
+ // Every in-progress invocation must carry a lease. Without this guard an
+ // older rolling-update writer can create a v2 row that the stale sweep can
+ // never identify, leaving the idempotency key permanently wedged.
+ // The terminal branch below also makes identical completion reports
+ // idempotent while preserving the expected-status CAS for new transitions.
+ const leaseSeconds = opts.leaseSeconds
+ if (
+ status === 'in_progress' &&
+ (typeof leaseSeconds !== 'number' || !Number.isInteger(leaseSeconds) || leaseSeconds <= 0)
+ ) {
+ return false
+ }
+ const values: unknown[] = [id, status, opts.completed ?? false, leaseSeconds ?? 0]
let bindingClause = ''
if (opts.recipeNamespace !== undefined && opts.recipeName !== undefined) {
values.push(opts.recipeNamespace, opts.recipeName)
bindingClause = ` AND recipe_namespace = $${values.length - 1} AND recipe_name = $${values.length}`
}
- let statusGuardClause = ''
+ let expectedStatusPlaceholder = ''
if (opts.expectedCurrentStatus !== undefined) {
values.push(opts.expectedCurrentStatus)
- statusGuardClause = ` AND status = $${values.length}`
+ expectedStatusPlaceholder = `$${values.length}`
}
let generationGuardClause = ''
if (opts.expectedAttemptGeneration !== undefined) {
@@ -1667,7 +1687,11 @@ export async function updateInvocationStatus(
ELSE NULL
END,
completed_at = CASE WHEN $3 THEN now() ELSE NULL END
- WHERE id = $1${bindingClause}${statusGuardClause}${generationGuardClause}`,
+ WHERE id = $1${bindingClause}
+ AND (
+ ${expectedStatusPlaceholder ? `status = ${expectedStatusPlaceholder}` : 'TRUE'}
+ OR (status = $2 AND $2 NOT IN ('in_progress', 'accepted'))
+ )${generationGuardClause}`,
values
)
if ((result.rowCount ?? 0) === 0) return false
@@ -1735,23 +1759,71 @@ export async function reviveFailedInvocation(input: {
}
/**
- * Mark stale in_progress invocations as failed (mcp-host restart recovery —
- * plan §2.4). Returns the number of rows transitioned.
+ * Close stale in_progress invocations conservatively as provider_unavailable
+ * (mcp-host restart recovery — plan §2.4). A provider call may have executed
+ * before the host disappeared, so marking the row failed would allow the
+ * idempotency authorizer to revive it and create a second billable call. The
+ * terminal provider_unavailable state is intentionally not auto-revivable;
+ * callers must choose a fresh idempotency key after an operator investigates.
+ * Returns the number of rows transitioned.
*/
-export async function failStaleInvocations(_olderThanSeconds: number): Promise<number> {
+export async function failStaleInvocations(olderThanSeconds: number): Promise<number> {
+ const timeoutSeconds = Math.max(1, Math.floor(olderThanSeconds))
return withTransaction(async db => {
const result = await db.query(
`UPDATE plugin_workload_sdk_invocations
- SET status = 'failed', updated_at = now(), completed_at = now()
- WHERE status = 'in_progress'
- AND lease_expires_at IS NOT NULL
- AND lease_expires_at < now()
- RETURNING id, attempt_generation`
+ SET status = 'provider_unavailable', updated_at = now(), completed_at = now()
+ WHERE status = 'in_progress'
+ AND (
+ (lease_expires_at IS NOT NULL AND lease_expires_at < now())
+ OR (
+ lease_expires_at IS NULL
+ AND updated_at < now() - interval '1 second' * $1
+ )
+ )
+ RETURNING id, attempt_generation`,
+ [timeoutSeconds]
)
for (const row of result.rows as Array<{ id: string; attempt_generation: number }>) {
+ const physicalAttempts = await db.query(
+ `SELECT id, recipe_namespace, recipe_name, attempt_generation,
+ attempt_index, target_ref, provider, model, credential_slot
+ FROM plugin_workload_sdk_provider_attempts
+ WHERE invocation_id = $1
+ AND attempt_generation = $2
+ AND status IN ('reserved', 'in_progress', 'complete', 'failed')
+ FOR UPDATE`,
+ [row.id, row.attempt_generation]
+ )
+ for (const attempt of physicalAttempts.rows as Array<Record<string, unknown>>) {
+ // The host has disappeared, so no current JWT can prove a host_ref.
+ // Persist an unattributed unknown outcome instead of inventing one
+ // from recipe names; the physical-attempt PK makes this idempotent.
+ await db.query(
+ `INSERT INTO plugin_workload_sdk_spend_outcomes
+ (provider_attempt_id, invocation_id, recipe_namespace, recipe_name,
+ attempt_generation, attempt_index, target_ref, host_ref, provider, model,
+ credential_slot, outcome, reason, input_tokens, output_tokens, usage_request_id)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, NULL, $8, $9, $10, 'unknown',
+ 'stale_lease', NULL, NULL, NULL)
+ ON CONFLICT (provider_attempt_id) DO NOTHING`,
+ [
+ String(attempt.id),
+ row.id,
+ String(attempt.recipe_namespace),
+ String(attempt.recipe_name),
+ Number(attempt.attempt_generation),
+ Number(attempt.attempt_index),
+ String(attempt.target_ref),
+ String(attempt.provider),
+ String(attempt.model),
+ String(attempt.credential_slot),
+ ]
+ )
+ }
await db.query(
`UPDATE plugin_workload_sdk_invocation_attempts
- SET status = 'failed', lease_expires_at = NULL, completed_at = now()
+ SET status = 'provider_unavailable', lease_expires_at = NULL, completed_at = now()
WHERE invocation_id = $1 AND attempt_generation = $2`,
[row.id, row.attempt_generation]
)
diff --git a/control-api/src/services/pluginWorkloadSdkFinalization.ts b/control-api/src/services/pluginWorkloadSdkFinalization.ts
new file mode 100644
index 000000000..86eb83ef3
--- /dev/null
+++ b/control-api/src/services/pluginWorkloadSdkFinalization.ts
@@ -0,0 +1,445 @@
+import type { DbClient } from '../db.js'
+import { withTraceIngestTransaction } from './tracing/pools.js'
+import { projectAcceptedUsageEvents } from './tracing/usageProjection.js'
+import { ingestUsageEventsInTransaction } from './usageEvents.js'
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+
+export type PromptBridgeFinalizationStatus = 'complete' | 'provider_unavailable'
+
+export type PromptBridgeFinalizationUsage = {
+ llmSecretName: string
+ callerRef: string
+ fallbackUsed: boolean
+ attemptCount: number
+ inputTokens: number
+ outputTokens: number
+}
+
+export type PromptBridgeFinalizationInput = {
+ invocationId: string
+ recipeNamespace: string
+ recipeName: string
+ hostRef: string
+ attemptGeneration: number
+ providerAttemptId: string
+ providerAttemptIndex: number
+ status: PromptBridgeFinalizationStatus
+ target: {
+ targetRef: string
+ provider: string
+ model: string
+ credentialSlot: string
+ }
+ reason: string
+ usage?: PromptBridgeFinalizationUsage
+}
+
+export type PromptBridgeFinalizationResult = {
+ invocationId: string
+ providerAttemptId: string
+ status: PromptBridgeFinalizationStatus
+ outcome: 'exact' | 'unknown'
+ idempotent: boolean
+ usageAccepted: boolean
+}
+
+export type PromptBridgeFinalizationErrorCode =
+ | 'not_found'
+ | 'binding_mismatch'
+ | 'stale_attempt'
+ | 'conflict'
+ | 'invalid_request'
+
+export class PromptBridgeFinalizationError extends Error {
+ constructor(
+ readonly code: PromptBridgeFinalizationErrorCode,
+ message: string,
+ readonly httpStatus: 400 | 403 | 404 | 409
+ ) {
+ super(message)
+ this.name = 'PromptBridgeFinalizationError'
+ }
+}
+
+function requireUuid(value: string, field: string): void {
+ if (!UUID_RE.test(value)) {
+ throw new PromptBridgeFinalizationError('invalid_request', `${field} must be a UUID`, 400)
+ }
+}
+
+function requireNonEmpty(value: string, field: string): void {
+ if (!value.trim()) {
+ throw new PromptBridgeFinalizationError('invalid_request', `${field} is required`, 400)
+ }
+}
+
+function validateInput(input: PromptBridgeFinalizationInput): void {
+ requireUuid(input.invocationId, 'invocationId')
+ requireUuid(input.providerAttemptId, 'providerAttemptId')
+ requireNonEmpty(input.recipeNamespace, 'recipeNamespace')
+ requireNonEmpty(input.recipeName, 'recipeName')
+ requireNonEmpty(input.hostRef, 'hostRef')
+ requireNonEmpty(input.reason, 'reason')
+ if (!Number.isInteger(input.attemptGeneration) || input.attemptGeneration < 1) {
+ throw new PromptBridgeFinalizationError('invalid_request', 'attemptGeneration is required', 400)
+ }
+ if (!Number.isInteger(input.providerAttemptIndex) || input.providerAttemptIndex < 1) {
+ throw new PromptBridgeFinalizationError(
+ 'invalid_request',
+ 'providerAttemptIndex is required',
+ 400
+ )
+ }
+ requireNonEmpty(input.target.targetRef, 'target.targetRef')
+ requireNonEmpty(input.target.provider, 'target.provider')
+ requireNonEmpty(input.target.model, 'target.model')
+ requireNonEmpty(input.target.credentialSlot, 'target.credentialSlot')
+ if (input.status === 'complete') {
+ const usage = input.usage
+ if (!usage) {
+ throw new PromptBridgeFinalizationError(
+ 'invalid_request',
+ 'complete finalization requires exact usage',
+ 400
+ )
+ }
+ requireNonEmpty(usage.llmSecretName, 'usage.llmSecretName')
+ requireNonEmpty(usage.callerRef, 'usage.callerRef')
+ if (!Number.isInteger(usage.attemptCount) || usage.attemptCount < 1 || usage.attemptCount > 4) {
+ throw new PromptBridgeFinalizationError(
+ 'invalid_request',
+ 'usage.attemptCount is invalid',
+ 400
+ )
+ }
+ if (
+ !Number.isInteger(usage.inputTokens) ||
+ usage.inputTokens < 0 ||
+ !Number.isInteger(usage.outputTokens) ||
+ usage.outputTokens < 0
+ ) {
+ throw new PromptBridgeFinalizationError(
+ 'invalid_request',
+ 'usage token counts must be non-negative integers',
+ 400
+ )
+ }
+ } else if (input.usage) {
+ throw new PromptBridgeFinalizationError(
+ 'invalid_request',
+ 'provider_unavailable finalization cannot claim exact usage',
+ 400
+ )
+ }
+}
+
+type SpendOutcomeRow = {
+ provider_attempt_id: string
+ invocation_id: string
+ recipe_namespace: string
+ recipe_name: string
+ attempt_generation: number | string
+ attempt_index: number | string
+ target_ref: string
+ host_ref: string | null
+ provider: string
+ model: string
+ credential_slot: string
+ outcome: 'exact' | 'unknown'
+ input_tokens: number | string | null
+ output_tokens: number | string | null
+}
+
+function mapExistingOutcome(
+ row: SpendOutcomeRow,
+ input: PromptBridgeFinalizationInput
+): PromptBridgeFinalizationResult {
+ const expectedOutcome = input.status === 'complete' ? 'exact' : 'unknown'
+ if (
+ row.invocation_id !== input.invocationId ||
+ row.recipe_namespace !== input.recipeNamespace ||
+ row.recipe_name !== input.recipeName ||
+ Number(row.attempt_generation) !== input.attemptGeneration ||
+ Number(row.attempt_index) !== input.providerAttemptIndex ||
+ row.target_ref !== input.target.targetRef ||
+ (row.host_ref !== null && row.host_ref !== input.hostRef) ||
+ row.provider !== input.target.provider ||
+ row.model !== input.target.model ||
+ row.credential_slot !== input.target.credentialSlot ||
+ row.outcome !== expectedOutcome ||
+ (expectedOutcome === 'exact' &&
+ (Number(row.input_tokens) !== input.usage?.inputTokens ||
+ Number(row.output_tokens) !== input.usage?.outputTokens))
+ ) {
+ throw new PromptBridgeFinalizationError(
+ 'conflict',
+ 'provider attempt was finalized with a different immutable outcome',
+ 409
+ )
+ }
+ return {
+ invocationId: input.invocationId,
+ providerAttemptId: input.providerAttemptId,
+ status: input.status,
+ outcome: row.outcome,
+ idempotent: true,
+ usageAccepted: row.outcome === 'exact',
+ }
+}
+
+/**
+ * Finalize one physical promptBridge attempt and its logical invocation in a
+ * single trace-ingest transaction. Exact usage is inserted through the same
+ * receipt binder as the normal usage endpoint; unknown provider spend gets an
+ * immutable ledger row instead of disappearing behind provider_unavailable.
+ */
+export async function finalizePromptBridge(
+ input: PromptBridgeFinalizationInput
+): Promise<PromptBridgeFinalizationResult> {
+ validateInput(input)
+ return withTraceIngestTransaction(db => finalizePromptBridgeInTransaction(input, db))
+}
+
+export async function finalizePromptBridgeInTransaction(
+ input: PromptBridgeFinalizationInput,
+ db: DbClient
+): Promise<PromptBridgeFinalizationResult> {
+ validateInput(input)
+
+ const recipeLock = `plugin_workload_sdk:${input.recipeNamespace}/${input.recipeName}`
+ await db.query(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [recipeLock])
+
+ const existingResult = await db.query(
+ `SELECT provider_attempt_id, invocation_id, recipe_namespace, recipe_name,
+ attempt_generation, attempt_index, target_ref, provider, model,
+ credential_slot, host_ref, outcome, input_tokens, output_tokens
+ FROM plugin_workload_sdk_spend_outcomes
+ WHERE provider_attempt_id = $1
+ FOR UPDATE`,
+ [input.providerAttemptId]
+ )
+ const existing = existingResult.rows[0] as SpendOutcomeRow | undefined
+ if (existing) return mapExistingOutcome(existing, input)
+
+ const invocationResult = await db.query(
+ `SELECT id, recipe_namespace, recipe_name, method, status, attempt_generation
+ FROM plugin_workload_sdk_invocations
+ WHERE id = $1
+ AND recipe_namespace = $2
+ AND recipe_name = $3
+ FOR UPDATE`,
+ [input.invocationId, input.recipeNamespace, input.recipeName]
+ )
+ const invocation = invocationResult.rows[0] as Record<string, unknown> | undefined
+ if (!invocation) {
+ throw new PromptBridgeFinalizationError('not_found', 'invocation not found', 404)
+ }
+ if (invocation.method !== 'promptBridge') {
+ throw new PromptBridgeFinalizationError('binding_mismatch', 'invocation method mismatch', 403)
+ }
+ if (Number(invocation.attempt_generation) !== input.attemptGeneration) {
+ throw new PromptBridgeFinalizationError('stale_attempt', 'attempt generation is stale', 409)
+ }
+
+ const receiptResult = await db.query(
+ `SELECT invocation_id, recipe_namespace, recipe_name, attempt_generation, method, status
+ FROM plugin_workload_sdk_invocation_attempts
+ WHERE invocation_id = $1
+ AND recipe_namespace = $2
+ AND recipe_name = $3
+ AND attempt_generation = $4
+ FOR UPDATE`,
+ [input.invocationId, input.recipeNamespace, input.recipeName, input.attemptGeneration]
+ )
+ const receipt = receiptResult.rows[0] as Record<string, unknown> | undefined
+ if (!receipt || receipt.method !== 'promptBridge') {
+ throw new PromptBridgeFinalizationError(
+ 'not_found',
+ 'promptBridge attempt receipt not found',
+ 404
+ )
+ }
+
+ const providerResult = await db.query(
+ `SELECT id, invocation_id, recipe_namespace, recipe_name, attempt_generation,
+ attempt_index, target_ref, provider, model, credential_slot, status
+ FROM plugin_workload_sdk_provider_attempts
+ WHERE id = $1
+ FOR UPDATE`,
+ [input.providerAttemptId]
+ )
+ const providerAttempt = providerResult.rows[0] as Record<string, unknown> | undefined
+ if (!providerAttempt) {
+ throw new PromptBridgeFinalizationError('not_found', 'provider attempt not found', 404)
+ }
+ if (
+ String(providerAttempt.invocation_id) !== input.invocationId ||
+ String(providerAttempt.recipe_namespace) !== input.recipeNamespace ||
+ String(providerAttempt.recipe_name) !== input.recipeName ||
+ Number(providerAttempt.attempt_generation) !== input.attemptGeneration ||
+ Number(providerAttempt.attempt_index) !== input.providerAttemptIndex ||
+ String(providerAttempt.target_ref) !== input.target.targetRef ||
+ String(providerAttempt.provider) !== input.target.provider ||
+ String(providerAttempt.model) !== input.target.model ||
+ String(providerAttempt.credential_slot) !== input.target.credentialSlot
+ ) {
+ throw new PromptBridgeFinalizationError(
+ 'binding_mismatch',
+ 'provider attempt binding mismatch',
+ 403
+ )
+ }
+
+ const expectedStatus = input.status
+ const currentInvocationStatus = String(invocation.status)
+ const currentReceiptStatus = String(receipt.status)
+ const currentProviderStatus = String(providerAttempt.status)
+ const compatibleStatuses = new Set(['in_progress', expectedStatus])
+ // SDK-only success is finalized atomically by this service, so the normal
+ // path leaves the physical attempt in_progress until usage/outcome commit.
+ // Accept terminal provider states on the unknown path as a recovery fence:
+ // older hosts and an ACK race may have marked the physical row complete (or
+ // provider_unavailable) before the durable spend row was inserted. The
+ // unknown ledger entry is then the only honest accounting result and still
+ // prevents replay.
+ const compatibleProviderStatuses =
+ input.status === 'provider_unavailable'
+ ? new Set(['in_progress', 'provider_unavailable', 'complete', 'failed'])
+ : new Set(['in_progress', 'complete'])
+ if (
+ !compatibleStatuses.has(currentInvocationStatus) ||
+ !compatibleStatuses.has(currentReceiptStatus) ||
+ !compatibleProviderStatuses.has(currentProviderStatus)
+ ) {
+ throw new PromptBridgeFinalizationError(
+ 'conflict',
+ 'attempt already has a conflicting terminal outcome',
+ 409
+ )
+ }
+
+ const outcome = input.status === 'complete' ? 'exact' : 'unknown'
+ let usageAccepted = false
+
+ // Promote the immutable physical and attempt receipts before exact usage is
+ // passed through the normal binder. The enclosing transaction rolls these
+ // transitions back if usage validation/projection fails.
+ await db.query(
+ `UPDATE plugin_workload_sdk_provider_attempts
+ SET status = $2,
+ completed_at = now(),
+ lease_expires_at = NULL,
+ usage_request_id = CASE WHEN $3 THEN $1 ELSE usage_request_id END
+ WHERE id = $1`,
+ [input.providerAttemptId, expectedStatus, input.status === 'complete']
+ )
+ await db.query(
+ `UPDATE plugin_workload_sdk_invocation_attempts
+ SET status = $2, completed_at = now(), lease_expires_at = NULL
+ WHERE invocation_id = $1 AND attempt_generation = $3`,
+ [input.invocationId, expectedStatus, input.attemptGeneration]
+ )
+
+ if (input.status === 'complete') {
+ const usage = input.usage!
+ const event = {
+ request_id: input.providerAttemptId,
+ ts: new Date().toISOString(),
+ run_id: null,
+ host_ref: input.hostRef,
+ context_ref: null,
+ team_id: null,
+ provider: input.target.provider,
+ model: input.target.model,
+ llm_secret_name: usage.llmSecretName,
+ source_kind: 'plugin_workload_sdk',
+ user_id: null,
+ sender: usage.callerRef,
+ channel_type: 'plugin_workload_sdk',
+ recipe_name: input.recipeName,
+ cron_job_id: null,
+ task_id: null,
+ iteration: null,
+ input_tokens: usage.inputTokens,
+ output_tokens: usage.outputTokens,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ cache_tokens_reported: false,
+ prompt_bridge_metadata: {
+ invocation_id: input.invocationId,
+ target_ref: input.target.targetRef,
+ credential_slot: input.target.credentialSlot,
+ fallback_used: usage.fallbackUsed,
+ attempt_count: usage.attemptCount,
+ attempt_generation: input.attemptGeneration,
+ provider_attempt_id: input.providerAttemptId,
+ provider_attempt_index: input.providerAttemptIndex,
+ },
+ }
+ const ingest = await ingestUsageEventsInTransaction([event], db, {
+ recipeNamespace: input.recipeNamespace,
+ recipeName: input.recipeName,
+ })
+ if (
+ ingest.bindingViolation ||
+ ingest.result.rejected > 0 ||
+ ingest.result.accepted + ingest.result.duplicates !== 1
+ ) {
+ throw new PromptBridgeFinalizationError(
+ 'conflict',
+ 'exact provider usage could not be bound to its physical receipt',
+ 409
+ )
+ }
+ if (ingest.acceptedEvents.length > 0) {
+ await projectAcceptedUsageEvents(db, ingest.acceptedEvents, new Map(), {
+ recipeNamespace: input.recipeNamespace,
+ recipeName: input.recipeName,
+ hostRef: input.hostRef,
+ })
+ }
+ usageAccepted = true
+ }
+
+ await db.query(
+ `UPDATE plugin_workload_sdk_invocations
+ SET status = $2, updated_at = now(), completed_at = now(), lease_expires_at = NULL
+ WHERE id = $1 AND attempt_generation = $3`,
+ [input.invocationId, expectedStatus, input.attemptGeneration]
+ )
+ await db.query(
+ `INSERT INTO plugin_workload_sdk_spend_outcomes
+ (provider_attempt_id, invocation_id, recipe_namespace, recipe_name,
+ attempt_generation, attempt_index, target_ref, host_ref, provider, model,
+ credential_slot, outcome, reason, input_tokens, output_tokens, usage_request_id)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)`,
+ [
+ input.providerAttemptId,
+ input.invocationId,
+ input.recipeNamespace,
+ input.recipeName,
+ input.attemptGeneration,
+ input.providerAttemptIndex,
+ input.target.targetRef,
+ input.hostRef,
+ input.target.provider,
+ input.target.model,
+ input.target.credentialSlot,
+ outcome,
+ input.reason,
+ input.usage?.inputTokens ?? null,
+ input.usage?.outputTokens ?? null,
+ input.status === 'complete' ? input.providerAttemptId : null,
+ ]
+ )
+
+ return {
+ invocationId: input.invocationId,
+ providerAttemptId: input.providerAttemptId,
+ status: input.status,
+ outcome,
+ idempotent: false,
+ usageAccepted,
+ }
+}
diff --git a/control-api/src/services/pluginWorkloadSdkSchema.ts b/control-api/src/services/pluginWorkloadSdkSchema.ts
index 76ec2eea5..f2f3e17a4 100644
--- a/control-api/src/services/pluginWorkloadSdkSchema.ts
+++ b/control-api/src/services/pluginWorkloadSdkSchema.ts
@@ -333,6 +333,11 @@ export async function addPluginWorkloadSdkProtocolAndRevocation(db: DbClient): P
ALTER TABLE plugin_workload_sdk_invocations
ADD COLUMN IF NOT EXISTS contract_version INTEGER NOT NULL DEFAULT 2;
+ -- Keep the default at v1 during the rolling-update compatibility window.
+ -- New writers send contract_version=2 explicitly; an older pod that omits
+ -- the column is therefore identifiable and can be swept conservatively.
+ ALTER TABLE plugin_workload_sdk_invocations
+ ALTER COLUMN contract_version SET DEFAULT 1;
DO $$ BEGIN
ALTER TABLE plugin_workload_sdk_invocations
ADD CONSTRAINT plugin_workload_sdk_invocations_contract_version_check
@@ -371,6 +376,17 @@ export async function addPluginWorkloadSdkProtocolAndRevocation(db: DbClient): P
AND invocations.contract_version = 1
AND invocations.status = 'failed';
+ DO $$ BEGIN
+ 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
+ );
+ EXCEPTION WHEN duplicate_object THEN NULL;
+ END $$;
+
CREATE INDEX IF NOT EXISTS plugin_workload_sdk_invocations_contract_idx
ON plugin_workload_sdk_invocations (recipe_namespace, recipe_name, contract_version, created_at DESC);
`)
@@ -448,3 +464,59 @@ export async function addPluginWorkloadSdkRuntimeAccess(db: DbClient): Promise<v
TO control_api_runtime;
`)
}
+
+/**
+ * Durable spend outcome for a physical promptBridge attempt. The provider
+ * attempt ledger prevents a second execution, while this table preserves the
+ * accounting truth when the provider response is known only to have possibly
+ * executed (for example, a timeout or a lost completion acknowledgement).
+ * Rows are immutable and keyed by the physical attempt id so retries of the
+ * finalization request are safe.
+ */
+export async function addPluginWorkloadSdkSpendOutcomeLedger(db: DbClient): Promise<void> {
+ await db.query(`
+ CREATE TABLE IF NOT EXISTS plugin_workload_sdk_spend_outcomes (
+ provider_attempt_id UUID PRIMARY KEY,
+ invocation_id UUID NOT NULL,
+ recipe_namespace TEXT NOT NULL,
+ recipe_name TEXT NOT NULL,
+ attempt_generation INTEGER NOT NULL CHECK (attempt_generation >= 1),
+ attempt_index INTEGER NOT NULL CHECK (attempt_index BETWEEN 1 AND 4),
+ target_ref TEXT NOT NULL,
+ -- A normal finalization is bound to the runtime JWT host_ref. A stale
+ -- lease can be detected only after mcp-host has disappeared, however,
+ -- so that recovery row is intentionally unattributed rather than
+ -- fabricating a host identity from recipe names.
+ host_ref TEXT NULL,
+ provider TEXT NOT NULL,
+ model TEXT NOT NULL,
+ credential_slot TEXT NOT NULL,
+ outcome TEXT NOT NULL CHECK (outcome IN ('exact', 'unknown')),
+ reason TEXT NOT NULL,
+ input_tokens INTEGER NULL CHECK (input_tokens IS NULL OR input_tokens >= 0),
+ output_tokens INTEGER NULL CHECK (output_tokens IS NULL OR output_tokens >= 0),
+ usage_request_id UUID NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT plugin_workload_sdk_spend_outcomes_token_pair_check
+ CHECK ((outcome = 'exact' AND input_tokens IS NOT NULL AND output_tokens IS NOT NULL)
+ OR (outcome = 'unknown' AND input_tokens IS NULL AND output_tokens IS NULL))
+ );
+ CREATE INDEX IF NOT EXISTS plugin_workload_sdk_spend_outcomes_recipe_idx
+ ON plugin_workload_sdk_spend_outcomes (recipe_namespace, recipe_name, created_at DESC);
+ REVOKE ALL ON TABLE plugin_workload_sdk_spend_outcomes
+ FROM PUBLIC, trace_maintenance_runtime, workflow_recipes_runtime;
+ GRANT SELECT, INSERT ON TABLE plugin_workload_sdk_spend_outcomes TO control_api_runtime;
+ `)
+}
+
+/**
+ * The spend ledger was initially shipped with a required host_ref. Stale
+ * lease recovery has no bearer token from which to prove that binding, so
+ * existing clusters must converge to the same nullable shape as fresh ones.
+ */
+export async function relaxPluginWorkloadSdkSpendOutcomeHostRef(db: DbClient): Promise<void> {
+ await db.query(`
+ ALTER TABLE plugin_workload_sdk_spend_outcomes
+ ALTER COLUMN host_ref DROP NOT NULL;
+ `)
+}
diff --git a/control-api/src/services/usageEvents.ts b/control-api/src/services/usageEvents.ts
index 0fb7e7897..39c57c17a 100644
--- a/control-api/src/services/usageEvents.ts
+++ b/control-api/src/services/usageEvents.ts
@@ -53,10 +53,22 @@ export type UsageIngestResult = {
export type UsageIngestTransactionResult = {
result: UsageIngestResult
acceptedEvents: LlmUsageEvent[]
+ bindingViolation?: UsageBindingViolation
+}
+
+export type UsageBindingViolation = {
+ index: number
+ reason: 'recipe_token_invalid_sdk_usage_binding'
+}
+
+export type UsageBindingContext = {
+ recipeNamespace: string
+ recipeName: string
}
type PromptBridgeAttemptBinding = {
invocation_id: string
+ recipe_namespace: string
recipe_name: string
attempt_generation: number
method: string
@@ -73,6 +85,8 @@ type ProviderAttemptBinding = {
model: string
credential_slot: string
status: string
+ recipe_namespace: string
+ recipe_name: string
}
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
@@ -342,10 +356,11 @@ function buildInsertParams(events: LlmUsageEvent[]): unknown[] {
* that actually executed, while a stale generation or forged target is
* rejected before it can enter the usage ledger.
*/
-async function filterEventsByAttemptReceipt(
+async function bindEventsToAttemptReceipts(
events: LlmUsageEvent[],
- db: DbClient
-): Promise<{ accepted: LlmUsageEvent[]; rejected: number }> {
+ db: DbClient,
+ binding?: UsageBindingContext
+): Promise<{ accepted: LlmUsageEvent[]; rejected: number; violation?: UsageBindingViolation }> {
// Both runtime lanes use the same immutable attempt receipt. SDK-only
// hosts emit source_kind=plugin_workload_sdk; step-bearing hosts retain
// source_kind=workflow for run attribution but mark the channel as the
@@ -358,6 +373,16 @@ async function filterEventsByAttemptReceipt(
event.source_kind === 'workflow')
const sdkEvents = events.filter(isPromptBridgeSdkEvent)
if (sdkEvents.length === 0) return { accepted: events, rejected: 0 }
+ if (!binding) {
+ return {
+ accepted: [],
+ rejected: sdkEvents.length,
+ violation: {
+ index: events.findIndex(isPromptBridgeSdkEvent),
+ reason: 'recipe_token_invalid_sdk_usage_binding',
+ },
+ }
+ }
const invocationIds = [
...new Set(
sdkEvents
@@ -373,10 +398,12 @@ async function filterEventsByAttemptReceipt(
}
const result = await db.query(
`SELECT attempts.invocation_id::text, attempts.attempt_generation, attempts.method,
- attempts.target_refs, attempts.recipe_name
+ attempts.target_refs, attempts.recipe_namespace, attempts.recipe_name
FROM plugin_workload_sdk_invocation_attempts attempts
- WHERE attempts.invocation_id = ANY($1::uuid[])`,
- [invocationIds]
+ WHERE attempts.invocation_id = ANY($1::uuid[])
+ AND attempts.recipe_namespace = $2
+ AND attempts.recipe_name = $3`,
+ [invocationIds, binding.recipeNamespace, binding.recipeName]
)
const receipts = new Map<string, PromptBridgeAttemptBinding>()
for (const row of result.rows as PromptBridgeAttemptBinding[]) {
@@ -388,10 +415,13 @@ async function filterEventsByAttemptReceipt(
const providerAttempts = providerAttemptIds.length
? await db.query(
`SELECT id::text, invocation_id::text, attempt_generation, attempt_index,
- target_ref, provider, model, credential_slot, status
+ target_ref, provider, model, credential_slot, status,
+ recipe_namespace, recipe_name
FROM plugin_workload_sdk_provider_attempts
- WHERE id = ANY($1::uuid[])`,
- [[...new Set(providerAttemptIds)]]
+ WHERE id = ANY($1::uuid[])
+ AND recipe_namespace = $2
+ AND recipe_name = $3`,
+ [[...new Set(providerAttemptIds)], binding.recipeNamespace, binding.recipeName]
)
: { rows: [] }
const providerAttemptById = new Map<string, ProviderAttemptBinding>()
@@ -421,10 +451,14 @@ async function filterEventsByAttemptReceipt(
const physicalCompatible =
hasPhysicalAttempt &&
receipt?.method === 'promptBridge' &&
+ receipt.recipe_namespace === binding.recipeNamespace &&
+ receipt.recipe_name === binding.recipeName &&
receipt.recipe_name === event.recipe_name &&
typeof targetRef === 'string' &&
targetRefs.some(ref => ref === targetRef) &&
providerAttemptById.get(providerAttemptId!)?.invocation_id === invocationId &&
+ providerAttemptById.get(providerAttemptId!)?.recipe_namespace === binding.recipeNamespace &&
+ providerAttemptById.get(providerAttemptId!)?.recipe_name === binding.recipeName &&
providerAttemptById.get(providerAttemptId!)?.attempt_generation === generation &&
providerAttemptById.get(providerAttemptId!)?.attempt_index === providerAttemptIndex &&
providerAttemptById.get(providerAttemptId!)?.target_ref === targetRef &&
@@ -438,7 +472,21 @@ async function filterEventsByAttemptReceipt(
rejected += 1
}
}
- return { accepted, rejected }
+ const firstInvalidSdkEvent = events.findIndex(
+ event => isPromptBridgeSdkEvent(event) && !accepted.includes(event)
+ )
+ return {
+ accepted,
+ rejected,
+ ...(firstInvalidSdkEvent >= 0
+ ? {
+ violation: {
+ index: firstInvalidSdkEvent,
+ reason: 'recipe_token_invalid_sdk_usage_binding',
+ },
+ }
+ : {}),
+ }
}
export async function ingestUsageEvents(
@@ -450,7 +498,8 @@ export async function ingestUsageEvents(
export async function ingestUsageEventsInTransaction(
rawEvents: unknown[],
- db: DbClient
+ db: DbClient,
+ binding?: UsageBindingContext
): Promise<UsageIngestTransactionResult> {
const total = rawEvents.length
let validated: LlmUsageEvent[] = []
@@ -466,7 +515,14 @@ export async function ingestUsageEventsInTransaction(
}
}
- const receiptFilter = await filterEventsByAttemptReceipt(validated, db)
+ const receiptFilter = await bindEventsToAttemptReceipts(validated, db, binding)
+ if (receiptFilter.violation) {
+ return {
+ result: { accepted: 0, duplicates: 0, rejected: rejected + receiptFilter.rejected },
+ acceptedEvents: [],
+ bindingViolation: receiptFilter.violation,
+ }
+ }
validated = receiptFilter.accepted
rejected += receiptFilter.rejected
if (validated.length === 0) {
diff --git a/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.ts b/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.ts
index 3a46ddc94..d9326b8be 100644
--- a/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.ts
+++ b/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.ts
@@ -12,6 +12,8 @@ describe('plugin workload SDK protocol migration', () => {
const migrationSql = String(query.mock.calls[0]?.[0])
expect(migrationSql).toContain('completed_at = COALESCE(attempts.completed_at, now())')
+ expect(migrationSql).toContain('ALTER COLUMN contract_version SET DEFAULT 1')
+ expect(migrationSql).toContain('plugin_workload_sdk_invocations_v2_lease_check')
})
it('grants attempt-ledger DML only to control_api_runtime', async () => {
diff --git a/control-api/test/network.gateway.intent.test.ts b/control-api/test/network.gateway.intent.test.ts
index 48401737f..490f76a7a 100644
--- a/control-api/test/network.gateway.intent.test.ts
+++ b/control-api/test/network.gateway.intent.test.ts
@@ -333,13 +333,13 @@ describe('network/gateway intent (manifest-level)', () => {
expect(gatewayConf).not.toContain('/api/v1/external/')
})
- it('keeps the Minikube control-api Marketplace on the branch-local registry', () => {
+ it('keeps the Minikube control-api Marketplace on the shared registry', () => {
const controlApiConfig = read(`${OVERLAYS}/minikube/configmaps/control-api-config.yaml`)
- expect(controlApiConfig).toContain(
+ expect(controlApiConfig).toContain("CLERUM_REGISTRY_URL: 'https://registry.evenfire.ai'")
+ expect(controlApiConfig).not.toContain(
"CLERUM_REGISTRY_URL: 'http://registry-api.registry.svc.cluster.local:8085'"
)
- expect(controlApiConfig).not.toContain("CLERUM_REGISTRY_URL: 'https://registry.evenfire.ai'")
})
it('keeps the stateless heartbeat route POST-only through the mcp-host gateway', () => {
diff --git a/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts b/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
index f8476eadb..d1817842a 100644
--- a/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
+++ b/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
@@ -7,6 +7,7 @@ import * as notificationEmitter from '../src/services/notificationEmitter.js'
import * as authorizer from '../src/services/pluginWorkloadSdkAuthorizer.js'
import { issuePluginWorkloadSdkCredentialTicket } from '../src/services/pluginWorkloadSdkCredentialTicket.js'
import * as sdkDb from '../src/services/pluginWorkloadSdkDb.js'
+import * as finalizer from '../src/services/pluginWorkloadSdkFinalization.js'
import * as auditor from '../src/services/pluginWorkloadSdkInvocationAuditor.js'
import * as mcpHostJwt from '../src/utils/auth/mcpHostJwtToken.js'
@@ -65,6 +66,13 @@ vi.mock('../src/services/pluginWorkloadSdkInvocationAuditor.js', async () => {
}
})
+vi.mock('../src/services/pluginWorkloadSdkFinalization.js', async () => {
+ const actual = await vi.importActual<
+ typeof import('../src/services/pluginWorkloadSdkFinalization.js')
+ >('../src/services/pluginWorkloadSdkFinalization.js')
+ return { ...actual, finalizePromptBridge: vi.fn() }
+})
+
const NS = 'sandbox-recipes'
const RECIPE = 'sdk-recipe'
@@ -111,6 +119,7 @@ beforeEach(() => {
vi.mocked(authorizer.authorizeClientNotification).mockReset()
vi.mocked(sdkDb.listInvocations).mockReset()
vi.mocked(auditor.markInvocationStatus).mockReset().mockResolvedValue(true)
+ vi.mocked(finalizer.finalizePromptBridge).mockReset()
vi.mocked(sdkDb.getInvocationById).mockReset()
vi.mocked(sdkDb.getPluginWorkloadSdkAttemptReceipt).mockReset()
vi.mocked(sdkDb.getPluginWorkloadSdkProviderAttempt).mockReset()
@@ -773,6 +782,74 @@ describe('POST /mcp-host/plugin-workload-sdk/invocations/:id/status', () => {
})
})
+describe('POST /mcp-host/plugin-workload-sdk/invocations/:id/finalize', () => {
+ const finalizationBody = {
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ invocationId: 'inv-1',
+ attemptGeneration: 1,
+ providerAttemptId: '22222222-2222-4222-8222-222222222222',
+ providerAttemptIndex: 1,
+ status: 'complete',
+ reason: 'provider_completed',
+ target: {
+ targetRef: 'primary-zai',
+ provider: 'zai',
+ model: 'glm-4.7',
+ credentialSlot: 'zai-api-key',
+ },
+ usage: {
+ llmSecretName: 'zai-api-key',
+ callerRef: 'api',
+ fallbackUsed: false,
+ attemptCount: 1,
+ inputTokens: 2,
+ outputTokens: 3,
+ },
+ }
+
+ it('passes the recipe-bound finalization request to the atomic service', async () => {
+ vi.mocked(finalizer.finalizePromptBridge).mockResolvedValue({
+ invocationId: 'inv-1',
+ providerAttemptId: finalizationBody.providerAttemptId,
+ status: 'complete',
+ outcome: 'exact',
+ idempotent: false,
+ usageAccepted: true,
+ })
+ const res = await request(buildApp())
+ .post('/mcp-host/plugin-workload-sdk/invocations/inv-1/finalize')
+ .set('Authorization', `Bearer ${issueSdkToken()}`)
+ .send(finalizationBody)
+ expect(res.status).toBe(201)
+ expect(res.body).toMatchObject({ outcome: 'exact', usageAccepted: true })
+ expect(finalizer.finalizePromptBridge).toHaveBeenCalledWith(
+ expect.objectContaining({
+ invocationId: 'inv-1',
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ hostRef: expect.any(String),
+ })
+ )
+ })
+
+ it('returns a structured conflict without allowing a retryable provider call', async () => {
+ vi.mocked(finalizer.finalizePromptBridge).mockRejectedValue(
+ new finalizer.PromptBridgeFinalizationError(
+ 'conflict',
+ 'provider attempt was finalized with a different immutable outcome',
+ 409
+ )
+ )
+ const res = await request(buildApp())
+ .post('/mcp-host/plugin-workload-sdk/invocations/inv-1/finalize')
+ .set('Authorization', `Bearer ${issueSdkToken()}`)
+ .send(finalizationBody)
+ expect(res.status).toBe(409)
+ expect(res.body).toMatchObject({ error: 'idempotency_conflict', retryable: false })
+ })
+})
+
describe('GET /mcp-host/plugin-workload-sdk/invocations/:recipeRef', () => {
it('returns 403 binding_mismatch for a recipeRef outside the JWT binding', async () => {
const res = await request(buildApp())
diff --git a/control-api/test/services.pluginWorkloadSdkDb.test.ts b/control-api/test/services.pluginWorkloadSdkDb.test.ts
index 652140d43..988ecb1d2 100644
--- a/control-api/test/services.pluginWorkloadSdkDb.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkDb.test.ts
@@ -7,6 +7,7 @@ import {
finalizePluginWorkloadSdkRevocation,
getPluginWorkloadSdkLegacyGrantInventory,
hashPromptTargetPolicy,
+ markPluginWorkloadSdkProviderAttemptStatus,
redeemPluginWorkloadSdkCredentialTicketJti,
registerPluginWorkloadSdkCredentialTicketJti,
reservePluginWorkloadSdkProviderAttempt,
@@ -346,6 +347,7 @@ describe('invocation retry lifecycle timestamps', () => {
recipeNamespace: 'sandbox-recipes',
recipeName: 'sdk-recipe',
expectedCurrentStatus: 'failed',
+ leaseSeconds: 180,
})
).resolves.toBe(true)
const [sql, params] = vi.mocked(pool.query).mock.calls[0] as unknown as [string, unknown[]]
@@ -355,18 +357,96 @@ describe('invocation retry lifecycle timestamps', () => {
'inv-1',
'in_progress',
false,
- 0,
+ 180,
'sandbox-recipes',
'sdk-recipe',
'failed',
])
})
+ it('rejects an in-progress transition without a positive lease', async () => {
+ await expect(
+ updateInvocationStatus('inv-1', 'in_progress', {
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'sdk-recipe',
+ })
+ ).resolves.toBe(false)
+ expect(pool.query).not.toHaveBeenCalled()
+ })
+
+ it('accepts a repeated terminal invocation report without weakening the CAS guard', async () => {
+ await expect(
+ updateInvocationStatus('inv-1', 'complete', {
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'sdk-recipe',
+ expectedCurrentStatus: 'in_progress',
+ expectedAttemptGeneration: 1,
+ })
+ ).resolves.toBe(true)
+ const [sql] = vi.mocked(pool.query).mock.calls[0] as unknown as [string, unknown[]]
+ expect(sql).toContain('status = $7')
+ expect(sql).toContain("status = $2 AND $2 NOT IN ('in_progress', 'accepted')")
+ })
+
+ it('makes provider-attempt terminal reports idempotent and outcome-specific', async () => {
+ await expect(
+ markPluginWorkloadSdkProviderAttemptStatus({
+ id: 'attempt-1',
+ invocationId: 'inv-1',
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'sdk-recipe',
+ attemptGeneration: 1,
+ status: 'complete',
+ })
+ ).resolves.toBe(true)
+ const [sql] = vi.mocked(pool.query).mock.calls[0] as unknown as [string, unknown[]]
+ expect(sql).toContain('status = $6')
+ expect(sql).toContain("status IN ('reserved', 'in_progress')")
+ })
+
it('sweeps by the latest retry timestamp rather than the original reservation', async () => {
+ vi.mocked(pool.query)
+ .mockResolvedValueOnce({
+ rows: [{ id: 'inv-1', attempt_generation: 2 }],
+ rowCount: 1,
+ } as never)
+ .mockResolvedValueOnce({
+ rows: [
+ {
+ id: 'attempt-2',
+ recipe_namespace: 'sandbox-recipes',
+ recipe_name: 'sdk-recipe',
+ attempt_generation: 2,
+ attempt_index: 1,
+ target_ref: 'primary-openai',
+ provider: 'openai',
+ model: 'gpt-5.4-mini',
+ credential_slot: 'openai-api-key',
+ },
+ ],
+ rowCount: 1,
+ } as never)
+ .mockResolvedValue({ rows: [], rowCount: 1 } as never)
await expect(failStaleInvocations(150)).resolves.toBe(1)
const [sql] = vi.mocked(pool.query).mock.calls[0] as unknown as [string, unknown[]]
+ expect(sql).toContain("SET status = 'provider_unavailable'")
expect(sql).toContain('lease_expires_at < now()')
- expect(sql).not.toContain('created_at < now()')
+ expect(sql).toContain('lease_expires_at IS NULL')
+ expect(sql).toContain('updated_at < now()')
+ expect(sql).toContain('RETURNING id, attempt_generation')
+ expect(pool.query).toHaveBeenCalledTimes(5)
+ expect(vi.mocked(pool.query).mock.calls[1]?.[0] as string).toContain(
+ 'FROM plugin_workload_sdk_provider_attempts'
+ )
+ expect(vi.mocked(pool.query).mock.calls[2]?.[0] as string).toContain(
+ 'INSERT INTO plugin_workload_sdk_spend_outcomes'
+ )
+ expect(vi.mocked(pool.query).mock.calls[3]?.[0] as string).toContain(
+ "SET status = 'provider_unavailable'"
+ )
+ expect(vi.mocked(pool.query).mock.calls[4]?.[0] as string).toContain(
+ "SET status = 'provider_unavailable'"
+ )
})
})
diff --git a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts b/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
new file mode 100644
index 000000000..1fa87ceab
--- /dev/null
+++ b/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
@@ -0,0 +1,303 @@
+import { describe, expect, it, vi } from 'vitest'
+import {
+ PromptBridgeFinalizationError,
+ finalizePromptBridgeInTransaction,
+} from '../src/services/pluginWorkloadSdkFinalization.js'
+
+const ingest = vi.hoisted(() => vi.fn())
+const project = vi.hoisted(() => vi.fn())
+
+vi.mock('../src/services/usageEvents.js', () => ({
+ ingestUsageEventsInTransaction: ingest,
+}))
+vi.mock('../src/services/tracing/usageProjection.js', () => ({
+ projectAcceptedUsageEvents: project,
+}))
+
+const IDS = {
+ invocation: '11111111-1111-4111-8111-111111111111',
+ providerAttempt: '22222222-2222-4222-8222-222222222222',
+}
+
+const inputBase = {
+ invocationId: IDS.invocation,
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'prompt-notify',
+ hostRef: 'sandbox-recipes/prompt-notify',
+ attemptGeneration: 1,
+ providerAttemptId: IDS.providerAttempt,
+ providerAttemptIndex: 1,
+ target: {
+ targetRef: 'primary-openai',
+ provider: 'openai',
+ model: 'gpt-5.4-mini',
+ credentialSlot: 'openai-api-key',
+ },
+ reason: 'provider_completed',
+} as const
+
+function dbWithRows(...rows: unknown[]) {
+ const query = vi.fn()
+ for (const row of rows)
+ query.mockResolvedValueOnce({ rows: Array.isArray(row) ? row : [row], rowCount: 1 })
+ return { query }
+}
+
+describe('Plugin Workload SDK promptBridge finalization', () => {
+ it('atomically records exact usage and terminalizes the physical/logical receipts', async () => {
+ const usageEvent = { request_id: IDS.providerAttempt }
+ ingest.mockResolvedValueOnce({
+ result: { accepted: 1, duplicates: 0, rejected: 0 },
+ acceptedEvents: [usageEvent],
+ })
+ project.mockResolvedValueOnce(1)
+ const db = dbWithRows(
+ [],
+ [],
+ {
+ id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ method: 'promptBridge',
+ status: 'in_progress',
+ attempt_generation: 1,
+ },
+ {
+ invocation_id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ attempt_generation: 1,
+ method: 'promptBridge',
+ status: 'in_progress',
+ },
+ {
+ id: IDS.providerAttempt,
+ invocation_id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ attempt_generation: 1,
+ attempt_index: 1,
+ target_ref: inputBase.target.targetRef,
+ host_ref: inputBase.hostRef,
+ provider: inputBase.target.provider,
+ model: inputBase.target.model,
+ credential_slot: inputBase.target.credentialSlot,
+ status: 'in_progress',
+ },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 }
+ )
+
+ const result = await finalizePromptBridgeInTransaction(
+ {
+ ...inputBase,
+ status: 'complete',
+ usage: {
+ llmSecretName: 'openai-api-key',
+ callerRef: 'scanner',
+ fallbackUsed: false,
+ attemptCount: 1,
+ inputTokens: 12,
+ outputTokens: 7,
+ },
+ },
+ db as never
+ )
+
+ expect(result).toMatchObject({
+ status: 'complete',
+ outcome: 'exact',
+ idempotent: false,
+ usageAccepted: true,
+ })
+ expect(ingest).toHaveBeenCalledWith(
+ [expect.objectContaining({ request_id: IDS.providerAttempt })],
+ db,
+ { recipeNamespace: inputBase.recipeNamespace, recipeName: inputBase.recipeName }
+ )
+ expect(project).toHaveBeenCalledWith(db, [usageEvent], expect.any(Map), {
+ recipeNamespace: inputBase.recipeNamespace,
+ recipeName: inputBase.recipeName,
+ hostRef: inputBase.hostRef,
+ })
+ const sql = db.query.mock.calls.map(([statement]: [string]) => statement).join('\n')
+ expect(sql).toContain('plugin_workload_sdk_spend_outcomes')
+ expect(sql).toContain('usage_request_id')
+ })
+
+ it('persists an explicit unknown spend outcome without inventing token counts', async () => {
+ ingest.mockReset()
+ project.mockReset()
+ const db = dbWithRows(
+ [],
+ [],
+ {
+ id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ method: 'promptBridge',
+ status: 'in_progress',
+ attempt_generation: 1,
+ },
+ {
+ invocation_id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ attempt_generation: 1,
+ method: 'promptBridge',
+ status: 'in_progress',
+ },
+ {
+ id: IDS.providerAttempt,
+ invocation_id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ attempt_generation: 1,
+ attempt_index: 1,
+ target_ref: inputBase.target.targetRef,
+ provider: inputBase.target.provider,
+ model: inputBase.target.model,
+ credential_slot: inputBase.target.credentialSlot,
+ status: 'in_progress',
+ },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 }
+ )
+
+ const result = await finalizePromptBridgeInTransaction(
+ { ...inputBase, status: 'provider_unavailable', reason: 'outcome_unknown' },
+ db as never
+ )
+
+ expect(result).toMatchObject({
+ status: 'provider_unavailable',
+ outcome: 'unknown',
+ usageAccepted: false,
+ })
+ expect(ingest).not.toHaveBeenCalled()
+ expect(project).not.toHaveBeenCalled()
+ const insert = db.query.mock.calls.find(([statement]: [string]) =>
+ statement.includes('INSERT INTO plugin_workload_sdk_spend_outcomes')
+ )
+ expect(insert?.[1]).toEqual([
+ IDS.providerAttempt,
+ IDS.invocation,
+ inputBase.recipeNamespace,
+ inputBase.recipeName,
+ 1,
+ 1,
+ inputBase.target.targetRef,
+ inputBase.hostRef,
+ inputBase.target.provider,
+ inputBase.target.model,
+ inputBase.target.credentialSlot,
+ 'unknown',
+ 'outcome_unknown',
+ null,
+ null,
+ null,
+ ])
+ })
+
+ it('converts a previously acknowledged physical attempt into a durable unknown outcome', async () => {
+ const db = dbWithRows(
+ [],
+ [],
+ {
+ id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ method: 'promptBridge',
+ status: 'in_progress',
+ attempt_generation: 1,
+ },
+ {
+ invocation_id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ attempt_generation: 1,
+ method: 'promptBridge',
+ status: 'in_progress',
+ },
+ {
+ id: IDS.providerAttempt,
+ invocation_id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ attempt_generation: 1,
+ attempt_index: 1,
+ target_ref: inputBase.target.targetRef,
+ provider: inputBase.target.provider,
+ model: inputBase.target.model,
+ credential_slot: inputBase.target.credentialSlot,
+ status: 'complete',
+ },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 }
+ )
+
+ await expect(
+ finalizePromptBridgeInTransaction(
+ { ...inputBase, status: 'provider_unavailable', reason: 'outcome_unknown' },
+ db as never
+ )
+ ).resolves.toMatchObject({ outcome: 'unknown', usageAccepted: false })
+ expect(
+ db.query.mock.calls.some(([statement]: [string]) =>
+ statement.includes('INSERT INTO plugin_workload_sdk_spend_outcomes')
+ )
+ ).toBe(true)
+ })
+
+ it('replays the same physical finalization and rejects a conflicting outcome', async () => {
+ const row = {
+ provider_attempt_id: IDS.providerAttempt,
+ invocation_id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ attempt_generation: 1,
+ attempt_index: 1,
+ target_ref: inputBase.target.targetRef,
+ host_ref: inputBase.hostRef,
+ provider: inputBase.target.provider,
+ model: inputBase.target.model,
+ credential_slot: inputBase.target.credentialSlot,
+ outcome: 'unknown',
+ input_tokens: null,
+ output_tokens: null,
+ }
+ const db = dbWithRows([], row)
+ const unknown = {
+ ...inputBase,
+ status: 'provider_unavailable' as const,
+ reason: 'outcome_unknown',
+ }
+ await expect(finalizePromptBridgeInTransaction(unknown, db as never)).resolves.toMatchObject({
+ idempotent: true,
+ outcome: 'unknown',
+ })
+ const conflictingDb = dbWithRows([], row)
+ await expect(
+ finalizePromptBridgeInTransaction(
+ {
+ ...inputBase,
+ status: 'complete',
+ reason: 'provider_completed',
+ usage: {
+ llmSecretName: 'openai-api-key',
+ callerRef: 'scanner',
+ fallbackUsed: false,
+ attemptCount: 1,
+ inputTokens: 1,
+ outputTokens: 1,
+ },
+ },
+ conflictingDb as never
+ )
+ ).rejects.toMatchObject<PromptBridgeFinalizationError>({ code: 'conflict', httpStatus: 409 })
+ })
+})
diff --git a/control-api/test/services.pluginWorkloadSdkSchema.test.ts b/control-api/test/services.pluginWorkloadSdkSchema.test.ts
index ae40ba097..603f9671d 100644
--- a/control-api/test/services.pluginWorkloadSdkSchema.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkSchema.test.ts
@@ -63,4 +63,16 @@ describe('pluginWorkloadSdkSchema', () => {
expect(source).toMatch(/redeemed_at TIMESTAMPTZ NULL/)
expect(source).toMatch(/addPluginWorkloadSdkJitCredentialTicketColumns/)
})
+
+ it('persists exact or unknown provider spend as an immutable attempt ledger', () => {
+ const schemaPath = join(
+ dirname(fileURLToPath(import.meta.url)),
+ '../src/services/pluginWorkloadSdkSchema.ts'
+ )
+ const source = readFileSync(schemaPath, 'utf8')
+ expect(source).toMatch(/plugin_workload_sdk_spend_outcomes/)
+ expect(source).toMatch(/outcome IN \('exact', 'unknown'\)/)
+ expect(source).toMatch(/plugin_workload_sdk_spend_outcomes_token_pair_check/)
+ expect(source).toMatch(/addPluginWorkloadSdkSpendOutcomeLedger/)
+ })
})
diff --git a/control-api/test/services.usageEvents.test.ts b/control-api/test/services.usageEvents.test.ts
index 67273ce2b..156605765 100644
--- a/control-api/test/services.usageEvents.test.ts
+++ b/control-api/test/services.usageEvents.test.ts
@@ -1,5 +1,9 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { ingestUsageEvents, validateUsageEvent } from '../src/services/usageEvents.js'
+import {
+ ingestUsageEvents,
+ ingestUsageEventsInTransaction,
+ validateUsageEvent,
+} from '../src/services/usageEvents.js'
const mockPoolQuery = vi.fn()
vi.mock('../src/db.js', () => ({
@@ -33,6 +37,26 @@ const VALID_EVENT = {
prompt_bridge_metadata: null,
}
+const SDK_EVENT = {
+ ...VALID_EVENT,
+ host_ref: 'sandbox-recipes/sdk-recipe',
+ source_kind: 'plugin_workload_sdk',
+ channel_type: 'plugin_workload_sdk',
+ recipe_name: 'sdk-recipe',
+ llm_secret_name: 'zai-secret',
+ task_id: null,
+ prompt_bridge_metadata: {
+ invocation_id: '33333333-3333-4333-8333-333333333333',
+ target_ref: 'zai-primary',
+ credential_slot: 'zai-api-key',
+ fallback_used: false,
+ attempt_count: 1,
+ attempt_generation: 1,
+ provider_attempt_id: '44444444-4444-4444-8444-444444444444',
+ provider_attempt_index: 1,
+ },
+}
+
describe('validateUsageEvent', () => {
it('accepts a fully-populated valid event', () => {
expect(validateUsageEvent(VALID_EVENT)).not.toBeNull()
@@ -270,4 +294,20 @@ describe('ingestUsageEvents', () => {
])
expect(result).toEqual({ accepted: 1, duplicates: 1, rejected: 2 })
})
+
+ it('fails closed when SDK usage has no persisted authoritative receipt', async () => {
+ mockPoolQuery.mockResolvedValue({ rows: [], rowCount: 0 })
+ const db = { query: mockPoolQuery } as never
+ const result = await ingestUsageEventsInTransaction([SDK_EVENT], db, {
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'sdk-recipe',
+ })
+
+ expect(result.bindingViolation).toEqual({
+ index: 0,
+ reason: 'recipe_token_invalid_sdk_usage_binding',
+ })
+ expect(result.result.accepted).toBe(0)
+ expect(mockPoolQuery).toHaveBeenCalledTimes(2)
+ })
})
diff --git a/control-ui/app/plugin-workload-sdk/page.tsx b/control-ui/app/plugin-workload-sdk/page.tsx
index 307139ebf..7f2926991 100644
--- a/control-ui/app/plugin-workload-sdk/page.tsx
+++ b/control-ui/app/plugin-workload-sdk/page.tsx
@@ -36,8 +36,9 @@ import { useLlmAllowedModels } from '@lib/hooks/useLlmAllowedModels'
import {
LLM_PROVIDER_OPTIONS,
type LlmProvider,
- getCredentialSlotOptions,
+ buildPromptBridgeTargetPolicy,
getModelOptions,
+ getPromptBridgeCredentialSlotOptions,
getProviderLabel,
normalizeProvider,
} from '@lib/llm'
@@ -464,7 +465,7 @@ function GrantFormModal({
.then(result => {
if (cancelled) return
setAvailableCredentialKeys(
- Array.from(new Set((result.items ?? []).flatMap(item => item.keys))).sort((a, b) =>
+ Array.from(new Set((result.items ?? []).flatMap(item => item.keys ?? []))).sort((a, b) =>
a.localeCompare(b)
)
)
@@ -544,7 +545,7 @@ function GrantFormModal({
[allowedCatalog, modelProvider]
)
const credentialSlotOptions = useMemo(
- () => getCredentialSlotOptions(modelProvider, availableCredentialKeys),
+ () => getPromptBridgeCredentialSlotOptions(modelProvider, availableCredentialKeys),
[availableCredentialKeys, modelProvider]
)
const userOptions = useMemo(
@@ -590,23 +591,25 @@ function GrantFormModal({
quotaLimits.maxOutputTokens = grant.quotaLimits.maxOutputTokens
}
+ const routingPolicy =
+ family === 'promptBridge' ? buildPromptBridgeTargetPolicy(promptTargets) : undefined
const payload: PluginWorkloadSdkGrantInput = {
recipeNamespace: recipeNamespace.trim(),
recipeName: recipeName.trim(),
capabilityFamily: family,
// R1: persist the explicit provider (control-api requires it for
// promptBridge). Omitted for clientNotifications, which has no model.
- provider: family === 'promptBridge' ? promptTargets[0]?.provider : undefined,
+ provider: routingPolicy?.provider,
// Retained only as legacy inventory metadata; runtime selection uses the
// ordered targets below and never falls back to this flat list.
- allowedModels: family === 'promptBridge' ? promptTargets.map(target => target.model) : [],
+ allowedModels: routingPolicy?.allowedModels ?? [],
allowedEventTypes: family === 'clientNotifications' ? eventTypesList : [],
allowedTargetRefs: family === 'clientNotifications' ? parseList(allowedTargetRefs) : [],
allowedUserRefs: family === 'clientNotifications' ? allowedUserRefs : [],
allowedCallers: callersList,
quotaLimits,
- promptTargets: family === 'promptBridge' ? promptTargets : undefined,
- defaultTargetRef: family === 'promptBridge' ? promptTargets[0]?.targetRef : undefined,
+ promptTargets: routingPolicy?.promptTargets,
+ defaultTargetRef: routingPolicy?.defaultTargetRef,
}
// Edit mode: preserve modelPolicies, which the form does not expose, so the
// full-column upsert does not wipe policies configured outside this form.
diff --git a/control-ui/lib/__tests__/llmPolicy.test.ts b/control-ui/lib/__tests__/llmPolicy.test.ts
index 6e68f5d32..b12563b26 100644
--- a/control-ui/lib/__tests__/llmPolicy.test.ts
+++ b/control-ui/lib/__tests__/llmPolicy.test.ts
@@ -1,7 +1,9 @@
import { describe, expect, it } from 'vitest'
import {
type LlmModelCatalogEntry,
+ buildPromptBridgeTargetPolicy,
getCredentialSlotOptions,
+ getPromptBridgeCredentialSlotOptions,
normalizeLlmPolicy,
providerSupportsFallbackCredentialSlot,
validateLlmPolicy,
@@ -55,6 +57,57 @@ describe('getCredentialSlotOptions (spec R4.5.6)', () => {
})
})
+describe('getPromptBridgeCredentialSlotOptions', () => {
+ it('keeps canonical multiline and multi-slot provider identities selectable', () => {
+ expect(getPromptBridgeCredentialSlotOptions('vertex')).toEqual(['vertex-service-account-json'])
+ expect(getPromptBridgeCredentialSlotOptions('bedrock')).toEqual([
+ 'aws-access-key-id',
+ 'aws-secret-access-key',
+ ])
+ })
+
+ it('allows suffixed extra identities only for single-key providers', () => {
+ expect(
+ getPromptBridgeCredentialSlotOptions('claude', [
+ 'claude-api-key',
+ 'claude-api-key-fb1',
+ 'vertex-service-account-json-fb1',
+ ])
+ ).toEqual(['claude-api-key', 'claude-api-key-fb1'])
+ })
+})
+
+describe('buildPromptBridgeTargetPolicy', () => {
+ it('derives the default, provider and model inventory from ordered targets', () => {
+ const fallback = {
+ targetRef: 'fallback-openai',
+ provider: 'openai',
+ model: 'gpt-5.4',
+ credentialSlot: 'openai-api-key-fb1',
+ }
+ const primary = {
+ targetRef: 'primary-claude',
+ provider: 'claude',
+ model: 'claude-opus-4-8',
+ credentialSlot: 'claude-api-key',
+ }
+
+ expect(buildPromptBridgeTargetPolicy([primary, fallback])).toEqual({
+ provider: 'claude',
+ allowedModels: ['claude-opus-4-8', 'gpt-5.4'],
+ promptTargets: [primary, fallback],
+ defaultTargetRef: 'primary-claude',
+ })
+ })
+
+ it('does not invent a provider or default for an empty policy', () => {
+ expect(buildPromptBridgeTargetPolicy([])).toEqual({
+ allowedModels: [],
+ promptTargets: [],
+ })
+ })
+})
+
describe('validateLlmPolicy (client mirror of control-api gate)', () => {
it('accepts a policy whose fallback models are enabled', () => {
expect(
diff --git a/control-ui/lib/llm.ts b/control-ui/lib/llm.ts
index eae1db576..44d42668b 100644
--- a/control-ui/lib/llm.ts
+++ b/control-ui/lib/llm.ts
@@ -13,6 +13,33 @@ import {
// multi-slot secrets form itself is B3; here we only re-cable the data source.
export type LlmProvider = LlmProviderId
+export type PromptBridgeTargetPolicyInput = {
+ targetRef: string
+ provider: string
+ model: string
+ credentialSlot: string
+}
+
+/**
+ * Serialize the operator's ordered promptBridge list without inventing a
+ * second default-selection rule. The first reviewed target is authoritative;
+ * every other field is derived from that same ordered list.
+ */
+export function buildPromptBridgeTargetPolicy(targets: PromptBridgeTargetPolicyInput[]): {
+ provider?: string
+ allowedModels: string[]
+ promptTargets: PromptBridgeTargetPolicyInput[]
+ defaultTargetRef?: string
+} {
+ const promptTargets = targets.map(target => ({ ...target }))
+ const first = promptTargets[0]
+ return {
+ ...(first ? { provider: first.provider, defaultTargetRef: first.targetRef } : {}),
+ allowedModels: promptTargets.map(target => target.model),
+ promptTargets,
+ }
+}
+
export const LLM_PROVIDER_OPTIONS: Array<{ value: LlmProvider; label: string }> = PROVIDER_IDS.map(
id => ({ value: id, label: PROVIDER_DISPLAY_LABELS[id] })
)
@@ -579,6 +606,30 @@ export function getCredentialSlotOptions(
return Array.from(new Set([...registrySlots, ...extras]))
}
+/**
+ * Credential identities for an ordered promptBridge target. Unlike a Host
+ * failover override, a promptBridge target names the complete provider
+ * credential set that the WRC broker resolves for that attempt. Canonical
+ * multiline and multi-slot providers therefore remain selectable; only
+ * single-key providers may add suffixed extra slots.
+ */
+export function getPromptBridgeCredentialSlotOptions(
+ provider: LlmProvider,
+ secretKeys: string[] = []
+): string[] {
+ const slots = PROVIDER_CREDENTIAL_SLOTS[provider]
+ const registrySlots = slots.map(slot => slot.dataKey)
+ if (registrySlots.length === 0) return []
+ if (slots.length !== 1 || slots[0].multiline === true) return registrySlots
+
+ const prefixes = [...registrySlots, `${provider}-`]
+ const extras = secretKeys
+ .filter(key => !ALL_REGISTRY_SLOT_KEYS.has(key))
+ .filter(key => prefixes.some(prefix => key.startsWith(prefix)))
+ .sort((a, b) => a.localeCompare(b))
+ return Array.from(new Set([...registrySlots, ...extras]))
+}
+
// Derive the provider that owns a Secret dataKey, or null for a stray key
// (additive LLM secrets editor, spec B1). Prefix-aware — matching only
// canonical slots would lose operator-minted EXTRA slots (`claude-api-key-fb1`
diff --git a/control-ui/next-env.d.ts b/control-ui/next-env.d.ts
index c4b7818fb..9edff1c7c 100644
--- a/control-ui/next-env.d.ts
+++ b/control-ui/next-env.d.ts
@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
-import "./.next/dev/types/routes.d.ts";
+import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index e309c061c..02ee3adb1 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.379",
+ "version": "0.1.380",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.379",
+ "version": "0.1.380",
"dependencies": {
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
diff --git a/control-ui/package.json b/control-ui/package.json
index beca2d0af..e7be76a82 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.379",
+ "version": "0.1.380",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/deploy/scripts/control-api-runtime-access-profiles.tsv b/deploy/scripts/control-api-runtime-access-profiles.tsv
index 63cfbda45..db3459be8 100644
--- a/deploy/scripts/control-api-runtime-access-profiles.tsv
+++ b/deploy/scripts/control-api-runtime-access-profiles.tsv
@@ -38,6 +38,7 @@ plugin_workload_sdk_grants legacy_dml
plugin_workload_sdk_invocations legacy_dml
plugin_workload_sdk_provider_attempts legacy_dml
plugin_workload_sdk_quota_counters legacy_dml
+plugin_workload_sdk_spend_outcomes append
profiles legacy_dml
rate_limit_buckets legacy_dml
registry_connection legacy_dml
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index 18c7e81bc..7bca2fe3a 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.334",
+ "version": "0.1.335",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.334",
+ "version": "0.1.335",
"license": "MPL-2.0",
"dependencies": {
"@clerum/desktop-app-links": "file:../packages/desktop-app-links",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index 734fef64c..65ce5d94f 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.334",
+ "version": "0.1.335",
"private": true,
"license": "MPL-2.0",
"description": "Evenfire desktop client for secure agent and workflow access",
diff --git a/desktop-app/src/main.ts b/desktop-app/src/main.ts
index 6f533a905..9705ec6e5 100644
--- a/desktop-app/src/main.ts
+++ b/desktop-app/src/main.ts
@@ -34,6 +34,7 @@ const MAX_PENDING_EVENFIRE_URLS = 20
const sandboxUiDeepLinkQueue = new SandboxUiDeepLinkQueue()
let mainWindowLifecycleReady = false
let mainWindowRendererReady = false
+let appWindowVisibilityWired = false
const appServiceInitializer = createRetryableInitializer(() => appService.initialize())
function enqueuePendingEvenfireUrl(rawUrl: string): void {
@@ -116,9 +117,20 @@ function wireWindowVisibility(win: BrowserWindow): void {
win.on('restore', emit)
win.on('focus', emit)
win.on('blur', emit)
- // A future secondary BrowserWindow can take focus without emitting a focus
- // event on the main window. App-level events keep the main renderer's
- // application-focus view authoritative in that case as well.
+}
+
+/**
+ * App-level focus events are process-scoped. Register them once so closing and
+ * recreating the main window cannot accumulate listeners that retain a
+ * destroyed WebContents instance.
+ */
+function wireAppWindowVisibility(): void {
+ if (appWindowVisibilityWired) return
+ appWindowVisibilityWired = true
+ const emit = () => {
+ if (!mainWindow || mainWindow.isDestroyed()) return
+ mainWindow.webContents.send('window:visibility', windowState(mainWindow))
+ }
app.on('browser-window-focus', emit)
app.on('browser-window-blur', emit)
}
@@ -374,6 +386,7 @@ async function createWindow(): Promise<void> {
})
wireWindowVisibility(window)
+ wireAppWindowVisibility()
window.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
window.webContents.on('will-navigate', (event, url) => {
diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.ts
index 3e901e2d0..89fa0984c 100644
--- a/desktop-app/src/types.ts
+++ b/desktop-app/src/types.ts
@@ -250,11 +250,11 @@ export type WorkflowInputContractSchema = {
export type WorkflowInputValues = Record<string, string | number | boolean>
export type PluginWorkloadSdkCapabilityStatus = {
- state: 'validated' | 'disabled' | 'degraded'
+ state: 'validated' | 'awaiting_policy' | 'disabled' | 'degraded'
promptBridge: boolean
clientNotifications: boolean
message?: string
- validatedAt?: string
+ validatedAt?: string | null
}
export type WorkflowRecipeResource = Record<string, unknown> & {
diff --git a/desktop-app/ui/src/lib/__tests__/pluginWorkloadSdkCapability.test.ts b/desktop-app/ui/src/lib/__tests__/pluginWorkloadSdkCapability.test.ts
index ee0d81648..58cf3c749 100644
--- a/desktop-app/ui/src/lib/__tests__/pluginWorkloadSdkCapability.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/pluginWorkloadSdkCapability.test.ts
@@ -53,4 +53,35 @@ describe('describePluginWorkloadSdkCapability', () => {
expect(result?.tone).toBe('neutral')
expect(result?.title).toBe('Plugin Workload SDK capability is disabled')
})
+
+ it('distinguishes awaiting policy from a disabled feature', () => {
+ expect(
+ describePluginWorkloadSdkCapability({
+ state: 'awaiting_policy',
+ promptBridge: true,
+ clientNotifications: false,
+ validatedAt: null,
+ message: 'Grant required',
+ })
+ ).toEqual({
+ label: 'SDK: awaiting policy',
+ tone: 'neutral',
+ title: 'Grant required',
+ })
+ })
+
+ it('preserves a degraded diagnostic instead of labeling the capability disabled', () => {
+ expect(
+ describePluginWorkloadSdkCapability({
+ state: 'degraded',
+ promptBridge: true,
+ clientNotifications: false,
+ validatedAt: null,
+ })
+ ).toEqual({
+ label: 'SDK: degraded',
+ tone: 'neutral',
+ title: 'Plugin Workload SDK capability is degraded',
+ })
+ })
})
diff --git a/desktop-app/ui/src/lib/workflowStatus.ts b/desktop-app/ui/src/lib/workflowStatus.ts
index 04db325d7..68044c3c4 100644
--- a/desktop-app/ui/src/lib/workflowStatus.ts
+++ b/desktop-app/ui/src/lib/workflowStatus.ts
@@ -29,6 +29,20 @@ export function describePluginWorkloadSdkCapability(
title: `Plugin Workload SDK capability validated (${families.join(', ') || 'none'})`,
}
}
+ if (capability.state === 'awaiting_policy') {
+ return {
+ label: 'SDK: awaiting policy',
+ tone: 'neutral',
+ title: capability.message || 'Plugin Workload SDK is awaiting operator policy',
+ }
+ }
+ if (capability.state === 'degraded') {
+ return {
+ label: 'SDK: degraded',
+ tone: 'neutral',
+ title: capability.message || 'Plugin Workload SDK capability is degraded',
+ }
+ }
return {
label: 'SDK: disabled',
tone: 'neutral',
diff --git a/docs/architecture/platform-topology.md b/docs/architecture/platform-topology.md
index edc13dc90..d120a5739 100644
--- a/docs/architecture/platform-topology.md
+++ b/docs/architecture/platform-topology.md
@@ -801,7 +801,7 @@ flowchart TD
#### 11.2.5 L3-Egress — External Runtime Egress
-**What it does**: Opens explicit public egress paths declared by runtime configuration. Kubernetes NetworkPolicy cannot enforce HTTP hostnames at L7, so the current architecture resolves declared hostnames to public IPv4 CIDRs and writes L3/L3-runtime egress policies that allow only those CIDRs on ports 443 and 80.
+**What it does**: Opens explicit public egress paths declared by runtime configuration. Kubernetes NetworkPolicy cannot enforce HTTP hostnames at L7, so the current architecture resolves declared hostnames to public IPv4 CIDRs and writes L3/L3-runtime egress policies that allow only those CIDRs on HTTPS port 443. Plain HTTP is intentionally not permitted because it can expose credentials or prompt content.
**Applied to**:
@@ -1026,7 +1026,7 @@ See [§7.2 Full Deployment Flow](#72-full-deployment-flow) for the complete merm
| Feature | Description |
| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| ~~Egress policies per MCP server~~ | **Specified** — `bindings[].to: external` with `dns`/`cidr` → McpServer CRD `spec.egressBindings[]` → HCC L3-egress NetworkPolicies |
+| ~~Egress policies per MCP server~~ | **Specified** — `bindings[].to: external` with `dns`/`cidr` → McpServer CRD `spec.egressBindings[]` → HCC L3-egress NetworkPolicies |
| Per-recipe ResourceQuotas | CPU/memory quotas in sandbox-recipes |
| WRO detection pipeline | Workflow Recipe Optimization (design not published in this repo) |
| Namespace-per-context sandbox | Stronger isolation if scale requires it |
@@ -1041,21 +1041,21 @@ See [§7.2 Full Deployment Flow](#72-full-deployment-flow) for the complete merm
| ----------------------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Discovery API (HCC REST) | **Implemented** | `host-context-controller/src/server.ts` |
| MCP Server Reconciler | **Implemented** | `host-context-controller/src/reconciler.ts` |
-| NetworkPolicy Reconciler (L0-L3 + L3-egress) | **Implemented** | `host-context-controller/src/networkPolicyReconciler.ts` |
-| L0 deny-all (Ingress + Egress, 4 NS) | **Implemented** | `ensureDefaultDeny()` — dynamic, HCC's 4 runtime namespaces (mcp-host is static) |
-| L1 infrastructure (DNS, HCC API, K8s API) | **Implemented** | `ensureInfrastructurePolicies()` — 10 policies (DNS x 4, HCC/K8s API x 3; sandbox-ui is DNS-only) |
-| L1 allow-api ingress | **Implemented** | `ensureAllowContextMapperApi()` — `from` bug fixed |
-| L2 context-allow (bidirectional) | **Implemented** | `reconcileContext()` — ingress in mcp-server + egress in mcp-host |
-| L3 binding-scoped NetworkPolicies | **Implemented** | `bindingPolicyReconciler.ts` — wired to HCC McpServer watch loop |
-| L3-egress external-scoped | **Implemented** | `reconcileExternalEgress()` — CIDR + DNS resolution |
-| Prometheus metrics (HCC + WRC) | **Implemented** | `host-context-controller/src/metrics.ts`, `workflow-recipes/src/metrics.ts` |
+| NetworkPolicy Reconciler (L0-L3 + L3-egress) | **Implemented** | `host-context-controller/src/networkPolicyReconciler.ts` |
+| L0 deny-all (Ingress + Egress, 4 NS) | **Implemented** | `ensureDefaultDeny()` — dynamic, HCC's 4 runtime namespaces (mcp-host is static) |
+| L1 infrastructure (DNS, HCC API, K8s API) | **Implemented** | `ensureInfrastructurePolicies()` — 10 policies (DNS x 4, HCC/K8s API x 3; sandbox-ui is DNS-only) |
+| L1 allow-api ingress | **Implemented** | `ensureAllowContextMapperApi()` — `from` bug fixed |
+| L2 context-allow (bidirectional) | **Implemented** | `reconcileContext()` — ingress in mcp-server + egress in mcp-host |
+| L3 binding-scoped NetworkPolicies | **Implemented** | `bindingPolicyReconciler.ts` — wired to HCC McpServer watch loop |
+| L3-egress external-scoped | **Implemented** | `reconcileExternalEgress()` — CIDR + DNS resolution |
+| Prometheus metrics (HCC + WRC) | **Implemented** | `host-context-controller/src/metrics.ts`, `workflow-recipes/src/metrics.ts` |
| RPC Proxy service + NetworkPolicy | **Implemented** | `rpc-proxy/src/` + `deploy/base/rpc-proxy/networkpolicies.yaml` |
| WRC reconciler pipeline | **Implemented** | `workflow-recipes/src/reconciler/` — ships as the standalone `workflow-recipes` Deployment |
| Host Reconciler | **Implemented** | `host-context-controller/src/hostReconciler.ts` |
-| WorkflowRecipePolicy CRD | **Implemented** | Blocking enforcement in reconciler step 2.5 |
-| Namespace splitting (non-MCP → sandbox-recipes) | **Implemented** | `resolveWorkloadNamespace()` + finalizer pattern + cross-namespace L3 |
-| ValidatingAdmissionWebhook | **Deferred** | Requires TLS certificates (cert-manager) |
-| Per-context auth (TokenReview) | **Deferred** | Requires ServiceAccount projected token infrastructure |
+| WorkflowRecipePolicy CRD | **Implemented** | Blocking enforcement in reconciler step 2.5 |
+| Namespace splitting (non-MCP → sandbox-recipes) | **Implemented** | `resolveWorkloadNamespace()` + finalizer pattern + cross-namespace L3 |
+| ValidatingAdmissionWebhook | **Deferred** | Requires TLS certificates (cert-manager) |
+| Per-context auth (TokenReview) | **Deferred** | Requires ServiceAccount projected token infrastructure |
| ~~ReadinessGate `clerum.io/network-isolated`~~ | **Replaced** by Option C (§11.4) | Pre-deploy annotation handshake closes vulnerability window without pod patching |
| Pre-deploy annotation handshake (Option C) | **Implemented** | `mcpDelegation.ts:preDeployMcpServers()` + `waitForNetworkReady()` — Steps 7b/7c in reconciler pipeline |
| Sanitization Gate | **Partially implemented** — see §5.1 | `managed: true` servers only (WRC's HTTP/SSE recipe servers are `managed: false` and skip it). `sanitizeCrdSpec()` (coerces/strips, never rejects; resource clamp is unit-naive) + `validateSecret()` and `classifyPluginImage()` (the only blocking checks; image allowlist is audit-only by default) in `host-context-controller/src/reconciler.ts` |
diff --git a/docs/crds/workflowrecipe.md b/docs/crds/workflowrecipe.md
index 52d902047..6524194c7 100644
--- a/docs/crds/workflowrecipe.md
+++ b/docs/crds/workflowrecipe.md
@@ -1033,13 +1033,13 @@ Resolution happens at reconciliation time only:
The **default LLM configuration** for every agentic (`instruction`) step. Steps may override `model` / `provider` via `steps[].agent`. The reconciler resolves the recipe's `mcp-host` agent from `spec.agent` first, then falls back to the first step declaring a _complete_ agent.
-| Field | Type | Required | Description |
-| --------------------- | ------ | -------- | ---------------------------------------------------------------------------------------------------------------- |
-| `model` | string | No\* | LLM model name (e.g. `gpt-4o`, `claude-3-opus`). |
-| `provider` | string | No\* | Enum: `openai`, `claude`, `zai`, `bailian`. |
-| `secretRef.name` | string | No | Secret holding the API key. |
-| `secretRef.namespace` | string | No | Secret namespace. |
-| `soulRef.storageRef` | object | No | `SOUL.md` in object storage: `bucket`, `key`, `provider` (`s3`\|`gcs`\|`spaces`\|`minio`), `region`, `endpoint`. |
+| Field | Type | Required | Description |
+| --------------------- | ------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `model` | string | No\* | LLM model name (e.g. `gpt-4o`, `claude-3-opus`). |
+| `provider` | string | No\* | Enum: `openai`, `claude`, `zai`, `bailian`, `vertex`, `bedrock`, `openrouter`, `gemini`, `deepseek`, `groq`, `together`, `fireworks`, `mistral`, `xai`, `cerebras`, `deepinfra`, `perplexity`, `moonshot`, `nebius`, `novita`, `azure`. |
+| `secretRef.name` | string | No | Secret holding the API key. |
+| `secretRef.namespace` | string | No | Secret namespace. |
+| `soulRef.storageRef` | object | No | `SOUL.md` in object storage: `bucket`, `key`, `provider` (`s3`\|`gcs`\|`spaces`\|`minio`), `region`, `endpoint`. |
\* The schema marks no field required, but the reconciler treats an agent as usable only when **both** `provider` and `model` are set. A half-declared `spec.agent` behaves as if absent.
@@ -1058,7 +1058,7 @@ spec:
**What gets rejected**
- **CEL R1** — `agent requires non-empty workflow steps or spec.pluginWorkloadSdk.promptBridge`. An agent remains invalid for an ordinary workloads-only recipe, but a stepless `promptBridge` recipe uses `spec.agent` as the eager mcp-host bootstrap binding rather than as a workflow agent.
-- A `provider` outside the four-value enum.
+- A `provider` outside the canonical provider enum.
- An `instruction` step with no resolvable agent: _"step requires an agent configuration"_.
### 3.10 MCP Servers (`spec.mcpServers`)
@@ -1122,10 +1122,10 @@ spec:
The recipe-wide egress intent for the **workflow runtime** (snippet-runner and custom-coordinator pods). It is the shared allowlist that per-step snippet HTTP capabilities must be a subset of. Distinct from `workloads[].egressBindings` (§3.2), which governs long-lived workload pods.
-| Field | Type | Required | Description |
-| ------------------- | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `http.egressClass` | string | No | Enum `exact-host` (default) or `public-web`. `public-web` is an explicit opt-in for public TCP 80/443 with private, metadata, link-local and reserved ranges blocked. |
-| `http.allowedHosts` | string[] | No | Max 20, each max 253, pattern `^[a-z0-9][a-z0-9.-]*[a-z0-9]$`. |
+| Field | Type | Required | Description |
+| ------------------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `http.egressClass` | string | No | Enum `exact-host` (default) or `public-web`. `public-web` is an explicit opt-in for public TCP 443 with private, metadata, link-local and reserved ranges blocked. |
+| `http.allowedHosts` | string[] | No | Max 20, each max 253, pattern `^[a-z0-9][a-z0-9.-]*[a-z0-9]$`. |
```yaml
spec:
@@ -2875,7 +2875,7 @@ The spec-level rules in the shipped CRD are numbered in comments (R1-R18, W1, O1
| ID | Message |
| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| R1 | `agent requires workflow steps or spec.pluginWorkloadSdk.promptBridge` |
+| R1 | `agent requires workflow steps or spec.pluginWorkloadSdk.promptBridge` |
| R1a | `spec.pluginWorkloadSdk without workflow steps cannot define triggers, scheduling, or coordinatorImage` |
| R2 | `recipe must define at least workloads or steps` |
| R3 | `duplicate step IDs are not allowed` |
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 0f3f47cd7..5354b4fbc 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.226",
+ "version": "0.1.227",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.226",
+ "version": "0.1.227",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 2f171f034..94e47e66f 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.226",
+ "version": "0.1.227",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/core/types.ts b/mcp-host/src/core/types.ts
index 1850a31c1..199aa4f1e 100644
--- a/mcp-host/src/core/types.ts
+++ b/mcp-host/src/core/types.ts
@@ -126,6 +126,8 @@ export interface CompletionRequest {
export interface CompletionResponse {
content: string
usage: TokenUsage
+ /** True only when the provider response carried authoritative token counters. */
+ usage_reported?: boolean
finish_reason: FinishReason
}
@@ -150,6 +152,8 @@ export interface ToolCompletionResponse {
content: string | null
tool_calls: ToolCall[] | null
usage: TokenUsage
+ /** True only when the provider response carried authoritative token counters. */
+ usage_reported?: boolean
finish_reason: FinishReason
}
diff --git a/mcp-host/src/llm/__tests__/openai.singleTurn.test.ts b/mcp-host/src/llm/__tests__/openai.singleTurn.test.ts
index aa63dbbaf..37f1d0249 100644
--- a/mcp-host/src/llm/__tests__/openai.singleTurn.test.ts
+++ b/mcp-host/src/llm/__tests__/openai.singleTurn.test.ts
@@ -323,5 +323,19 @@ describe('OpenAI token usage mapping', () => {
output_tokens: 18,
total_tokens: 60,
})
+ expect(result.usage_reported).toBe(true)
+ })
+
+ it('marks missing provider usage as non-authoritative instead of exact zero', async () => {
+ const mockClient = createMockOpenAIClient()
+ mockClient.chat.completions.create.mockResolvedValue({
+ choices: [{ message: { role: 'assistant', content: 'Hi' }, finish_reason: 'stop' }],
+ })
+ const provider = new OpenAIProvider(mockClient as any, 'gpt-4o')
+
+ const result = await provider.completeSingleTurn([{ role: 'user', content: 'Hi' }])
+
+ expect(result.usage_reported).toBe(false)
+ expect(result.usage).toEqual({ input_tokens: 0, output_tokens: 0, total_tokens: 0 })
})
})
diff --git a/mcp-host/src/llm/claude.ts b/mcp-host/src/llm/claude.ts
index 1a06cf4d5..4385cd200 100644
--- a/mcp-host/src/llm/claude.ts
+++ b/mcp-host/src/llm/claude.ts
@@ -99,13 +99,21 @@ export class ClaudeProvider implements SingleTurnProvider {
.map(b => b.text)
.join('')
+ const usage = response.usage
+ const usageReported =
+ usage != null &&
+ Number.isInteger(usage.input_tokens) &&
+ usage.input_tokens >= 0 &&
+ Number.isInteger(usage.output_tokens) &&
+ usage.output_tokens >= 0
return {
content: textContent,
usage: {
- input_tokens: response.usage.input_tokens,
- output_tokens: response.usage.output_tokens,
- total_tokens: response.usage.input_tokens + response.usage.output_tokens,
+ input_tokens: usage?.input_tokens ?? 0,
+ output_tokens: usage?.output_tokens ?? 0,
+ total_tokens: (usage?.input_tokens ?? 0) + (usage?.output_tokens ?? 0),
},
+ usage_reported: usageReported,
finish_reason: this.mapStopReason(response.stop_reason),
}
}
diff --git a/mcp-host/src/llm/drivers/bedrockConverse.ts b/mcp-host/src/llm/drivers/bedrockConverse.ts
index 406aa54ec..581948cf7 100644
--- a/mcp-host/src/llm/drivers/bedrockConverse.ts
+++ b/mcp-host/src/llm/drivers/bedrockConverse.ts
@@ -111,6 +111,7 @@ export class BedrockConverseDriver implements SingleTurnProvider {
return {
content: extractText(response) ?? '',
usage: mapUsage(response),
+ usage_reported: hasAuthoritativeUsage(response),
finish_reason: mapStopReason(response.stopReason),
}
}
@@ -262,6 +263,21 @@ function mapUsage(response: BedrockConverseResponse): CompletionResponse['usage'
}
}
+function hasAuthoritativeUsage(response: BedrockConverseResponse): boolean {
+ const usage = response.usage
+ const input = usage?.inputTokens
+ const output = usage?.outputTokens
+ return (
+ usage != null &&
+ typeof input === 'number' &&
+ Number.isInteger(input) &&
+ input >= 0 &&
+ typeof output === 'number' &&
+ Number.isInteger(output) &&
+ output >= 0
+ )
+}
+
function mapStopReason(reason: string | undefined): FinishReason {
switch (reason) {
case 'end_turn':
diff --git a/mcp-host/src/llm/drivers/googleGenerative.ts b/mcp-host/src/llm/drivers/googleGenerative.ts
index e93fc11e5..943422b09 100644
--- a/mcp-host/src/llm/drivers/googleGenerative.ts
+++ b/mcp-host/src/llm/drivers/googleGenerative.ts
@@ -109,6 +109,7 @@ export class GoogleGenerativeDriver implements SingleTurnProvider {
return {
content: textContent,
usage: mapUsage(response),
+ usage_reported: hasAuthoritativeUsage(response),
finish_reason: mapFinishReason(response.candidates?.[0]?.finishReason, parts),
}
}
@@ -240,6 +241,21 @@ function mapUsage(response: GeminiResponse): CompletionResponse['usage'] {
}
}
+function hasAuthoritativeUsage(response: GeminiResponse): boolean {
+ const usage = response.usageMetadata
+ const input = usage?.promptTokenCount
+ const output = usage?.candidatesTokenCount
+ return (
+ usage != null &&
+ typeof input === 'number' &&
+ Number.isInteger(input) &&
+ input >= 0 &&
+ typeof output === 'number' &&
+ Number.isInteger(output) &&
+ output >= 0
+ )
+}
+
function mapFinishReason(reason: string | undefined, parts: GeminiPart[]): FinishReason {
if (parts.some(p => p.functionCall)) return FinishReason.ToolUse
switch (reason) {
diff --git a/mcp-host/src/llm/openai.ts b/mcp-host/src/llm/openai.ts
index c19e67f08..7a3fe1864 100644
--- a/mcp-host/src/llm/openai.ts
+++ b/mcp-host/src/llm/openai.ts
@@ -81,6 +81,12 @@ export class OpenAIProvider implements SingleTurnProvider {
)
const choice = response.choices[0]
+ const usageReported =
+ response.usage != null &&
+ Number.isInteger(response.usage.prompt_tokens) &&
+ response.usage.prompt_tokens >= 0 &&
+ Number.isInteger(response.usage.completion_tokens) &&
+ response.usage.completion_tokens >= 0
return {
content: choice.message.content ?? '',
usage: {
@@ -88,6 +94,7 @@ export class OpenAIProvider implements SingleTurnProvider {
output_tokens: response.usage?.completion_tokens ?? 0,
total_tokens: response.usage?.total_tokens ?? 0,
},
+ usage_reported: usageReported,
finish_reason: this.mapFinishReason(choice.finish_reason),
}
}
@@ -141,6 +148,12 @@ export class OpenAIProvider implements SingleTurnProvider {
arguments: this.parseArguments(tc.function.arguments),
})) ?? null
+ const usageReported =
+ response.usage != null &&
+ Number.isInteger(response.usage.prompt_tokens) &&
+ response.usage.prompt_tokens >= 0 &&
+ Number.isInteger(response.usage.completion_tokens) &&
+ response.usage.completion_tokens >= 0
return {
content: message.content,
tool_calls: toolCalls && toolCalls.length > 0 ? toolCalls : null,
@@ -149,6 +162,7 @@ export class OpenAIProvider implements SingleTurnProvider {
output_tokens: response.usage?.completion_tokens ?? 0,
total_tokens: response.usage?.total_tokens ?? 0,
},
+ usage_reported: usageReported,
finish_reason: this.mapFinishReason(choice.finish_reason),
}
}
diff --git a/mcp-host/src/pluginWorkloadSdk/domain/errors.ts b/mcp-host/src/pluginWorkloadSdk/domain/errors.ts
index 38b390b9f..7107dede2 100644
--- a/mcp-host/src/pluginWorkloadSdk/domain/errors.ts
+++ b/mcp-host/src/pluginWorkloadSdk/domain/errors.ts
@@ -35,9 +35,24 @@ export const PLUGIN_WORKLOAD_ERROR_REASONS = [
'configuration',
'timeout',
'network',
+ 'outcome_unknown',
] as const
export type PluginWorkloadErrorReason = (typeof PLUGIN_WORKLOAD_ERROR_REASONS)[number]
+export type PluginWorkloadProviderAttemptContext = {
+ providerAttemptId: string
+ providerAttemptIndex: number
+ target: {
+ targetRef: string
+ provider: string
+ model: string
+ credentialSlot: string
+ }
+ attemptCount: number
+ fallbackUsed: boolean
+ llmSecretName: string
+}
+
const ERROR_HTTP_STATUS: Record<PluginWorkloadErrorCode, number> = {
capability_not_declared: 403,
caller_not_allowed: 403,
@@ -63,12 +78,18 @@ export class PluginWorkloadError extends Error {
readonly retryable: boolean
readonly httpStatus: number
readonly reason?: PluginWorkloadErrorReason
+ /** True when the provider may already have accepted or returned a call. */
+ readonly providerMayHaveExecuted: boolean
+ /** Internal immutable context needed to persist an unknown spend receipt. */
+ readonly providerAttempt?: PluginWorkloadProviderAttemptContext
constructor(
code: PluginWorkloadErrorCode,
message: string,
retryable = false,
- reason?: PluginWorkloadErrorReason
+ reason?: PluginWorkloadErrorReason,
+ providerMayHaveExecuted = false,
+ providerAttempt?: PluginWorkloadProviderAttemptContext
) {
super(message)
this.name = 'PluginWorkloadError'
@@ -76,6 +97,8 @@ export class PluginWorkloadError extends Error {
this.retryable = retryable
this.httpStatus = ERROR_HTTP_STATUS[code]
this.reason = reason
+ this.providerMayHaveExecuted = providerMayHaveExecuted
+ this.providerAttempt = providerAttempt
}
toBody(): {
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts
index 94bd6c191..4747f4561 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts
@@ -372,6 +372,50 @@ describe('PluginWorkloadSdkControlApiClient', () => {
).rejects.toMatchObject({ code: 'provider_unavailable', retryable: true })
})
+ it('finalizes one provider attempt with an idempotent exact usage receipt', async () => {
+ const fetchImpl = vi.fn().mockResolvedValue(
+ jsonResponse(201, {
+ invocationId: 'inv-1',
+ providerAttemptId: 'attempt-1',
+ status: 'complete',
+ outcome: 'exact',
+ idempotent: false,
+ usageAccepted: true,
+ })
+ )
+ const client = makeClient(fetchImpl as unknown as typeof fetch)
+ const result = await client.finalizePromptBridge({
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'r1',
+ invocationId: 'inv-1',
+ attemptGeneration: 1,
+ providerAttemptId: 'attempt-1',
+ providerAttemptIndex: 1,
+ status: 'complete',
+ reason: 'provider_completed',
+ target,
+ usage: {
+ llmSecretName: 'zai-api-key',
+ callerRef: 'api',
+ fallbackUsed: false,
+ attemptCount: 1,
+ inputTokens: 3,
+ outputTokens: 4,
+ },
+ })
+ expect(result).toMatchObject({ outcome: 'exact', usageAccepted: true })
+ const [url, init] = fetchImpl.mock.calls[0] as [string, RequestInit]
+ expect(url).toBe(
+ 'http://gateway:8092/api/v1/mcp-host/plugin-workload-sdk/invocations/inv-1/finalize'
+ )
+ expect(JSON.parse(String(init.body))).toMatchObject({
+ invocationId: 'inv-1',
+ providerAttemptId: 'attempt-1',
+ status: 'complete',
+ usage: { inputTokens: 3, outputTokens: 4 },
+ })
+ })
+
it('submitClientNotification maps event_type_not_allowed', async () => {
const fetchImpl = vi
.fn()
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
index 74b47b56c..6ae6da4ab 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
@@ -108,6 +108,15 @@ export interface ReissuedPromptBridgeCredentialTicket {
expiresInSeconds: number
}
+export interface FinalizePromptBridgeResponse {
+ invocationId: string
+ providerAttemptId: string
+ status: 'complete' | 'provider_unavailable'
+ outcome: 'exact' | 'unknown'
+ idempotent: boolean
+ usageAccepted: boolean
+}
+
export interface SubmitClientNotificationResponse {
notificationId: string
replay: boolean
@@ -202,6 +211,19 @@ function isReissuedPromptBridgeCredentialTicket(
)
}
+function isFinalizePromptBridgeResponse(value: unknown): value is FinalizePromptBridgeResponse {
+ if (typeof value !== 'object' || value === null) return false
+ const result = value as Record<string, unknown>
+ return (
+ typeof result.invocationId === 'string' &&
+ typeof result.providerAttemptId === 'string' &&
+ (result.status === 'complete' || result.status === 'provider_unavailable') &&
+ (result.outcome === 'exact' || result.outcome === 'unknown') &&
+ typeof result.idempotent === 'boolean' &&
+ typeof result.usageAccepted === 'boolean'
+ )
+}
+
function isPromptBridgeTarget(value: unknown): value is PromptBridgeTarget {
if (typeof value !== 'object' || value === null) return false
const target = value as Record<string, unknown>
@@ -678,15 +700,77 @@ export class PluginWorkloadSdkControlApiClient {
status: 'complete' | 'failed' | 'provider_unavailable',
attemptGeneration: number
): Promise<void> {
- // A completion is not safe to return until control-api has accepted the
- // generation-fenced terminal transition. Swallowing this error would let
- // the caller observe a result whose audit/usage lease is still active.
+ // The handler owns the conservative policy for a lost ACK: it preserves a
+ // real provider result, reports provider_unavailable when the physical
+ // receipt is unknown, and lets the idempotent caller retry this operation.
await this.post(
`/api/v1/mcp-host/plugin-workload-sdk/invocations/${encodeURIComponent(invocationId)}/status`,
{ recipeNamespace, recipeName, status, attemptGeneration }
)
}
+ /**
+ * Atomically closes one SDK-only provider attempt and records exact or
+ * unknown spend. This replaces separate status + usage calls for the
+ * stepless runtime; the route is idempotent on providerAttemptId.
+ */
+ async finalizePromptBridge(body: {
+ recipeNamespace: string
+ recipeName: string
+ invocationId: string
+ attemptGeneration: number
+ providerAttemptId: string
+ providerAttemptIndex: number
+ status: 'complete' | 'provider_unavailable'
+ reason: string
+ target: PromptBridgeTarget
+ usage?: {
+ llmSecretName: string
+ callerRef: string
+ fallbackUsed: boolean
+ attemptCount: number
+ inputTokens: number
+ outputTokens: number
+ }
+ }): Promise<FinalizePromptBridgeResponse> {
+ const result = await this.post(
+ `/api/v1/mcp-host/plugin-workload-sdk/invocations/${encodeURIComponent(body.invocationId)}/finalize`,
+ {
+ recipeNamespace: body.recipeNamespace,
+ recipeName: body.recipeName,
+ invocationId: body.invocationId,
+ attemptGeneration: body.attemptGeneration,
+ providerAttemptId: body.providerAttemptId,
+ providerAttemptIndex: body.providerAttemptIndex,
+ status: body.status,
+ reason: body.reason,
+ target: body.target,
+ ...(body.usage ? { usage: body.usage } : {}),
+ }
+ )
+ if (!isFinalizePromptBridgeResponse(result)) {
+ throw new PluginWorkloadError(
+ 'provider_unavailable',
+ 'control-api returned an unexpected response shape for promptBridge finalization',
+ true
+ )
+ }
+ if (
+ result.invocationId !== body.invocationId ||
+ result.providerAttemptId !== body.providerAttemptId ||
+ result.status !== body.status
+ ) {
+ throw new PluginWorkloadError(
+ 'provider_unavailable',
+ 'control-api returned a finalization for a different provider attempt',
+ false,
+ 'outcome_unknown',
+ true
+ )
+ }
+ return result
+ }
+
async submitClientNotification(body: {
recipeNamespace: string
recipeName: string
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts
index bdec0b8a6..7748387e1 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts
@@ -50,6 +50,7 @@ function makeDeps(
report?: ReturnType<typeof vi.fn>
bootstrap?: () => { provider: string; model: string } | null
onUsage?: (usage: any) => void
+ finalize?: ReturnType<typeof vi.fn>
} = {}
) {
const authorize = overrides.authorize ?? vi.fn().mockResolvedValue(authorization())
@@ -79,6 +80,7 @@ function makeDeps(
recipeName: 'r1',
promptTimeoutMs: 120_000,
...(overrides.bootstrap ? { getBootstrapTarget: overrides.bootstrap } : {}),
+ ...(overrides.finalize ? { finalizePromptBridge: overrides.finalize } : {}),
onUsage: overrides.onUsage,
})
return { handler, authorize, complete, report }
@@ -198,6 +200,44 @@ describe('PromptBridgeHandler', () => {
)
})
+ it('preserves metering when the logical terminal acknowledgement is unavailable', async () => {
+ const report = vi.fn().mockRejectedValue(new Error('control-api unavailable'))
+ const onUsage = vi.fn()
+ const { handler, complete } = makeDeps({ report, onUsage })
+
+ const result = await handler.handle(validBody, 'api')
+
+ expect(result).toMatchObject({ invocationId: 'inv-1', content: 'summary text' })
+ expect(complete).toHaveBeenCalledOnce()
+ expect(report).toHaveBeenCalledWith('inv-1', 'sandbox-recipes', 'r1', 'complete', 1)
+ // The provider-attempt receipt is authoritative for usage binding, so a
+ // lost logical ACK must not silently discard the billable usage event.
+ expect(onUsage).toHaveBeenCalledOnce()
+ })
+
+ it('closes the invocation as provider_unavailable when the physical receipt is unknown', async () => {
+ const report = vi.fn().mockResolvedValue(undefined)
+ const complete = vi.fn().mockResolvedValue({
+ model: fallback.model,
+ servedTarget: fallback,
+ fallbackUsed: true,
+ attemptCount: 2,
+ llmSecretName: 'provider-secret',
+ content: 'summary text',
+ usage: { inputTokens: 10, outputTokens: 5 },
+ finishReason: 'complete',
+ providerAttemptAcknowledged: false,
+ })
+ const onUsage = vi.fn()
+ const { handler } = makeDeps({ complete, report, onUsage })
+
+ const result = await handler.handle(validBody, 'api')
+
+ expect(result).toMatchObject({ invocationId: 'inv-1', content: 'summary text' })
+ expect(report).toHaveBeenCalledWith('inv-1', 'sandbox-recipes', 'r1', 'provider_unavailable', 1)
+ expect(onUsage).not.toHaveBeenCalled()
+ })
+
it('does not repeat a provider charge for an existing non-failed replay', async () => {
const authorize = vi
.fn()
@@ -236,4 +276,140 @@ describe('PromptBridgeHandler', () => {
})
expect(report).toHaveBeenCalledWith('inv-1', 'sandbox-recipes', 'r1', 'provider_unavailable', 1)
})
+
+ it('preserves the original provider error when the failure audit acknowledgement fails', async () => {
+ const complete = vi
+ .fn()
+ .mockRejectedValue(new PluginWorkloadError('provider_unavailable', 'provider failed', false))
+ const report = vi.fn().mockRejectedValue(new Error('control-api unavailable'))
+ const { handler } = makeDeps({ complete, report })
+
+ await expect(handler.handle(validBody, 'api')).rejects.toMatchObject({
+ code: 'provider_unavailable',
+ message: 'provider failed',
+ })
+ })
+
+ it('uses the SDK-only finalizer instead of separate status and usage reporting', async () => {
+ const finalize = vi.fn().mockResolvedValue({
+ invocationId: 'inv-1',
+ providerAttemptId: 'attempt-1',
+ status: 'complete',
+ outcome: 'exact',
+ idempotent: false,
+ usageAccepted: true,
+ })
+ const onUsage = vi.fn()
+ const complete = vi.fn().mockResolvedValue({
+ model: fallback.model,
+ servedTarget: fallback,
+ fallbackUsed: true,
+ attemptCount: 2,
+ llmSecretName: 'provider-secret',
+ providerAttemptId: 'attempt-1',
+ providerAttemptIndex: 2,
+ content: 'summary text',
+ usage: { inputTokens: 10, outputTokens: 5 },
+ finishReason: 'complete',
+ })
+ const { handler, report } = makeDeps({ complete, finalize, onUsage })
+
+ await expect(handler.handle(validBody, 'api')).resolves.toMatchObject({
+ invocationId: 'inv-1',
+ content: 'summary text',
+ })
+ expect(finalize).toHaveBeenCalledWith(
+ expect.objectContaining({
+ invocationId: 'inv-1',
+ providerAttemptId: 'attempt-1',
+ providerAttemptIndex: 2,
+ status: 'complete',
+ target: fallback,
+ usage: expect.objectContaining({ inputTokens: 10, outputTokens: 5 }),
+ })
+ )
+ expect(report).not.toHaveBeenCalled()
+ expect(onUsage).not.toHaveBeenCalled()
+ })
+
+ it('records an unknown spend receipt before returning an ambiguous provider error', async () => {
+ const finalize = vi.fn().mockResolvedValue({
+ invocationId: 'inv-1',
+ providerAttemptId: 'attempt-1',
+ status: 'provider_unavailable',
+ outcome: 'unknown',
+ idempotent: false,
+ usageAccepted: false,
+ })
+ const complete = vi.fn().mockRejectedValue(
+ new PluginWorkloadError(
+ 'provider_unavailable',
+ 'provider outcome unknown',
+ false,
+ 'outcome_unknown',
+ true,
+ {
+ providerAttemptId: 'attempt-1',
+ providerAttemptIndex: 1,
+ target: primary,
+ attemptCount: 1,
+ fallbackUsed: false,
+ llmSecretName: 'provider-secret',
+ }
+ )
+ )
+ const { handler, report } = makeDeps({ complete, finalize })
+
+ await expect(handler.handle(validBody, 'api')).rejects.toMatchObject({
+ code: 'provider_unavailable',
+ reason: 'outcome_unknown',
+ })
+ expect(finalize).toHaveBeenCalledWith(
+ expect.objectContaining({
+ status: 'provider_unavailable',
+ reason: 'outcome_unknown',
+ target: primary,
+ })
+ )
+ expect(report).not.toHaveBeenCalled()
+ })
+
+ it('reconciles an exact-finalization failure into a durable unknown receipt', async () => {
+ const finalize = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('finalization transaction lost'))
+ .mockResolvedValueOnce({
+ invocationId: 'inv-1',
+ providerAttemptId: 'attempt-1',
+ status: 'provider_unavailable',
+ outcome: 'unknown',
+ idempotent: false,
+ usageAccepted: false,
+ })
+ const complete = vi.fn().mockResolvedValue({
+ model: fallback.model,
+ servedTarget: fallback,
+ fallbackUsed: true,
+ attemptCount: 2,
+ llmSecretName: 'provider-secret',
+ providerAttemptId: 'attempt-1',
+ providerAttemptIndex: 2,
+ content: 'summary text',
+ usage: { inputTokens: 10, outputTokens: 5 },
+ finishReason: 'complete',
+ })
+ const { handler, report } = makeDeps({ complete, finalize })
+
+ await expect(handler.handle(validBody, 'api')).rejects.toMatchObject({
+ code: 'provider_unavailable',
+ reason: 'outcome_unknown',
+ })
+ expect(finalize).toHaveBeenCalledTimes(2)
+ expect(finalize).toHaveBeenNthCalledWith(1, expect.objectContaining({ status: 'complete' }))
+ expect(finalize).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({ status: 'provider_unavailable', reason: 'outcome_unknown' })
+ )
+ expect(report).not.toHaveBeenCalled()
+ })
})
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts
index 0ec68b901..99f9c03fe 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts
@@ -1,5 +1,5 @@
import { randomUUID } from 'crypto'
-import { PluginWorkloadError } from '../domain/errors'
+import { PluginWorkloadError, type PluginWorkloadProviderAttemptContext } from '../domain/errors'
import {
DEFAULT_IDEMPOTENCY_KEY_PATTERN,
DEFAULT_MAX_REQUEST_CONTENT_BYTES,
@@ -26,7 +26,8 @@ import type { LlmBridge } from './llmBridge'
* 1. Validate input (purpose enum, idempotency key pattern, content cap).
* 2. Authorize through control-api via the anti-corruption layer.
* 3. Call the co-located LLM bridge (provider bound to this mcp-host).
- * 4. Report completion status back to the audit trail (best-effort).
+ * 4. Report physical and logical completion status back to the audit trail
+ * (idempotent and best-effort at the transport boundary).
* 5. Return PromptBridgeResult — or a PluginWorkloadError (spec §15).
*
* v1 invariant: inference-only. No tools, no conversational session.
@@ -36,6 +37,39 @@ const IDEMPOTENCY_KEY_RE = new RegExp(DEFAULT_IDEMPOTENCY_KEY_PATTERN)
const PURPOSE_SET = new Set<string>(PLUGIN_WORKLOAD_SDK_PURPOSES)
const MAX_METADATA_BYTES = 16 * 1024
+/**
+ * A provider response is already potentially billable when this acknowledgement
+ * is sent. Preserve that response if the audit transport is unavailable; the
+ * generation fence and maintenance sweep prevent the unfinished ledger row
+ * from being retried as a fresh provider call. Usage is emitted once the
+ * physical provider receipt is confirmed, even if the logical invocation ACK
+ * must be retried, because usage binding is anchored to that immutable receipt.
+ */
+async function reportInvocationStatusBestEffort(
+ client: PluginWorkloadSdkControlApiClient,
+ invocationId: string,
+ recipeNamespace: string,
+ recipeName: string,
+ status: 'complete' | 'failed' | 'provider_unavailable',
+ attemptGeneration: number
+): Promise<boolean> {
+ try {
+ await client.reportInvocationStatus(
+ invocationId,
+ recipeNamespace,
+ recipeName,
+ status,
+ attemptGeneration
+ )
+ return true
+ } catch {
+ // Keep this log static. The request, provider response, and credentials
+ // must not be copied into process logs while preserving the original error.
+ console.warn('[PluginWorkloadSdk] invocation acknowledgement failed')
+ return false
+ }
+}
+
export interface PromptBridgeHandlerDeps {
controlApiClient: PluginWorkloadSdkControlApiClient
llmBridge: LlmBridge
@@ -45,6 +79,24 @@ export interface PromptBridgeHandlerDeps {
maxRequestContentBytes?: number
/** Public provider/model identity from the live spec.agent binding. */
getBootstrapTarget?: () => { provider: string; model: string } | null
+ /** SDK-only atomic accounting boundary; workflow mode keeps the legacy reporter. */
+ finalizePromptBridge?: (input: {
+ invocationId: string
+ attemptGeneration: number
+ providerAttemptId: string
+ providerAttemptIndex: number
+ status: 'complete' | 'provider_unavailable'
+ reason: string
+ target: PromptBridgeTarget
+ usage?: {
+ llmSecretName: string
+ callerRef: string
+ fallbackUsed: boolean
+ attemptCount: number
+ inputTokens: number
+ outputTokens: number
+ }
+ }) => Promise<unknown>
onUsage?: (usage: {
invocationId: string
attemptGeneration: number
@@ -265,6 +317,7 @@ export class PromptBridgeHandler {
if (!selected || !sameTarget(selected, authorized.selectedTarget)) {
throw unexpectedAuthorizationResponse()
}
+ let unknownProviderAttempt: PluginWorkloadProviderAttemptContext | undefined
try {
const completion = await this.deps.llmBridge.complete({
invocationId: authorized.invocationId,
@@ -297,43 +350,116 @@ export class PromptBridgeHandler {
status: input.status,
}),
},
+ deferSuccessfulAttemptAcknowledgement: Boolean(this.deps.finalizePromptBridge),
maxTokens: clampMaxTokens(request.maxTokens, authorized.maxOutputTokens),
temperature: request.temperature ?? authorized.modelPolicy?.temperature,
timeoutMs: this.deps.promptTimeoutMs,
})
- await this.deps.controlApiClient.reportInvocationStatus(
- authorized.invocationId,
- this.deps.recipeNamespace,
- this.deps.recipeName,
- 'complete',
- authorized.attemptGeneration
- )
+ const providerAttemptAcknowledged = completion.providerAttemptAcknowledged !== false
+ const providerAttemptId = completion.providerAttemptId
+ const providerAttemptIndex = completion.providerAttemptIndex
+ if (
+ this.deps.finalizePromptBridge &&
+ (typeof providerAttemptId !== 'string' ||
+ typeof providerAttemptIndex !== 'number' ||
+ !Number.isInteger(providerAttemptIndex) ||
+ providerAttemptIndex < 1)
+ ) {
+ throw new PluginWorkloadError(
+ 'provider_unavailable',
+ 'provider attempt receipt is missing from the SDK-only completion',
+ false,
+ 'configuration'
+ )
+ }
+ if (
+ this.deps.finalizePromptBridge &&
+ typeof providerAttemptId === 'string' &&
+ typeof providerAttemptIndex === 'number' &&
+ Number.isInteger(providerAttemptIndex) &&
+ providerAttemptIndex >= 1
+ ) {
+ try {
+ await this.deps.finalizePromptBridge({
+ invocationId: authorized.invocationId,
+ attemptGeneration: authorized.attemptGeneration,
+ providerAttemptId,
+ providerAttemptIndex,
+ status: 'complete',
+ reason: providerAttemptAcknowledged
+ ? 'provider_completed'
+ : 'provider_completion_acknowledgement_recovered',
+ target: completion.servedTarget,
+ usage: {
+ llmSecretName: completion.llmSecretName,
+ callerRef,
+ fallbackUsed: completion.fallbackUsed,
+ attemptCount: completion.attemptCount,
+ inputTokens: completion.usage.inputTokens,
+ outputTokens: completion.usage.outputTokens,
+ },
+ })
+ } catch {
+ // Returning provider content before durable finalization would hide
+ // a possible spend. Surface an explicit unknown outcome instead.
+ throw new PluginWorkloadError(
+ 'provider_unavailable',
+ 'provider result could not be durably finalized; retry with a new idempotency key after investigation',
+ false,
+ 'outcome_unknown',
+ true,
+ {
+ providerAttemptId,
+ providerAttemptIndex,
+ target: completion.servedTarget,
+ attemptCount: completion.attemptCount,
+ fallbackUsed: completion.fallbackUsed,
+ llmSecretName: completion.llmSecretName,
+ }
+ )
+ }
+ } else {
+ await reportInvocationStatusBestEffort(
+ this.deps.controlApiClient,
+ authorized.invocationId,
+ this.deps.recipeNamespace,
+ this.deps.recipeName,
+ providerAttemptAcknowledged ? 'complete' : 'provider_unavailable',
+ authorized.attemptGeneration
+ )
+ }
- // Usage is emitted only after the generation-fenced terminal ACK. A
- // result whose audit transition was rejected must not enter metering as
- // if the provider call had completed authoritatively.
- this.deps.onUsage?.({
- invocationId: authorized.invocationId,
- attemptGeneration: authorized.attemptGeneration,
- provider: completion.servedTarget.provider,
- model: completion.model,
- servedTarget: completion.servedTarget,
- fallbackUsed: completion.fallbackUsed,
- attemptCount: completion.attemptCount,
- ...(completion.providerAttemptId
- ? { providerAttemptId: completion.providerAttemptId }
- : {}),
- ...(completion.providerAttemptIndex !== undefined
- ? { providerAttemptIndex: completion.providerAttemptIndex }
- : {}),
- llmSecretName: completion.llmSecretName,
- inputTokens: completion.usage.inputTokens,
- outputTokens: completion.usage.outputTokens,
- callerRef,
- ...(request.metadata ? { metadata: request.metadata } : {}),
- })
+ if (!this.deps.finalizePromptBridge && providerAttemptAcknowledged) {
+ // A confirmed physical completion is enough for receipt binding. If
+ // the logical invocation ACK is lost, the usage reporter can still
+ // retry against the durable provider-attempt receipt; suppressing the
+ // event here would silently lose metering after a successful call.
+ this.deps.onUsage?.({
+ invocationId: authorized.invocationId,
+ attemptGeneration: authorized.attemptGeneration,
+ provider: completion.servedTarget.provider,
+ model: completion.model,
+ servedTarget: completion.servedTarget,
+ fallbackUsed: completion.fallbackUsed,
+ attemptCount: completion.attemptCount,
+ ...(completion.providerAttemptId
+ ? { providerAttemptId: completion.providerAttemptId }
+ : {}),
+ ...(completion.providerAttemptIndex !== undefined
+ ? { providerAttemptIndex: completion.providerAttemptIndex }
+ : {}),
+ llmSecretName: completion.llmSecretName,
+ inputTokens: completion.usage.inputTokens,
+ outputTokens: completion.usage.outputTokens,
+ callerRef,
+ ...(request.metadata ? { metadata: request.metadata } : {}),
+ })
+ }
+ // Preserve a real provider response even when its physical receipt was
+ // not acknowledged. The invocation was closed as provider_unavailable
+ // above, so the idempotency key cannot be revived into a second call.
return {
invocationId: authorized.invocationId,
model: completion.model,
@@ -347,17 +473,38 @@ export class PromptBridgeHandler {
createdAt: new Date().toISOString(),
}
} catch (err) {
+ unknownProviderAttempt = err instanceof PluginWorkloadError ? err.providerAttempt : undefined
+ if (this.deps.finalizePromptBridge && unknownProviderAttempt) {
+ try {
+ await this.deps.finalizePromptBridge({
+ invocationId: authorized.invocationId,
+ attemptGeneration: authorized.attemptGeneration,
+ providerAttemptId: unknownProviderAttempt.providerAttemptId,
+ providerAttemptIndex: unknownProviderAttempt.providerAttemptIndex,
+ status: 'provider_unavailable',
+ reason:
+ err instanceof PluginWorkloadError && err.reason ? err.reason : 'outcome_unknown',
+ target: unknownProviderAttempt.target,
+ })
+ } catch {
+ console.warn('[PluginWorkloadSdk] provider spend finalization failed')
+ }
+ }
const status =
- err instanceof PluginWorkloadError && err.code === 'provider_unavailable'
+ err instanceof PluginWorkloadError &&
+ (err.code === 'provider_unavailable' || err.providerMayHaveExecuted)
? 'provider_unavailable'
: 'failed'
- await this.deps.controlApiClient.reportInvocationStatus(
- authorized.invocationId,
- this.deps.recipeNamespace,
- this.deps.recipeName,
- status,
- authorized.attemptGeneration
- )
+ if (!this.deps.finalizePromptBridge || !unknownProviderAttempt) {
+ await reportInvocationStatusBestEffort(
+ this.deps.controlApiClient,
+ authorized.invocationId,
+ this.deps.recipeNamespace,
+ this.deps.recipeName,
+ status,
+ authorized.attemptGeneration
+ )
+ }
throw err
}
}
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
index 8770a8b0d..62f9b3894 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
@@ -46,7 +46,8 @@ class FakeProvider implements Partial<SingleTurnProvider> {
function makeBridge(
providers: Record<string, FakeProvider>,
resolve?: PromptBridgeCredentialResolver['resolve'],
- createBreaker?: (target: PromptBridgeTarget) => CircuitBreaker
+ createBreaker?: (target: PromptBridgeTarget) => CircuitBreaker,
+ maxResponseBytes?: number
) {
const providerCalls: string[] = []
const credentialCalls: string[] = []
@@ -68,7 +69,11 @@ function makeBridge(
return (providers[model.name] ?? null) as unknown as SingleTurnProvider | null
}) as typeof createLLMProvider
return {
- bridge: new LlmBridge(resolver, { createProvider, createBreaker }),
+ bridge: new LlmBridge(resolver, {
+ createProvider,
+ createBreaker,
+ ...(maxResponseBytes !== undefined ? { maxResponseBytes } : {}),
+ }),
providerCalls,
credentialCalls,
resolver,
@@ -136,6 +141,23 @@ describe('LlmBridge authorized multi-provider fallback', () => {
expect(JSON.stringify(providerCalls)).not.toContain('secret-')
})
+ it('treats a successful response without authoritative usage as an unknown spend', async () => {
+ const missingUsage = new FakeProvider(() => Promise.resolve({ ...OK, usage_reported: false }))
+ const { bridge, providerCalls, credentialCalls } = makeBridge({
+ [primary.model]: missingUsage,
+ })
+
+ await expect(
+ bridge.complete({ ...request, targets: [{ target: primary }] })
+ ).rejects.toMatchObject({
+ code: 'provider_unavailable',
+ reason: 'outcome_unknown',
+ providerMayHaveExecuted: true,
+ })
+ expect(credentialCalls).toEqual([primary.targetRef])
+ expect(providerCalls).toEqual([`${primary.provider}/${primary.model}`])
+ })
+
it('treats credential resolution failure as terminal and never redeems a fallback', async () => {
const resolve = vi.fn(async () => {
throw new PluginWorkloadError(
@@ -366,6 +388,78 @@ describe('LlmBridge authorized multi-provider fallback', () => {
})
})
+ it('preserves a provider completion when its audit acknowledgement fails', async () => {
+ const provider = new FakeProvider(() => Promise.resolve(OK))
+ const { bridge } = makeBridge({ [primary.model]: provider })
+ const providerAttemptReporter = {
+ report: vi.fn().mockRejectedValue(new Error('control-api unavailable')),
+ }
+ const credentialTicketIssuer = {
+ issue: vi.fn(async () => ({
+ credentialTicket: 'fresh-primary',
+ providerAttemptId: 'attempt-primary',
+ providerAttemptIndex: 1,
+ })),
+ }
+
+ const result = await bridge.complete({
+ ...request,
+ targets: [{ target: primary }],
+ credentialTicketIssuer,
+ providerAttemptReporter,
+ })
+
+ expect(result).toMatchObject({
+ servedTarget: primary,
+ content: OK.content,
+ usage: { inputTokens: 3, outputTokens: 4 },
+ providerAttemptAcknowledged: false,
+ })
+ expect(provider.completeSingleTurn).toHaveBeenCalledOnce()
+ expect(providerAttemptReporter.report).toHaveBeenCalledWith({
+ providerAttemptId: 'attempt-primary',
+ providerAttemptIndex: 1,
+ status: 'complete',
+ })
+ })
+
+ it('does not turn a post-provider response rejection into a revivable failure', async () => {
+ const provider = new FakeProvider(() => Promise.resolve({ ...OK, content: 'too-large' }))
+ const { bridge, providerCalls } = makeBridge(
+ { [primary.model]: provider },
+ undefined,
+ undefined,
+ 4
+ )
+ const providerAttemptReporter = { report: vi.fn().mockResolvedValue(undefined) }
+
+ await expect(
+ bridge.complete({
+ ...request,
+ targets: [{ target: primary }],
+ credentialTicketIssuer: {
+ issue: vi.fn(async () => ({
+ credentialTicket: 'fresh-primary',
+ providerAttemptId: 'attempt-primary',
+ providerAttemptIndex: 1,
+ })),
+ },
+ providerAttemptReporter,
+ })
+ ).rejects.toMatchObject({
+ code: 'provider_unavailable',
+ retryable: false,
+ reason: 'outcome_unknown',
+ providerMayHaveExecuted: true,
+ })
+ expect(providerCalls).toEqual([`${primary.provider}/${primary.model}`])
+ expect(providerAttemptReporter.report).toHaveBeenCalledWith({
+ providerAttemptId: 'attempt-primary',
+ providerAttemptIndex: 1,
+ status: 'provider_unavailable',
+ })
+ })
+
it('publishes circuit state under the effective target label', async () => {
const target = { ...primary, targetRef: `metric-${Date.now()}` }
const failing = new FakeProvider(() => Promise.reject(new Error('429')))
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
index 250a3d480..6f0a9fab3 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
@@ -4,7 +4,7 @@ import { type SingleTurnProvider, createLLMProvider } from '../../llm'
import { type ClassifiedLike, type FailoverClass, classifyFailoverClass } from '../../llm/failover'
import { isLlmProvider } from '../../llm/registryCore'
import { CircuitBreaker } from '../domain/circuitBreaker'
-import { PluginWorkloadError } from '../domain/errors'
+import { PluginWorkloadError, type PluginWorkloadProviderAttemptContext } from '../domain/errors'
import type { PromptBridgeTarget } from '../domain/types'
import type { BrokeredCredential } from './credentialBrokerClient'
@@ -20,6 +20,10 @@ class ClassifiedProviderError extends Error {
toPluginWorkloadError(): PluginWorkloadError {
return this.publicError
}
+
+ get providerMayHaveExecuted(): boolean {
+ return this.publicError.providerMayHaveExecuted
+ }
}
export interface PromptBridgeCredentialResolver {
@@ -64,6 +68,8 @@ export interface LlmBridgeRequest {
policyHash: string
credentialTicketIssuer: PromptBridgeCredentialTicketIssuer
providerAttemptReporter?: PromptBridgeProviderAttemptReporter
+ /** SDK-only lane finalizes a successful physical attempt atomically in the handler. */
+ deferSuccessfulAttemptAcknowledgement?: boolean
messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>
maxTokens?: number
temperature?: number
@@ -79,11 +85,36 @@ export interface LlmBridgeResult {
llmSecretName: string
providerAttemptId?: string
providerAttemptIndex?: number
+ /** False means the provider result is real but its terminal receipt is not. */
+ providerAttemptAcknowledged?: boolean
content: string
usage: { inputTokens: number; outputTokens: number }
finishReason: 'complete' | 'length' | 'content_filter'
}
+/**
+ * Provider execution is the source of truth for the caller's result. A lost
+ * terminal acknowledgement must not turn a potentially billable completion
+ * into a revivable failure. The caller receives the result together with an
+ * explicit receipt flag; the handler then closes the logical invocation as
+ * provider_unavailable when the physical receipt is unknown.
+ */
+async function reportProviderAttemptBestEffort(
+ reporter: PromptBridgeProviderAttemptReporter | undefined,
+ input: Parameters<PromptBridgeProviderAttemptReporter['report']>[0]
+): Promise<boolean> {
+ if (!reporter) return true
+ try {
+ await reporter.report(input)
+ return true
+ } catch {
+ // Keep this log static. Provider responses and credential material must
+ // never be copied into process logs while preserving the provider outcome.
+ console.warn('[PluginWorkloadSdk] provider attempt acknowledgement failed')
+ return false
+ }
+}
+
const DEFAULT_MAX_LLM_RESPONSE_BYTES = 1024 * 1024
// Authentication and quota failures are operator/configuration signals, not
// safe automatic failover triggers. Provider-unavailable and rate-limited are
@@ -97,6 +128,19 @@ function remainingTimeoutMs(deadlineAt: number): number {
return deadlineAt - Date.now()
}
+function providerOutcomeUnknownError(
+ providerAttempt?: PluginWorkloadProviderAttemptContext
+): PluginWorkloadError {
+ return new PluginWorkloadError(
+ 'provider_unavailable',
+ 'provider execution outcome is unknown; retry with a new idempotency key after investigation',
+ false,
+ 'outcome_unknown',
+ true,
+ providerAttempt
+ )
+}
+
async function withinDeadline<T>(
operation: () => Promise<T>,
timeoutMs: number,
@@ -225,12 +269,8 @@ export class LlmBridge {
remainingTimeoutMs(deadlineAt),
'timeout'
)
- if (
- request.providerAttemptReporter &&
- skippedTicket.providerAttemptId &&
- skippedTicket.providerAttemptIndex !== undefined
- ) {
- await request.providerAttemptReporter.report({
+ if (skippedTicket.providerAttemptId && skippedTicket.providerAttemptIndex !== undefined) {
+ await reportProviderAttemptBestEffort(request.providerAttemptReporter, {
providerAttemptId: skippedTicket.providerAttemptId,
providerAttemptIndex: skippedTicket.providerAttemptIndex,
status: 'skipped',
@@ -293,11 +333,11 @@ export class LlmBridge {
// rejects the Secret read; close it before surfacing the terminal
// credential/configuration failure to the caller.
if (
- request.providerAttemptReporter &&
ticket.providerAttemptId &&
- ticket.providerAttemptIndex !== undefined
+ ticket.providerAttemptIndex !== undefined &&
+ !request.deferSuccessfulAttemptAcknowledgement
) {
- await request.providerAttemptReporter.report({
+ await reportProviderAttemptBestEffort(request.providerAttemptReporter, {
providerAttemptId: ticket.providerAttemptId,
providerAttemptIndex: ticket.providerAttemptIndex,
status: 'failed',
@@ -312,16 +352,16 @@ export class LlmBridge {
{ ...request, timeoutMs: remainingTimeoutMs(deadlineAt) },
breaker
)
- if (
- request.providerAttemptReporter &&
- ticket.providerAttemptId &&
- ticket.providerAttemptIndex !== undefined
- ) {
- await request.providerAttemptReporter.report({
- providerAttemptId: ticket.providerAttemptId,
- providerAttemptIndex: ticket.providerAttemptIndex,
- status: 'complete',
- })
+ let providerAttemptAcknowledged = true
+ if (ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined) {
+ providerAttemptAcknowledged = await reportProviderAttemptBestEffort(
+ request.providerAttemptReporter,
+ {
+ providerAttemptId: ticket.providerAttemptId,
+ providerAttemptIndex: ticket.providerAttemptIndex,
+ status: 'complete',
+ }
+ )
}
return {
...completion,
@@ -333,18 +373,43 @@ export class LlmBridge {
...(ticket.providerAttemptIndex !== undefined
? { providerAttemptIndex: ticket.providerAttemptIndex }
: {}),
+ providerAttemptAcknowledged,
}
} catch (error) {
- if (
- request.providerAttemptReporter &&
- ticket.providerAttemptId &&
- ticket.providerAttemptIndex !== undefined
- ) {
- await request.providerAttemptReporter.report({
- providerAttemptId: ticket.providerAttemptId,
- providerAttemptIndex: ticket.providerAttemptIndex,
- status: error instanceof ClassifiedProviderError ? 'provider_unavailable' : 'failed',
- })
+ const providerMayHaveExecuted =
+ (error instanceof PluginWorkloadError && error.providerMayHaveExecuted) ||
+ (error instanceof ClassifiedProviderError && error.providerMayHaveExecuted)
+ let providerAttemptAcknowledged = true
+ if (ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined) {
+ providerAttemptAcknowledged = await reportProviderAttemptBestEffort(
+ request.providerAttemptReporter,
+ {
+ providerAttemptId: ticket.providerAttemptId,
+ providerAttemptIndex: ticket.providerAttemptIndex,
+ status:
+ error instanceof ClassifiedProviderError || providerMayHaveExecuted
+ ? 'provider_unavailable'
+ : 'failed',
+ }
+ )
+ }
+ if (providerMayHaveExecuted || !providerAttemptAcknowledged) {
+ // Once execution may have started, a failed receipt is not a safe
+ // failover signal. Closing the logical invocation as terminal
+ // provider_unavailable prevents the same idempotency key from
+ // reviving into a second billable provider call.
+ throw providerOutcomeUnknownError(
+ ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined
+ ? {
+ providerAttemptId: ticket.providerAttemptId,
+ providerAttemptIndex: ticket.providerAttemptIndex,
+ target: authorized.target,
+ attemptCount: index + 1,
+ fallbackUsed: index > 0,
+ llmSecretName: credential.llmSecretName,
+ }
+ : undefined
+ )
}
if (!(error instanceof ClassifiedProviderError)) throw error
lastProviderError = error
@@ -416,18 +481,28 @@ export class LlmBridge {
const maxBytes = this.opts.maxResponseBytes ?? DEFAULT_MAX_LLM_RESPONSE_BYTES
if (Buffer.byteLength(response.content, 'utf8') > maxBytes) {
throw new PluginWorkloadError(
- 'payload_too_large',
- 'LLM response exceeded the maximum buffer size'
+ 'provider_unavailable',
+ 'provider returned a response that cannot be safely recorded',
+ false,
+ 'outcome_unknown',
+ true
)
}
const inputTokens = response.usage?.input_tokens ?? 0
const outputTokens = response.usage?.output_tokens ?? 0
- if (inputTokens < 0 || outputTokens < 0) {
+ if (
+ response.usage_reported === false ||
+ inputTokens < 0 ||
+ outputTokens < 0 ||
+ !Number.isInteger(inputTokens) ||
+ !Number.isInteger(outputTokens)
+ ) {
throw new PluginWorkloadError(
'provider_unavailable',
'provider returned invalid usage',
false,
- 'provider_unavailable'
+ 'outcome_unknown',
+ true
)
}
return {
@@ -446,7 +521,8 @@ export class LlmBridge {
'provider_unavailable',
'LLM provider did not respond within the request timeout',
true,
- 'timeout'
+ 'timeout',
+ true
)
)
}
@@ -459,7 +535,8 @@ export class LlmBridge {
'provider_unavailable',
`LLM provider error: ${classified.code}`,
classified.retryable,
- reason
+ reason,
+ classified.code === LlmErrorCode.ApiCallFailed
)
)
} finally {
diff --git a/mcp-host/src/pluginWorkloadSdk/server/index.ts b/mcp-host/src/pluginWorkloadSdk/server/index.ts
index dfbfc5f4c..3f34db27d 100644
--- a/mcp-host/src/pluginWorkloadSdk/server/index.ts
+++ b/mcp-host/src/pluginWorkloadSdk/server/index.ts
@@ -245,6 +245,7 @@ export function maybeCreatePluginWorkloadSdkServer(
pluginWorkloadSdkEnabled: config.pluginWorkloadSdkEnabled,
mcpHostRuntimeAccessToken: runtimeAuth?.accessToken ?? config.mcpHostRuntimeAccessToken ?? '',
podNamespace: config.podNamespace ?? '',
+ pluginWorkloadSdkCredentialBrokerUrl: config.pluginWorkloadSdkCredentialBrokerUrl,
})
if (!gate.start) {
console.log(
@@ -338,6 +339,15 @@ export function maybeCreatePluginWorkloadSdkServer(
return { provider: context.provider, model: context.defaultModel }
}
: undefined,
+ finalizePromptBridge:
+ config.pluginWorkloadSdkRuntimeMode === 'sdk-only'
+ ? input =>
+ controlApiClient.finalizePromptBridge({
+ recipeNamespace: binding.recipeNamespace,
+ recipeName: binding.recipeName,
+ ...input,
+ })
+ : undefined,
onUsage: usage => {
if (!usageReporter) return
const event = buildPromptBridgeUsageEvent({
diff --git a/mcp-host/src/pluginWorkloadSdk/server/sdkServer.test.ts b/mcp-host/src/pluginWorkloadSdk/server/sdkServer.test.ts
index e09cfdba7..ebde33bd1 100644
--- a/mcp-host/src/pluginWorkloadSdk/server/sdkServer.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/server/sdkServer.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest'
-import { checkLiveRuntimeBinding, shouldStartPluginWorkloadSdk } from './sdkServer'
+import {
+ checkLiveRuntimeBinding,
+ shouldStartPluginWorkloadSdk,
+ validatePluginWorkloadSdkCredentialBrokerUrl,
+} from './sdkServer'
/**
* Triple activation gate (plan §6.3): 2^3 combinations — only
@@ -21,6 +25,7 @@ function makeRuntimeToken(recipeNamespace: string | null): string {
const SANDBOX_TOKEN = makeRuntimeToken('sandbox-recipes')
const HOST_NS_TOKEN = makeRuntimeToken('mcp-host')
const UNBOUND_TOKEN = makeRuntimeToken(null)
+const BROKER_URL = 'http://workflow-recipes:8082'
describe('shouldStartPluginWorkloadSdk — behavior matrix', () => {
const cases: Array<{
@@ -108,6 +113,7 @@ describe('shouldStartPluginWorkloadSdk — behavior matrix', () => {
pluginWorkloadSdkEnabled: c.enabled,
mcpHostRuntimeAccessToken: c.token,
podNamespace: c.podNamespace,
+ pluginWorkloadSdkCredentialBrokerUrl: c.enabled ? BROKER_URL : '',
})
expect(result.start).toBe(c.start)
expect(result.reason).toBeTruthy()
@@ -120,6 +126,7 @@ describe('shouldStartPluginWorkloadSdk — behavior matrix', () => {
pluginWorkloadSdkEnabled: false,
mcpHostRuntimeAccessToken: SANDBOX_TOKEN,
podNamespace: 'sandbox-recipes',
+ pluginWorkloadSdkCredentialBrokerUrl: '',
}).reason
).toContain('PLUGIN_WORKLOAD_SDK_ENABLED')
expect(
@@ -127,6 +134,7 @@ describe('shouldStartPluginWorkloadSdk — behavior matrix', () => {
pluginWorkloadSdkEnabled: true,
mcpHostRuntimeAccessToken: HOST_NS_TOKEN,
podNamespace: 'sandbox-recipes',
+ pluginWorkloadSdkCredentialBrokerUrl: BROKER_URL,
}).reason
).toContain("recipeNamespace is 'mcp-host'")
expect(
@@ -134,11 +142,32 @@ describe('shouldStartPluginWorkloadSdk — behavior matrix', () => {
pluginWorkloadSdkEnabled: true,
mcpHostRuntimeAccessToken: SANDBOX_TOKEN,
podNamespace: '',
+ pluginWorkloadSdkCredentialBrokerUrl: BROKER_URL,
}).reason
).toContain('(empty)')
})
})
+describe('validatePluginWorkloadSdkCredentialBrokerUrl', () => {
+ it.each(['', ' ', 'workflow-recipes:8082', 'ftp://workflow-recipes:8082'])(
+ 'rejects %j',
+ value => {
+ expect(validatePluginWorkloadSdkCredentialBrokerUrl(value)).toBeTruthy()
+ }
+ )
+
+ it('accepts an internal service base URL and rejects URL authority/path injection', () => {
+ expect(validatePluginWorkloadSdkCredentialBrokerUrl('http://workflow-recipes:8082')).toBeNull()
+ expect(validatePluginWorkloadSdkCredentialBrokerUrl('https://wrc.example.test')).toBeNull()
+ expect(
+ validatePluginWorkloadSdkCredentialBrokerUrl('http://user:pass@workflow-recipes:8082')
+ ).toBeTruthy()
+ expect(
+ validatePluginWorkloadSdkCredentialBrokerUrl('http://workflow-recipes:8082/api')
+ ).toBeTruthy()
+ })
+})
+
describe('checkLiveRuntimeBinding — per-request token re-validation', () => {
const boundBinding = {
hostRef: 'sandbox-recipes/r1',
diff --git a/mcp-host/src/pluginWorkloadSdk/server/sdkServer.ts b/mcp-host/src/pluginWorkloadSdk/server/sdkServer.ts
index 49b22bce8..0b0e90b32 100644
--- a/mcp-host/src/pluginWorkloadSdk/server/sdkServer.ts
+++ b/mcp-host/src/pluginWorkloadSdk/server/sdkServer.ts
@@ -19,15 +19,43 @@ import { registerSdkRoutes } from './routes'
export const PLUGIN_WORKLOAD_SDK_REQUIRED_NAMESPACE = 'sandbox-recipes'
+/** Validate the WRC credential-broker base URL before any SDK listener binds. */
+export function validatePluginWorkloadSdkCredentialBrokerUrl(value: string): string | null {
+ const raw = value.trim()
+ if (!raw) return 'CLERUM_WRC_URL is required when Plugin Workload SDK is enabled'
+ let parsed: URL
+ try {
+ parsed = new URL(raw)
+ } catch {
+ return 'CLERUM_WRC_URL must be an absolute http(s) URL'
+ }
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
+ return 'CLERUM_WRC_URL must use http or https'
+ }
+ if (!parsed.hostname || parsed.username || parsed.password || parsed.search || parsed.hash) {
+ return 'CLERUM_WRC_URL must not contain credentials, query parameters, or fragments'
+ }
+ if (parsed.pathname !== '' && parsed.pathname !== '/') {
+ return 'CLERUM_WRC_URL must be a service base URL without a path'
+ }
+ return null
+}
+
export function shouldStartPluginWorkloadSdk(config: {
pluginWorkloadSdkEnabled: boolean
mcpHostRuntimeAccessToken: string
podNamespace: string
+ pluginWorkloadSdkCredentialBrokerUrl?: string
}): { start: boolean; reason: string } {
if (!config.pluginWorkloadSdkEnabled) {
return { start: false, reason: 'PLUGIN_WORKLOAD_SDK_ENABLED is not set' }
}
+ const brokerUrlError = validatePluginWorkloadSdkCredentialBrokerUrl(
+ config.pluginWorkloadSdkCredentialBrokerUrl ?? ''
+ )
+ if (brokerUrlError) return { start: false, reason: brokerUrlError }
+
const runtimeBinding = getJwtRuntimeBinding(config.mcpHostRuntimeAccessToken)
if (runtimeBinding?.recipeNamespace !== PLUGIN_WORKLOAD_SDK_REQUIRED_NAMESPACE) {
return {
diff --git a/scripts/tests/test-gcp-scripts.sh b/scripts/tests/test-gcp-scripts.sh
index 2fdb31600..9f68f875a 100755
--- a/scripts/tests/test-gcp-scripts.sh
+++ b/scripts/tests/test-gcp-scripts.sh
@@ -1461,16 +1461,17 @@ assert_control_api_runtime_access_contract_is_exact() {
relation_count="$(awk -F '\t' '!/^[[:space:]]*(#|$)/ { count++ } END { print count + 0 }' "$profile_file")"
duplicate_count="$(awk -F '\t' '!/^[[:space:]]*(#|$)/ { seen[$1]++ } END { for (name in seen) if (seen[name] > 1) count++ } END { print count + 0 }' "$profile_file")"
- invalid_count="$(awk -F '\t' '!/^[[:space:]]*(#|$)/ && (NF != 2 || $1 !~ /^[a-z][a-z0-9_]*$/ || $2 !~ /^(legacy_dml|append|read)$/) { count++ } END { print count + 0 }' "$profile_file")"
+ invalid_count="$(awk -F '\t' '!/^[[:space:]]*(#|$)/ && (NF != 2 || $1 !~ /^[a-z][a-z0-9_]*$/ || $2 !~ /^(legacy_dml|upsert|append|read|none)$/) { count++ } END { print count + 0 }' "$profile_file")"
sequence_count="$(awk -F '\t' '!/^[[:space:]]*(#|$)/ { count++ } END { print count + 0 }' "$sequence_profile_file")"
sequence_duplicate_count="$(awk -F '\t' '!/^[[:space:]]*(#|$)/ { seen[$1]++ } END { for (name in seen) if (seen[name] > 1) count++ } END { print count + 0 }' "$sequence_profile_file")"
sequence_invalid_count="$(awk -F '\t' '!/^[[:space:]]*(#|$)/ && (NF != 2 || $1 !~ /^[a-z][a-z0-9_]*$/ || $2 !~ /^(legacy_rw|consume)$/) { count++ } END { print count + 0 }' "$sequence_profile_file")"
- if [[ "$relation_count" == "75" && "$duplicate_count" == "0" && "$invalid_count" == "0" ]] && \
+ if [[ "$relation_count" == "80" && "$duplicate_count" == "0" && "$invalid_count" == "0" ]] && \
grep -qx $'llm_allowed_models\tlegacy_dml' "$profile_file" && \
- grep -qx $'member_registration_credentials\tlegacy_dml' "$profile_file" && \
+ grep -qx $'member_registration_credentials\tupsert' "$profile_file" && \
grep -qx $'llm_allowed_models_audit\tappend' "$profile_file" && \
grep -qx $'llm_catalog_sync_runs\tappend' "$profile_file" && \
+ grep -qx $'plugin_workload_sdk_spend_outcomes\tappend' "$profile_file" && \
[[ "$sequence_count" == "7" && "$sequence_duplicate_count" == "0" && "$sequence_invalid_count" == "0" ]] && \
grep -qx $'member_registration_credentials_id_seq\tconsume' "$sequence_profile_file" && \
[[ "$migration_script" != *'RUNTIME_ACCESS_PROFILES_FILE:-'* ]] && \
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index a6c4fc594..0ec736c30 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.276",
+ "version": "0.1.277",
"lockfileVersion": 3,
"requires": true,
"packages": {
@@ -34,7 +34,7 @@
"engines": {
"node": ">=24"
},
- "version": "0.1.276"
+ "version": "0.1.277"
},
"../packages/image-policy": {
"name": "@clerum/image-policy",
diff --git a/workflow-recipes/package.json b/workflow-recipes/package.json
index c51d40431..e36b28aeb 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.276",
+ "version": "0.1.277",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/reconciler/reconciler.test.ts b/workflow-recipes/src/reconciler/reconciler.test.ts
index 4b6bac2a4..c8ae73600 100644
--- a/workflow-recipes/src/reconciler/reconciler.test.ts
+++ b/workflow-recipes/src/reconciler/reconciler.test.ts
@@ -409,7 +409,9 @@ describe('WorkflowRecipeReconciler', () => {
)
expect(result.phase).toBe('active')
- expect(cleanupPluginWorkloadSdk).toHaveBeenCalledWith('test-recipe')
+ expect(cleanupPluginWorkloadSdk).toHaveBeenCalledWith('test-recipe', {
+ preserveWorkflowRuntime: false,
+ })
expect(workflowReconcile).not.toHaveBeenCalled()
})
@@ -437,7 +439,9 @@ describe('WorkflowRecipeReconciler', () => {
)
expect(result.phase).toBe(phase)
- expect(cleanupPluginWorkloadSdk).toHaveBeenCalledWith('test-recipe')
+ expect(cleanupPluginWorkloadSdk).toHaveBeenCalledWith('test-recipe', {
+ preserveWorkflowRuntime: false,
+ })
}
)
@@ -480,7 +484,9 @@ describe('WorkflowRecipeReconciler', () => {
pluginWorkloadSdkTeardownConfirmed: true,
message: 'Plugin Workload SDK disabled after confirmed teardown',
})
- expect(cleanupPluginWorkloadSdk).toHaveBeenCalledWith('test-recipe')
+ expect(cleanupPluginWorkloadSdk).toHaveBeenCalledWith('test-recipe', {
+ preserveWorkflowRuntime: false,
+ })
expect(workflowReconcile).not.toHaveBeenCalled()
})
diff --git a/workflow-recipes/src/workflow/networkPolicyFactory.ts b/workflow-recipes/src/workflow/networkPolicyFactory.ts
index 9b7e8f9fd..4b96aa63c 100644
--- a/workflow-recipes/src/workflow/networkPolicyFactory.ts
+++ b/workflow-recipes/src/workflow/networkPolicyFactory.ts
@@ -198,16 +198,24 @@ export function buildWorkflowNetworkPolicies(
'clerum.io/managed-by': 'wrc',
}
const includeCoordinator = config.includeCoordinator !== false
+ const usesCoordinatorLane = (policy: k8s.V1NetworkPolicy): boolean => {
+ if (policy.spec?.podSelector?.matchLabels?.['clerum.io/component'] === 'workflow-coordinator') {
+ return true
+ }
+ // Coordinator-to-workload ingress policies select the workload pod, so
+ // their metadata.name and podSelector do not identify the coordinator.
+ // Classify them by the semantic peer label instead of a generated name;
+ // truncateRfc1123WithHash may remove the textual coordinator prefix.
+ return Boolean(
+ policy.spec?.ingress?.some(rule =>
+ rule._from?.some(
+ peer => peer.podSelector?.matchLabels?.['clerum.io/component'] === 'workflow-coordinator'
+ )
+ )
+ )
+ }
const filterCoordinatorPolicies = (policies: k8s.V1NetworkPolicy[]) =>
- includeCoordinator
- ? policies
- : policies.filter(policy => {
- const name = policy.metadata?.name ?? ''
- return (
- !name.startsWith(`${config.recipeName}-coord-to-`) &&
- !name.startsWith(`${config.recipeName}-coordinator-to-`)
- )
- })
+ includeCoordinator ? policies : policies.filter(policy => !usesCoordinatorLane(policy))
const dnsEgressRule: k8s.V1NetworkPolicyEgressRule = {
to: [
{
diff --git a/workflow-recipes/tests/unit/workflow/networkPolicyFactory.test.ts b/workflow-recipes/tests/unit/workflow/networkPolicyFactory.test.ts
index bee96c0ce..629ad09eb 100644
--- a/workflow-recipes/tests/unit/workflow/networkPolicyFactory.test.ts
+++ b/workflow-recipes/tests/unit/workflow/networkPolicyFactory.test.ts
@@ -29,7 +29,6 @@ function hasPublicHttpEgressRule(policy: {
const ports = new Set(rule.ports?.map(port => port.port))
return (
ports.has(443) &&
- ports.has(80) &&
rule.to?.some(target => {
const block = target.ipBlock
const requiredExcludes = [
@@ -75,7 +74,7 @@ function publicHttpEgressCidrs(policy: {
policy.spec?.egress
?.filter(rule => {
const ports = new Set(rule.ports?.map(port => port.port))
- return ports.has(443) && ports.has(80)
+ return ports.has(443)
})
.flatMap(rule => rule.to?.map(target => target.ipBlock?.cidr).filter(Boolean) ?? []) ?? []
)
@@ -298,6 +297,34 @@ describe('NetworkPolicy Factory', () => {
}
})
+ it('removes coordinator lanes by semantic labels even when generated names are hashed', () => {
+ const longRecipe = 'e2e-layer3a-coordinator-lane-with-a-name-longer-than-rfc1123-prefix'
+ const policies = buildWorkflowNetworkPolicies(
+ {
+ ...npConfig,
+ recipeName: longRecipe,
+ includeCoordinator: false,
+ coordinatorWorkloadEgress: [{ resourceName: `${longRecipe}-scanner`, port: 8080 }],
+ },
+ []
+ )
+
+ expect(
+ policies.some(
+ policy =>
+ policy.spec?.podSelector?.matchLabels?.['clerum.io/component'] ===
+ 'workflow-coordinator' ||
+ policy.spec?.ingress?.some(rule =>
+ rule._from?.some(
+ peer =>
+ peer.podSelector?.matchLabels?.['clerum.io/component'] === 'workflow-coordinator'
+ )
+ )
+ )
+ ).toBe(false)
+ expect(policies.some(policy => policy.metadata?.name?.includes('coordinator-to'))).toBe(false)
+ })
+
it('grants public HTTP egress to snippet runner only when declared', () => {
const snippetPolicies = buildWorkflowNetworkPolicies(
{
@@ -458,7 +485,7 @@ describe('NetworkPolicy Factory', () => {
expect(policy!.spec!.egress![0].to?.[0]?.ipBlock?.except).toEqual(
expect.arrayContaining(['10.0.0.0/8', '169.254.0.0/16', '192.168.0.0/16'])
)
- expect(policy!.spec!.egress![0].ports!.map(port => port.port)).toEqual([443, 80])
+ expect(policy!.spec!.egress![0].ports!.map(port => port.port)).toEqual([443])
})
it('does not grant recipe MCP servers implicit public HTTP egress', () => {
diff --git a/workflow-recipes/tests/unit/workflow/workflowReconciler.test.ts b/workflow-recipes/tests/unit/workflow/workflowReconciler.test.ts
index bc43f2a75..d6a98e3a7 100644
--- a/workflow-recipes/tests/unit/workflow/workflowReconciler.test.ts
+++ b/workflow-recipes/tests/unit/workflow/workflowReconciler.test.ts
@@ -386,7 +386,6 @@ function hasPublicHttpEgressRule(policy: {
]
return (
ports.has(443) &&
- ports.has(80) &&
rule.to?.some(target => {
const block = target.ipBlock
return Boolean(
@@ -412,7 +411,7 @@ function publicHttpEgressCidrs(policy: {
policy.spec?.egress
?.filter(rule => {
const ports = new Set(rule.ports?.map(port => port.port))
- return ports.has(443) && ports.has(80)
+ return ports.has(443)
})
.flatMap(rule => rule.to?.map(target => target.ipBlock?.cidr).filter(Boolean) ?? []) ?? []
)