Skip to content

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

TypeScript

fix(control-api): serialize grant upsert with the per-model advisory lock (R1-H3 fase 2)

Diego Zacarias4d61eacb9716
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 4f1a278a1..97c5fb140 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.452",
+ "version": "0.1.453",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.452",
+ "version": "0.1.453",
"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 c33a8dbab..3d0090147 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.452",
+ "version": "0.1.453",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/routes/admin/pluginWorkloadSdk.ts b/control-api/src/routes/admin/pluginWorkloadSdk.ts
index ee1b5af30..eeee3b665 100644
--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts
+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts
@@ -4,6 +4,11 @@ import {
isLlmProviderId,
isRunnableLlmModelId,
} from '@clerum/llm-providers'
+import {
+ advisoryLockModelNames,
+ boundCarrierTransactionIdleTimeout,
+ withTransaction,
+} from '../../db.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'
import { createPluginWorkloadSdkAdminRateLimit } from '../../middleware/pluginWorkloadSdkRateLimits.js'
@@ -262,6 +267,19 @@ function parsePromptTargets(value: unknown, res: Response): PluginWorkloadSdkPro
return targets
}
+// A rejection produced by the enabled-ness write-gate WHILE it runs inside the
+// carrier transaction that holds the per-model advisory locks (R1-H3 fase 2).
+// It is THROWN (not `res.json`-ed inline) so the transaction ROLLS BACK — the
+// upsert never persists and no Pieza D audit is emitted — then mapped back to
+// the SAME 400 body the gate has always returned. `body` is byte-stable with
+// the pre-fase-2 responses (`model_not_allowed`, `modelPolicies.*` drift).
+class GrantModelGateError extends Error {
+ constructor(readonly body: Record<string, unknown>) {
+ super('grant_model_gate_rejected')
+ this.name = 'GrantModelGateError'
+ }
+}
+
export interface AdminPluginWorkloadSdkRouterDeps {
/**
* Emit the audit signal for a tolerated pre-existing model_not_allowed
@@ -421,159 +439,217 @@ export function createAdminPluginWorkloadSdkRouter(
const defaultTarget = promptTargets[0]!
// `provider` remains the bootstrap host binding during the compatibility
// window. It cannot authorize routes by itself and must agree with the
- // policy default instead of being silently reconciled.
+ // policy default instead of being silently reconciled. Pure check, kept
+ // OUTSIDE the carrier transaction (no model read, no lock needed).
if (provider !== defaultTarget.provider) {
res.status(400).json({ error: 'policy_bootstrap_mismatch' })
return
}
- const modelsByProvider = new Map<string, string[]>()
- for (const target of promptTargets) {
- modelsByProvider.set(target.provider, [
- ...(modelsByProvider.get(target.provider) ?? []),
- target.model,
- ])
- }
- // Pieza D — role-scoped no-worsening tolerance (editability trap, mini-spec
- // 01). A grant that references a model later disabled globally would
- // otherwise be uneditable (every save 400s `model_not_allowed`). Tolerate a
- // disabled `(provider, model)` iff (b) the incoming `allowed_models` does
- // NOT shrink the stored coverage AND it kept its ROLE: the incoming DEFAULT
- // target (`promptTargets[0]`) is tolerated only if it was the stored default
- // target; a NON-default target only if it was any stored target (demotion is
- // not worsening). Promoting a disabled non-default target to the default slot
- // is NOT tolerated. A brand-new disabled model is never tolerated. The stored
- // grant is read lazily — only when a candidate rejection appears — so the
- // all-enabled happy path keeps its single-query cost.
- const incomingDefaultKey = offeredKey(promptTargets[0]!.provider, promptTargets[0]!.model)
- let storedLoaded = false
- let storedDefaultTarget = new Set<string>()
- let storedAnyTarget = new Set<string>()
- // Grant `allowed_models` is a flat model-name list; treat it as a literal
- // finite coverage set (NOT the Host UNIVERSAL-on-empty semantics) so an
- // emptied list is a strict reduction, not a widening.
- const incomingCoverage: CoverageSet = new Set(allowedModels)
- let storedCoverage: CoverageSet = new Set<string>()
- const loadStoredGrant = async (): Promise<void> => {
- if (storedLoaded) return
- storedLoaded = true
- const storedGrant = (await listGrants({ recipeNamespace, recipeName }))?.find(
- existing => existing.capabilityFamily === capabilityFamily
- )
- const storedTargets = storedGrant?.promptTargets ?? []
- storedDefaultTarget = new Set(
- storedTargets[0] ? [offeredKey(storedTargets[0].provider, storedTargets[0].model)] : []
- )
- storedAnyTarget = new Set(storedTargets.map(t => offeredKey(t.provider, t.model)))
- storedCoverage = new Set(storedGrant?.allowedModels ?? [])
- }
- for (const [targetProvider, targetModels] of modelsByProvider) {
- const enabledRows = await listEnabledModelsWithStaleForProvider(targetProvider)
- const enabled = new Set(enabledRows.map(row => row.model))
- const staleEnabled = new Set(enabledRows.filter(row => row.stale).map(row => row.model))
-
- // Fase 6 soft quarantine: warn (never block) when a NEW target assigns an
- // ENABLED but `stale` model. A live reference already in the stored grant
- // is not revalidated (spec §3.3). The stored grant is loaded lazily — only
- // when a stale-enabled candidate is actually present — so the all-fresh /
- // no-stale happy path keeps its single-query cost.
- for (const model of targetModels) {
- if (!enabled.has(model) || !staleEnabled.has(model)) continue
- const pairKey = offeredKey(targetProvider, model)
- if (grantWarnedKeys.has(pairKey)) continue
- grantWarnedKeys.add(pairKey)
- await loadStoredGrant()
- if (storedAnyTarget.has(pairKey)) continue
- const i = promptTargets.findIndex(
- target => target.provider === targetProvider && target.model === model
+ }
+
+ // R1-H3 fase 2 — carrier transaction that serializes this grant upsert
+ // against a concurrent llm-model disable/delete (the reductor, fase 1).
+ // The reductor enumerates grants by NAME in `allowed_models` under
+ // `advisoryLockModelName`; so the upsert takes the SAME per-name locks over
+ // ALL incoming `allowed_models` names, HOLDS them across the enabled-ness
+ // re-validation, and commits the write atomically. Ordering is the global
+ // invariant (adenda A5): every `llm-model:*` lock is taken BEFORE the
+ // recipe lock (`plugin_workload_sdk:*`, taken inside `upsertGrant`). If the
+ // reductor commits first, the gate below re-reads `llm_allowed_models`
+ // under the lock and rejects (400); if the grant commits first, the
+ // reductor sees it and answers 409 — neither can strand a dangling grant.
+ // Enabled-ness is validated only for promptBridge targets, EXACTLY as
+ // before (serialization only, no accept/reject change): a disabled model
+ // reachable solely through `allowed_models` (no promptTarget) is a
+ // PRE-EXISTING gap, out of R1-H3 scope.
+ let grant: Awaited<ReturnType<typeof upsertGrant>>
+ try {
+ grant = await withTransaction(async db => {
+ // Bound idle-in-transaction tenancy for parity with the reductor
+ // (fase 1). This seam is PG-only (no K8s write under the lock), so the
+ // lock is never held across an external round-trip — cheap, defensive.
+ await boundCarrierTransactionIdleTimeout(db)
+ // Model-name locks FIRST, deduped + totally ordered, over EVERY incoming
+ // `allowed_models` name (the reductor matches by name across families).
+ // Empty list = no-op. Taken before the recipe lock (global order A5).
+ await advisoryLockModelNames(db, allowedModels)
+
+ if (capabilityFamily === 'promptBridge') {
+ const modelsByProvider = new Map<string, string[]>()
+ for (const target of promptTargets) {
+ modelsByProvider.set(target.provider, [
+ ...(modelsByProvider.get(target.provider) ?? []),
+ target.model,
+ ])
+ }
+ // Pieza D — role-scoped no-worsening tolerance (editability trap,
+ // mini-spec 01). A grant that references a model later disabled
+ // globally would otherwise be uneditable (every save 400s
+ // `model_not_allowed`). Tolerate a disabled `(provider, model)` iff
+ // (b) the incoming `allowed_models` does NOT shrink the stored
+ // coverage AND it kept its ROLE: the incoming DEFAULT target
+ // (`promptTargets[0]`) is tolerated only if it was the stored default
+ // target; a NON-default target only if it was any stored target
+ // (demotion is not worsening). Promoting a disabled non-default target
+ // to the default slot is NOT tolerated. A brand-new disabled model is
+ // never tolerated. The stored grant is read lazily — only when a
+ // candidate rejection appears — so the all-enabled happy path keeps
+ // its single-query cost.
+ const incomingDefaultKey = offeredKey(
+ promptTargets[0]!.provider,
+ promptTargets[0]!.model
)
- grantWarnings.push({
- code: STALE_MODEL_ASSIGNED,
- provider: targetProvider,
- model,
- field: i >= 0 ? `promptTargets[${i}].model` : 'promptTargets',
- })
- }
+ let storedLoaded = false
+ let storedDefaultTarget = new Set<string>()
+ let storedAnyTarget = new Set<string>()
+ // Grant `allowed_models` is a flat model-name list; treat it as a
+ // literal finite coverage set (NOT the Host UNIVERSAL-on-empty
+ // semantics) so an emptied list is a strict reduction, not a widening.
+ const incomingCoverage: CoverageSet = new Set(allowedModels)
+ let storedCoverage: CoverageSet = new Set<string>()
+ const loadStoredGrant = async (): Promise<void> => {
+ if (storedLoaded) return
+ storedLoaded = true
+ // Read the stored grant on the CARRIER connection (holds the model
+ // locks) so no extra pool checkout happens under the lock (A3).
+ const storedGrant = (await listGrants({ recipeNamespace, recipeName }, db))?.find(
+ existing => existing.capabilityFamily === capabilityFamily
+ )
+ const storedTargets = storedGrant?.promptTargets ?? []
+ storedDefaultTarget = new Set(
+ storedTargets[0]
+ ? [offeredKey(storedTargets[0].provider, storedTargets[0].model)]
+ : []
+ )
+ storedAnyTarget = new Set(storedTargets.map(t => offeredKey(t.provider, t.model)))
+ storedCoverage = new Set(storedGrant?.allowedModels ?? [])
+ }
+ for (const [targetProvider, targetModels] of modelsByProvider) {
+ // Enabled-ness re-read UNDER the model locks, on the carrier `db`
+ // (NOT the global pool) — this is the read the reductor races.
+ const enabledRows = await listEnabledModelsWithStaleForProvider(targetProvider, db)
+ const enabled = new Set(enabledRows.map(row => row.model))
+ const staleEnabled = new Set(
+ enabledRows.filter(row => row.stale).map(row => row.model)
+ )
+
+ // Fase 6 soft quarantine: warn (never block) when a NEW target
+ // assigns an ENABLED but `stale` model. A live reference already in
+ // the stored grant is not revalidated (spec §3.3). The stored grant
+ // is loaded lazily — only when a stale-enabled candidate is actually
+ // present — so the all-fresh / no-stale happy path keeps its
+ // single-query cost.
+ for (const model of targetModels) {
+ if (!enabled.has(model) || !staleEnabled.has(model)) continue
+ const pairKey = offeredKey(targetProvider, model)
+ if (grantWarnedKeys.has(pairKey)) continue
+ grantWarnedKeys.add(pairKey)
+ await loadStoredGrant()
+ if (storedAnyTarget.has(pairKey)) continue
+ const i = promptTargets.findIndex(
+ target => target.provider === targetProvider && target.model === model
+ )
+ grantWarnings.push({
+ code: STALE_MODEL_ASSIGNED,
+ provider: targetProvider,
+ model,
+ field: i >= 0 ? `promptTargets[${i}].model` : 'promptTargets',
+ })
+ }
- const rawOffenders = targetModels.filter(model => !enabled.has(model))
- if (rawOffenders.length === 0) continue
- await loadStoredGrant()
- const offenders: string[] = []
- for (const model of rawOffenders) {
- const pairKey = offeredKey(targetProvider, model)
- // Role of the offending pair in the INCOMING grant: the default slot
- // (`promptTargets[0]`) must have been the stored default; any other
- // target may have been any stored target.
- const storedRoleSet =
- pairKey === incomingDefaultKey ? storedDefaultTarget : storedAnyTarget
- const tolerated = isNonWorseningToleration({
- pairKey,
- storedReferencedPairKeys: storedRoleSet,
- incomingCoverage,
- storedCoverage,
- })
- if (tolerated) {
- pendingGrantTolerations.push({
- resourceKind: 'grant',
- namespace: recipeNamespace,
- name: recipeName,
- provider: targetProvider,
- model,
- gate: 'grant',
- offeredBefore: storedCoverage,
- offeredAfter: incomingCoverage,
- })
- } else {
- offenders.push(model)
+ const rawOffenders = targetModels.filter(model => !enabled.has(model))
+ if (rawOffenders.length === 0) continue
+ await loadStoredGrant()
+ const offenders: string[] = []
+ for (const model of rawOffenders) {
+ const pairKey = offeredKey(targetProvider, model)
+ // Role of the offending pair in the INCOMING grant: the default
+ // slot (`promptTargets[0]`) must have been the stored default; any
+ // other target may have been any stored target.
+ const storedRoleSet =
+ pairKey === incomingDefaultKey ? storedDefaultTarget : storedAnyTarget
+ const tolerated = isNonWorseningToleration({
+ pairKey,
+ storedReferencedPairKeys: storedRoleSet,
+ incomingCoverage,
+ storedCoverage,
+ })
+ if (tolerated) {
+ pendingGrantTolerations.push({
+ resourceKind: 'grant',
+ namespace: recipeNamespace,
+ name: recipeName,
+ provider: targetProvider,
+ model,
+ gate: 'grant',
+ offeredBefore: storedCoverage,
+ offeredAfter: incomingCoverage,
+ })
+ } else {
+ offenders.push(model)
+ }
+ }
+ if (offenders.length > 0) {
+ // THROW (not res.json) so the transaction rolls back — the upsert
+ // never runs and no Pieza D audit fires — mapped to the byte-stable
+ // 400 `model_not_allowed` body outside the transaction.
+ throw new GrantModelGateError({
+ error: 'model_not_allowed',
+ provider: targetProvider,
+ models: offenders,
+ })
+ }
+ }
+ // A modelPolicyRef names an already-authorized target, not a second
+ // routing authority. Keep the older record shape but reject drift.
+ // Runs AFTER the enabled-ness gate to preserve error precedence.
+ for (const [ref, policy] of Object.entries(modelPolicies)) {
+ if (
+ !promptTargets.some(
+ target => target.provider === policy.provider && target.model === policy.model
+ )
+ ) {
+ throw new GrantModelGateError({
+ error: `modelPolicies.${ref} does not match an authorized target`,
+ })
+ }
}
}
- if (offenders.length > 0) {
- res.status(400).json({
- error: 'model_not_allowed',
- provider: targetProvider,
- models: offenders,
- })
- return
- }
- }
- // A modelPolicyRef names an already-authorized target, not a second
- // routing authority. Keep the older record shape but reject drift.
- for (const [ref, policy] of Object.entries(modelPolicies)) {
- if (
- !promptTargets.some(
- target => target.provider === policy.provider && target.model === policy.model
- )
- ) {
- res
- .status(400)
- .json({ error: `modelPolicies.${ref} does not match an authorized target` })
- return
+
+ if (allowedCallers.length === 0) {
+ throw new GrantModelGateError({ error: 'allowedCallers must be non-empty' })
}
- }
- }
- if (allowedCallers.length === 0) {
- res.status(400).json({ error: 'allowedCallers must be non-empty' })
- return
+ // Reuse THIS transaction: `upsertGrant` takes the recipe lock as its
+ // first statement — AFTER the model locks above (global order A5) — and
+ // commits the write in the same critical section as the re-validation.
+ return upsertGrant(
+ {
+ recipeNamespace,
+ recipeName,
+ capabilityFamily: capabilityFamily as PluginWorkloadSdkFamily,
+ provider,
+ allowedModels,
+ allowedEventTypes,
+ allowedTargetRefs,
+ allowedUserRefs,
+ allowedCallers,
+ quotaLimits,
+ modelPolicies,
+ promptTargets,
+ defaultTargetRef: defaultTargetRef || undefined,
+ },
+ (req as UiAuthedRequest).adminAuth!.sub,
+ db
+ )
+ })
+ } catch (err) {
+ if (err instanceof GrantModelGateError) {
+ res.status(400).json(err.body)
+ return
+ }
+ throw err
}
-
- const grant = await upsertGrant(
- {
- recipeNamespace,
- recipeName,
- capabilityFamily: capabilityFamily as PluginWorkloadSdkFamily,
- provider,
- allowedModels,
- allowedEventTypes,
- allowedTargetRefs,
- allowedUserRefs,
- allowedCallers,
- quotaLimits,
- modelPolicies,
- promptTargets,
- defaultTargetRef: defaultTargetRef || undefined,
- },
- (req as UiAuthedRequest).adminAuth!.sub
- )
// Grant PERSISTED: NOW emit any Pieza D tolerations (never before the upsert
// lands, so a failed upsert leaves no audit record — mini-spec 01).
for (const event of pendingGrantTolerations) emitIncoherenceTolerated(event)
diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.ts
index 30e83eecc..741031b39 100644
--- a/control-api/src/services/pluginWorkloadSdkDb.ts
+++ b/control-api/src/services/pluginWorkloadSdkDb.ts
@@ -466,9 +466,25 @@ export interface UpsertGrantParams {
export async function upsertGrant(
params: UpsertGrantParams,
- operatorSub: string
+ operatorSub: string,
+ // When the caller already runs inside a carrier transaction (the grant
+ // write-gate, which holds the per-model advisory locks — R1-H3 fase 2), the
+ // upsert MUST reuse that same transaction so the recipe lock is taken AFTER
+ // the model locks (global order: `llm-model:*` before `plugin_workload_sdk:*`)
+ // and the enabled-ness revalidation + the write commit atomically. Every other
+ // caller passes no `db` and gets its own transaction, exactly as before.
+ db?: DbClient
): Promise<PluginWorkloadSdkGrant> {
- return withTransaction(async db => {
+ if (db) return upsertGrantInTransaction(params, operatorSub, db)
+ return withTransaction(inner => upsertGrantInTransaction(params, operatorSub, inner))
+}
+
+async function upsertGrantInTransaction(
+ params: UpsertGrantParams,
+ operatorSub: string,
+ db: DbClient
+): Promise<PluginWorkloadSdkGrant> {
+ {
// All capability families for a recipe share one lock. A family-scoped
// lock permits an SDK-only revoke to race an upsert for the other family.
const recipeLock = `plugin_workload_sdk:${params.recipeNamespace}/${params.recipeName}`
@@ -614,13 +630,20 @@ export async function upsertGrant(
]
await appendControlApiPermissionEventsInTransaction(db, { operatorSub, changes })
return grant
- })
+ }
}
-export async function listGrants(filter?: {
- recipeNamespace?: string
- recipeName?: string
-}): Promise<PluginWorkloadSdkGrant[]> {
+export async function listGrants(
+ filter?: {
+ recipeNamespace?: string
+ recipeName?: string
+ },
+ // Accepts a transaction client so the grant write-gate can read the stored
+ // grant (Pieza D no-worsening context) on the SAME connection that holds the
+ // model advisory locks — no extra pool checkout under the lock (adenda A3).
+ // Defaults to the global pool for every other (unlocked) caller.
+ db: Pick<DbClient, 'query'> = pool
+): Promise<PluginWorkloadSdkGrant[]> {
const clauses: string[] = []
const values: unknown[] = []
if (filter?.recipeNamespace) {
@@ -632,7 +655,7 @@ export async function listGrants(filter?: {
clauses.push(`recipe_name = $${values.length}`)
}
const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : ''
- const result = await pool.query(
+ const result = await db.query(
`SELECT * FROM plugin_workload_sdk_grants ${where}
ORDER BY recipe_namespace, recipe_name, capability_family`,
values
diff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
index 1d5634253..15d164d2d 100644
--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts
+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
@@ -10,13 +10,23 @@ vi.mock('../src/services/rateLimiterService.js', () => ({
checkAndIncrement: vi.fn(),
}))
-vi.mock('../src/db.js', () => ({
- pool: {
+vi.mock('../src/db.js', () => {
+ // The grant upsert route now composes its enabled-ness gate + the upsert inside
+ // ONE carrier transaction (R1-H3 fase 2). `withTransaction` must invoke the
+ // callback with the (mocked) pool so the gate's `listEnabledModelsWithStaleFor
+ // Provider(provider, db)` read still hits `pool.query`; the per-model advisory
+ // lock helpers are no-op in a mocked DB.
+ const pool = {
query: vi.fn().mockResolvedValue({ rows: [], rowCount: 0 }),
connect: vi.fn(),
- },
- withTransaction: vi.fn(),
-}))
+ }
+ return {
+ pool,
+ withTransaction: vi.fn(async (cb: (db: typeof pool) => unknown) => cb(pool)),
+ advisoryLockModelNames: vi.fn().mockResolvedValue(undefined),
+ boundCarrierTransactionIdleTimeout: vi.fn().mockResolvedValue(undefined),
+ }
+})
vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {
const actual = await vi.importActual<typeof import('../src/services/pluginWorkloadSdkDb.js')>(
@@ -257,7 +267,8 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
expect.objectContaining({ targetRef: 'openai-fallback', provider: 'openai' }),
]),
}),
- '11111111-1111-4111-8111-111111111111'
+ '11111111-1111-4111-8111-111111111111',
+ expect.anything() // carrier transaction client (R1-H3 fase 2)
)
expect(JSON.stringify(vi.mocked(sdkDb.upsertGrant).mock.calls)).not.toContain('secret-value')
})
@@ -285,7 +296,8 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
expect(res.status).toBe(200)
expect(sdkDb.upsertGrant).toHaveBeenCalledWith(
expect.objectContaining({ promptTargets: targets }),
- '11111111-1111-4111-8111-111111111111'
+ '11111111-1111-4111-8111-111111111111',
+ expect.anything() // carrier transaction client (R1-H3 fase 2)
)
})
@@ -343,7 +355,8 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
expect(res.status).toBe(200)
expect(sdkDb.upsertGrant).toHaveBeenCalledWith(
expect.objectContaining({ provider: 'vertex' }),
- '11111111-1111-4111-8111-111111111111'
+ '11111111-1111-4111-8111-111111111111',
+ expect.anything() // carrier transaction client (R1-H3 fase 2)
)
})
@@ -410,7 +423,8 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
expect(res.status).toBe(200)
expect(sdkDb.upsertGrant).toHaveBeenCalledWith(
expect.objectContaining({ capabilityFamily: 'clientNotifications', provider: undefined }),
- '11111111-1111-4111-8111-111111111111'
+ '11111111-1111-4111-8111-111111111111',
+ expect.anything() // carrier transaction client (R1-H3 fase 2)
)
})
@@ -472,7 +486,8 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
allowedCallers: ['api'],
quotaLimits: { maxRequestsPerRun: 10 },
}),
- '11111111-1111-4111-8111-111111111111'
+ '11111111-1111-4111-8111-111111111111',
+ expect.anything() // carrier transaction client (R1-H3 fase 2)
)
})
diff --git a/control-api/test/routes.llmModelGrantRace.realPostgres.integration.test.ts b/control-api/test/routes.llmModelGrantRace.realPostgres.integration.test.ts
new file mode 100644
index 000000000..dafa8b0b2
--- /dev/null
+++ b/control-api/test/routes.llmModelGrantRace.realPostgres.integration.test.ts
@@ -0,0 +1,296 @@
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { randomBytes } from 'node:crypto'
+import { Pool } from 'pg'
+import request from 'supertest'
+
+// R1-H3 fase 2 (llm-model reductor ↔ grant upsert) — regression test for the
+// TOCTOU race the per-MODEL advisory lock closes on the grant seam (mini-spec
+// "Fase 2 (grant)" / T3 / T4). This seam is PG-ONLY (no K8s write under the lock),
+// so — per adenda A4 — the race is driven by TWO REAL Postgres transactions with a
+// commit order the TEST controls, and the advisory lock's blocking semantics give
+// the determinism (no production test hook).
+//
+// The reductor side is a raw transaction that calls the REAL producers exactly as
+// `gatedReduce` does — take `advisoryLockModelName`, compute the (empty) impact via
+// the REAL `computeModelImpact`, `deleteAllowedModel` — then PAUSES before COMMIT so
+// the grant can race into the window. The grant side is the REAL admin route over
+// HTTP. Fixtures come from real producers (T1): the allowlist row from
+// `createAllowedModel`, the grant from the real POST handler + `upsertGrant`.
+//
+// Run against the parent commit (9dfd4a27, fase 1 only — the grant upsert takes NO
+// model lock), the FIRST case fails BY ASSERTION: the grant reads the model as still
+// enabled (the reductor's delete is uncommitted), commits, and then the reductor
+// deletes the model — leaving a grant that references a deleted model (a dangling
+// reference) and answering 200 instead of 400. Skipped without
+// CONTROL_API_REAL_PG_ADMIN_URL.
+
+const mockVerifyAdminToken = vi.fn()
+const mockIsAdminTokenRevoked = vi.fn()
+const mockFindAdminById = vi.fn()
+
+vi.mock('../src/utils/auth/adminAuthToken.js', () => ({
+ verifyAdminToken: (...args: unknown[]) => mockVerifyAdminToken(...args),
+}))
+
+vi.mock('../src/services/adminAuthService.js', () => ({
+ findAdminById: (...args: unknown[]) => mockFindAdminById(...args),
+ isAdminTokenRevoked: (...args: unknown[]) => mockIsAdminTokenRevoked(...args),
+}))
+
+const ADMIN_CLAIMS = {
+ sub: '00000000-0000-4000-8000-000000000001',
+ typ: 'user' as const,
+ role: 'admin' as const,
+ jti: 'admin-jti',
+ exp: Math.floor(Date.now() / 1000) + 3600,
+}
+const ACTIVE_ADMIN = {
+ id: ADMIN_CLAIMS.sub,
+ username: 'admin',
+ email: '[email protected]',
+ passwordHash: 'hash',
+ sessionVersion: 0,
+ role: 'admin' as const,
+ status: 'active' as const,
+ failedAttempts: 0,
+ lockedUntil: null,
+}
+const COOKIE = 'control_ui_admin_session=admin-token'
+
+// A provider/model/credentialSlot triple proven valid by the unit suite
+// (`routes.adminPluginWorkloadSdk.test.ts`). The model is both a promptTarget
+// (so the enabled-ness gate evaluates it) AND in `allowed_models` (so the reductor
+// enumerates it by name).
+const PROVIDER = 'zai'
+const MODEL = 'glm-4.7'
+const CREDENTIAL_SLOT = 'zai-api-key'
+const TARGET_REF = 'primary-zai'
+const RECIPE_NS = 'sandbox-recipes'
+const RECIPE_NAME = 'sdk-recipe'
+const GRANTS_PATH = '/api/v1/admin/plugin-workload-sdk/grants'
+
+const grantBody = {
+ recipeNamespace: RECIPE_NS,
+ recipeName: RECIPE_NAME,
+ capabilityFamily: 'promptBridge',
+ provider: PROVIDER,
+ allowedModels: [MODEL],
+ promptTargets: [
+ { targetRef: TARGET_REF, provider: PROVIDER, model: MODEL, credentialSlot: CREDENTIAL_SLOT },
+ ],
+ defaultTargetRef: TARGET_REF,
+ allowedCallers: ['api'],
+}
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+
+describeRealPostgres('llm-model reductor ↔ grant upsert serialization (R1-H3 fase 2)', () => {
+ const database = `control_api_grant_model_race_${randomBytes(6).toString('hex')}`
+ const connectionString = databaseUrl(
+ adminUrl ?? 'postgresql://[email protected]/postgres',
+ database
+ )
+ const previousPgEnv = process.env.CONTROL_API_PG_CONNECTION_STRING
+
+ let adminPool: Pool
+ let corePool: Pool
+ // A dedicated pool so the raw reductor transaction holds ONE connection (and its
+ // session-scoped advisory lock) independent of the app's module pool. Advisory
+ // locks are database-global, so a lock taken here blocks the app's grant upsert.
+ let racePool: Pool
+ // Loaded dynamically AFTER the env points the module pool at the test DB.
+ let mod: {
+ createApp: (gateway: unknown) => import('express').Express
+ config: typeof import('../src/config.js').config
+ pool: import('../src/db.js').DbClient
+ createAllowedModel: typeof import('../src/services/llmAllowedModels.js').createAllowedModel
+ deleteAllowedModel: typeof import('../src/services/llmAllowedModels.js').deleteAllowedModel
+ advisoryLockModelName: typeof import('../src/db.js').advisoryLockModelName
+ computeModelImpact: typeof import('../src/services/llmModelImpact.js').computeModelImpact
+ modelImpactHasReferences: typeof import('../src/services/llmModelImpact.js').modelImpactHasReferences
+ modelImpactSourcesFromGatewayTx: typeof import('../src/services/llmModelImpact.js').modelImpactSourcesFromGatewayTx
+ listGrants: typeof import('../src/services/pluginWorkloadSdkDb.js').listGrants
+ MockGateway: typeof import('./mockGateway.js').MockGateway
+ }
+ let hostNamespaces: string[]
+
+ type DbClientCast = import('../src/db.js').DbClient
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)
+
+ process.env.CONTROL_API_PG_CONNECTION_STRING = connectionString
+
+ const dbMod = await import('../src/db.js')
+ corePool = dbMod.pool as unknown as Pool
+ corePool.on('error', () => {})
+ const migratePool = new Pool({ connectionString })
+ await dbMod.initDb({ connect: () => migratePool.connect() })
+ await migratePool.end()
+
+ racePool = new Pool({ connectionString })
+ racePool.on('error', () => {})
+
+ const appMod = await import('../src/app.js')
+ const configMod = await import('../src/config.js')
+ const allowlistMod = await import('../src/services/llmAllowedModels.js')
+ const impactMod = await import('../src/services/llmModelImpact.js')
+ const sdkDbMod = await import('../src/services/pluginWorkloadSdkDb.js')
+ const { MockGateway } = await import('./mockGateway.js')
+ mod = {
+ createApp: appMod.createApp as never,
+ config: configMod.config,
+ pool: dbMod.pool,
+ createAllowedModel: allowlistMod.createAllowedModel,
+ deleteAllowedModel: allowlistMod.deleteAllowedModel,
+ advisoryLockModelName: dbMod.advisoryLockModelName,
+ computeModelImpact: impactMod.computeModelImpact,
+ modelImpactHasReferences: impactMod.modelImpactHasReferences,
+ modelImpactSourcesFromGatewayTx: impactMod.modelImpactSourcesFromGatewayTx,
+ listGrants: sdkDbMod.listGrants,
+ MockGateway,
+ }
+ // Same single source of truth for "where Hosts live" the reductor route uses.
+ hostNamespaces = Array.from(new Set([mod.config.hostsNamespace, mod.config.namespace]))
+ }, 60_000)
+
+ afterAll(async () => {
+ if (previousPgEnv === undefined) delete process.env.CONTROL_API_PG_CONNECTION_STRING
+ else process.env.CONTROL_API_PG_CONNECTION_STRING = previousPgEnv
+ await racePool?.end().catch(() => {})
+ await corePool?.end().catch(() => {})
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ await adminPool.end()
+ })
+
+ beforeEach(async () => {
+ mockVerifyAdminToken.mockReset().mockReturnValue(ADMIN_CLAIMS)
+ mockIsAdminTokenRevoked.mockReset().mockResolvedValue(false)
+ mockFindAdminById.mockReset().mockResolvedValue(ACTIVE_ADMIN)
+ await mod.pool.query('DELETE FROM plugin_workload_sdk_grants')
+ await mod.pool.query('DELETE FROM llm_allowed_models')
+ })
+
+ afterEach(async () => {
+ await mod.pool.query('DELETE FROM plugin_workload_sdk_grants')
+ await mod.pool.query('DELETE FROM llm_allowed_models')
+ })
+
+ async function seedEnabledModel(): Promise<string> {
+ const row = await mod.createAllowedModel(
+ { provider: PROVIDER, model: MODEL, enabled: true },
+ 'test-actor'
+ )
+ return row.id
+ }
+
+ async function grantRowCount(): Promise<number> {
+ const rows = await mod.listGrants({ recipeNamespace: RECIPE_NS, recipeName: RECIPE_NAME })
+ return rows.length
+ }
+
+ async function modelRow(id: string): Promise<{ enabled: boolean } | undefined> {
+ const res = await mod.pool.query('SELECT enabled FROM llm_allowed_models WHERE id = $1', [id])
+ return res.rows[0] as { enabled: boolean } | undefined
+ }
+
+ // Wait until the grant row is COMMITTED (parent ordering — the grant slipped in),
+ // or the budget elapses (child ordering — the grant is BLOCKED on the model lock).
+ async function waitForGrantOrBudget(budgetMs: number): Promise<void> {
+ const deadline = Date.now() + budgetMs
+ while (Date.now() < deadline) {
+ if ((await grantRowCount()) > 0) return
+ await new Promise(r => setTimeout(r, 25))
+ }
+ }
+
+ it('reductor commits first → grant is rejected under the model lock (no dangling grant)', async () => {
+ const id = await seedEnabledModel()
+ const gateway = new mod.MockGateway()
+ const app = mod.createApp(gateway)
+
+ // REDUCTOR as a raw transaction (adenda A4). Faithfully mirrors gatedReduce
+ // via the real producers, then PAUSES before COMMIT holding the model lock.
+ const rClient = await racePool.connect()
+ let grantDone!: Promise<request.Response>
+ try {
+ await rClient.query('BEGIN')
+ await mod.advisoryLockModelName(rClient as unknown as DbClientCast, MODEL)
+ const impact = await mod.computeModelImpact(
+ PROVIDER,
+ MODEL,
+ mod.modelImpactSourcesFromGatewayTx(
+ gateway,
+ hostNamespaces,
+ rClient as unknown as DbClientCast
+ )
+ )
+ // The grant has not committed yet → the reductor sees NO reference.
+ expect(mod.modelImpactHasReferences(impact)).toBe(false)
+ await mod.deleteAllowedModel(id, 'test-reductor', rClient as unknown as DbClientCast)
+ // The DELETE is now staged but UNCOMMITTED, and the reductor holds the lock.
+
+ // Fire the grant upsert over the REAL route while the reductor holds the lock.
+ grantDone = Promise.resolve(
+ request(app).post(GRANTS_PATH).set('Cookie', COOKIE).send(grantBody)
+ )
+
+ // Parent: the grant takes no lock → it reads the (uncommitted-deleted) model as
+ // enabled and COMMITS → the row appears, we stop waiting. Child: the grant
+ // BLOCKS on the model lock → no row → we wait the full budget.
+ await waitForGrantOrBudget(1_500)
+
+ await rClient.query('COMMIT') // reductor wins: model deleted, lock released
+ } finally {
+ rClient.release()
+ }
+
+ const grantRes = await grantDone
+
+ // Observable final state (T4). Child (fixed): the grant lost — it re-read the
+ // model under the lock, found it deleted, and 400'd; nothing dangling. Parent
+ // (fase 1 only): the grant was created against a now-deleted model — a dangling
+ // reference — and answered 200; these assertions FAIL there.
+ expect(grantRes.status).toBe(400)
+ expect(grantRes.body.error).toBe('model_not_allowed')
+ expect(await modelRow(id)).toBeUndefined() // reductor's delete stands
+ expect(await grantRowCount()).toBe(0) // no grant references the deleted model
+ }, 30_000)
+
+ it('grant commits first → reductor sees it and 409s (no dangling reference)', async () => {
+ const id = await seedEnabledModel()
+ const gateway = new mod.MockGateway()
+ const app = mod.createApp(gateway)
+
+ const grantRes = await request(app).post(GRANTS_PATH).set('Cookie', COOKIE).send(grantBody)
+ expect(grantRes.status).toBe(200)
+
+ const reductorRes = await request(app)
+ .delete(`/api/v1/admin/llm-models/${id}`)
+ .set('Cookie', COOKIE)
+
+ expect(reductorRes.status).toBe(409)
+ expect(reductorRes.body.error).toBe('model_in_use')
+ expect(
+ (reductorRes.body.impact.grantsAffected as Array<{ recipeName: string }>).map(
+ g => g.recipeName
+ )
+ ).toContain(RECIPE_NAME)
+ expect((await modelRow(id))?.enabled).toBe(true) // model untouched
+ expect(await grantRowCount()).toBe(1) // grant intact
+ }, 30_000)
+})