Skip to content

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

TypeScript

feat(plugin-sdk): platform per-minute ENV rate limits, deprecate per-run quotas (#348)

Alfredo Lopez4f58b1329fa5
diff --git a/charts/clerum-crds/crds/workflowrecipe.yaml b/charts/clerum-crds/crds/workflowrecipe.yaml
index 66841ad7a..c12a9d897 100644
--- a/charts/clerum-crds/crds/workflowrecipe.yaml
+++ b/charts/clerum-crds/crds/workflowrecipe.yaml
@@ -1707,6 +1707,11 @@ spec:
maxRequestsPerRun:
type: integer
minimum: 1
+ description: >-
+ DEPRECATED — accepted for compatibility but no
+ longer enforced. Platform per-minute rate limits
+ apply instead. Scheduled for removal in a future
+ version.
maxRequestContentBytes:
type: integer
minimum: 1
@@ -1757,6 +1762,11 @@ spec:
maxNotificationsPerRun:
type: integer
minimum: 1
+ description: >-
+ DEPRECATED — notifications per-run quota is
+ accepted for compatibility but no longer enforced.
+ Platform per-minute rate limits apply instead.
+ Scheduled for removal in a future version.
maxNotificationsPerMinute:
type: integer
minimum: 1
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index c47b8b39f..e874f5db2 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.441",
+ "version": "0.1.442",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.441",
+ "version": "0.1.442",
"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 6c2fdadf9..6492eff89 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.441",
+ "version": "0.1.442",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/config.ts b/control-api/src/config.ts
index 033cb2afe..5e6e7aeac 100644
--- a/control-api/src/config.ts
+++ b/control-api/src/config.ts
@@ -132,6 +132,14 @@ type Config = {
approvalRlExternalPerMin: number
oauthBrokerRlPerMin: number
adminPublicTokenRlPerMin: number
+ // Plugin Workload SDK platform rate limits (issue #348): per-minute
+ // ceilings on the plugin abuse surface (data-path + pre-auth). Platform
+ // protection, not per-service business quotas — usage/cost stays governed
+ // by Token Budgets.
+ pluginSdkNotificationsRlPerMin: number
+ pluginSdkPromptBridgeRlPerMin: number
+ pluginSdkRequestBucketRlPerMin: number
+ pluginSdkPreauthRlPerMin: number
// Stateless-agent wake endpoint: per-host wake rate limit + server-side
// coalescence window for the wake-annotation projection.
hostWakeRlPerMin: number
@@ -715,6 +723,23 @@ export const config: Config = {
approvalRlExternalPerMin: Number(process.env.APPROVAL_RL_EXTERNAL_PER_MIN || 60),
oauthBrokerRlPerMin: Number(process.env.CONTROL_API_OAUTH_BROKER_RL_PER_MIN || 60),
adminPublicTokenRlPerMin: Number(process.env.CONTROL_API_ADMIN_PUBLIC_TOKEN_RL_PER_MIN || 20),
+ // Plugin Workload SDK platform rate limits (issue #348). Parsed via
+ // positiveIntegerFromEnv so invalid operator config (non-integer, zero,
+ // negative) fails loud at boot instead of running with NaN limits, which
+ // would effectively fail open.
+ pluginSdkNotificationsRlPerMin: positiveIntegerFromEnv(
+ 'CONTROL_API_PLUGIN_SDK_NOTIFICATIONS_PER_MIN',
+ 200
+ ),
+ pluginSdkPromptBridgeRlPerMin: positiveIntegerFromEnv(
+ 'CONTROL_API_PLUGIN_SDK_PROMPTBRIDGE_PER_MIN',
+ 180
+ ),
+ pluginSdkRequestBucketRlPerMin: positiveIntegerFromEnv(
+ 'CONTROL_API_PLUGIN_SDK_REQUEST_BUCKET_PER_MIN',
+ 600
+ ),
+ pluginSdkPreauthRlPerMin: positiveIntegerFromEnv('CONTROL_API_PLUGIN_SDK_PREAUTH_PER_MIN', 600),
// Default derived from the wake mechanism's worst case, not picked ad hoc.
// rpc-proxy's wake-and-hold loop re-triggers POST /rpc/hosts/:hostRef/wake
// every wakeRetriggerMs=15000 for up to wakeMaxHoldMs=90000 (defaults in
diff --git a/control-api/src/middleware/pluginWorkloadSdkRateLimits.ts b/control-api/src/middleware/pluginWorkloadSdkRateLimits.ts
index ca33a0067..1b96b531a 100644
--- a/control-api/src/middleware/pluginWorkloadSdkRateLimits.ts
+++ b/control-api/src/middleware/pluginWorkloadSdkRateLimits.ts
@@ -1,4 +1,5 @@
import type { RequestHandler } from 'express'
+import { config } from '../config.js'
import type { UiAuthedRequest } from './controlUIAuth.js'
import { rateLimitMiddleware } from './rateLimitMiddleware.js'
@@ -13,7 +14,8 @@ export function createPluginWorkloadSdkRequestRateLimit(): RequestHandler {
// Keep the shared authenticated bucket above the provider-attempt burst
// budget. Credential-ticket issuance/introspection have their own tighter
// bucket; status and notification traffic must not starve each other.
- maxPerMinute: 600,
+ // ENV-tunable platform limit (issue #348): CONTROL_API_PLUGIN_SDK_REQUEST_BUCKET_PER_MIN.
+ maxPerMinute: config.pluginSdkRequestBucketRlPerMin,
getBucketKey: req => {
const claims = req.mcpHostJwt
if (!claims) return 'plugin_workload_sdk_request:unauthenticated'
@@ -26,7 +28,7 @@ export function createPluginWorkloadSdkRequestRateLimit(): RequestHandler {
export function createPluginWorkloadSdkInternalRateLimit(): RequestHandler {
return rateLimitMiddleware({
bucketType: 'plugin_workload_sdk_internal',
- maxPerMinute: 120,
+ maxPerMinute: 120, // not ENV: not part of the plugin abuse surface (issue #348)
getBucketKey: req => {
const claims = req.internalControl
if (!claims) return 'plugin_workload_sdk_internal:unauthenticated'
@@ -44,7 +46,7 @@ export function createPluginWorkloadSdkInternalRateLimit(): RequestHandler {
export function createPluginWorkloadSdkAdminRateLimit(): RequestHandler {
return rateLimitMiddleware({
bucketType: 'plugin_workload_sdk_admin',
- maxPerMinute: 120,
+ maxPerMinute: 120, // not ENV: not part of the plugin abuse surface (issue #348)
getBucketKey: req => {
const sub = (req as UiAuthedRequest).adminAuth?.sub
return `plugin_workload_sdk_admin:${sub || 'unauthenticated'}`
diff --git a/control-api/src/routes/admin/pluginWorkloadSdk.ts b/control-api/src/routes/admin/pluginWorkloadSdk.ts
index 2800dd4f6..622b374fc 100644
--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts
+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts
@@ -116,9 +116,15 @@ function parseModelArray(value: unknown, field: string, res: Response): string[]
return values
}
-const QUOTA_LIMIT_KEYS: ReadonlyArray<keyof PluginWorkloadSdkQuotaLimits> = [
+// Issue #348: per-run quota keys are deprecated. They remain accepted on the
+// wire for compatibility and are validated with the same shape rules, but they
+// are stripped before persistence — only per-minute/platform limits are stored.
+const DEPRECATED_QUOTA_LIMIT_KEYS: ReadonlyArray<keyof PluginWorkloadSdkQuotaLimits> = [
'maxRequestsPerRun',
'maxNotificationsPerRun',
+]
+
+const ACTIVE_QUOTA_LIMIT_KEYS: ReadonlyArray<keyof PluginWorkloadSdkQuotaLimits> = [
'maxInvocationsPerMinute',
'maxNotificationsPerMinute',
'maxOutputTokens',
@@ -131,14 +137,18 @@ function parseQuotaLimits(value: unknown, res: Response): PluginWorkloadSdkQuota
return null
}
const limits: PluginWorkloadSdkQuotaLimits = {}
- for (const key of QUOTA_LIMIT_KEYS) {
+ for (const key of [...DEPRECATED_QUOTA_LIMIT_KEYS, ...ACTIVE_QUOTA_LIMIT_KEYS]) {
const raw = value[key]
if (raw === undefined) continue
if (typeof raw !== 'number' || !Number.isInteger(raw) || raw < 1) {
res.status(400).json({ error: `quotaLimits.${key} must be a positive integer` })
return null
}
- limits[key] = raw
+ // Deprecated keys are validated (malformed input still 400s) but never
+ // assigned, so they are not persisted (issue #348).
+ if ((ACTIVE_QUOTA_LIMIT_KEYS as readonly string[]).includes(key)) {
+ limits[key] = raw
+ }
}
return limits
}
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 8ccbe28d3..f5c03695c 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
@@ -1,5 +1,6 @@
import { type NextFunction, type Request, type Response, Router } from 'express'
import { rateLimit } from 'express-rate-limit'
+import { config } from '../../config.js'
import { pool } from '../../db.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import { requireMcpHostJwt } from '../../middleware/mcpHostJwtAuth.js'
@@ -626,7 +627,9 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
'/mcp-host/plugin-workload-sdk',
rateLimit({
windowMs: 60_000,
- limit: 600,
+ // ENV-tunable pre-auth flood guard (issue #348):
+ // CONTROL_API_PLUGIN_SDK_PREAUTH_PER_MIN.
+ limit: config.pluginSdkPreauthRlPerMin,
standardHeaders: 'draft-8',
legacyHeaders: false,
message: { error: 'Too Many Requests', retryable: true },
diff --git a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts b/control-api/src/services/pluginWorkloadSdkAuthorizer.ts
index 1ee5e2e90..f209c1a65 100644
--- a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts
+++ b/control-api/src/services/pluginWorkloadSdkAuthorizer.ts
@@ -25,7 +25,7 @@ import {
recordInvocation,
reviveFailedSdkInvocation,
} from './pluginWorkloadSdkInvocationAuditor.js'
-import { checkRateLimit, consumeQuota } from './pluginWorkloadSdkQuotaTracker.js'
+import { checkRateLimit } from './pluginWorkloadSdkQuotaTracker.js'
// ─── Plugin Workload SDK — authorizer (plan §2.2) ────────────────────────
// Authorization pipeline for promptBridge and clientNotifications requests
@@ -467,22 +467,9 @@ async function authorizePromptBridgeInner(
await transitionToFailed()
return deny(rate.error, rate.message)
}
-
- // Period quota is charged once per logical idempotent invocation. A
- // failed provider retry is a new physical attempt (rate-limited above),
- // not a second logical request that should consume the same run budget.
- if (recorded.kind !== 'replay') {
- const quota = await consumeQuota(
- claims.recipeNamespace,
- claims.recipeName,
- 'promptBridge',
- grant
- )
- if (!quota.ok) {
- await transitionToFailed()
- return deny(quota.error, quota.message)
- }
- }
+ // The former per-run quota leg (consumeQuota) was deleted here (issue
+ // #348): deprecated per-run caps are ignored; only the per-minute
+ // platform rate limit above gates the invocation.
} catch (error) {
try {
await transitionToFailed()
@@ -812,21 +799,11 @@ async function authorizeClientNotificationInner(
return deny(rate.error, rate.message)
}
- const quota = await consumeQuota(
- claims.recipeNamespace,
- claims.recipeName,
- 'clientNotifications',
- grant
- )
- if (!quota.ok) {
- await markInvocationStatus(recorded.invocation.id, 'failed', {
- recipeNamespace: claims.recipeNamespace,
- recipeName: claims.recipeName,
- })
- return deny(quota.error, quota.message)
- }
+ // The former per-run quota leg (consumeQuota) was deleted here (issue
+ // #348): deprecated per-run caps are ignored; only the per-minute platform
+ // rate limit above gates the notification.
- // Revive a previously-failed invocation that has now passed quota.
+ // Revive a previously-failed invocation that has now passed the rate limit.
if (recorded.kind === 'replay') {
await markInvocationStatus(recorded.invocation.id, 'accepted', {
recipeNamespace: claims.recipeNamespace,
diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.ts
index b376e3fb2..920f57387 100644
--- a/control-api/src/services/pluginWorkloadSdkDb.ts
+++ b/control-api/src/services/pluginWorkloadSdkDb.ts
@@ -2028,37 +2028,14 @@ export async function prunePluginWorkloadSdkExpiredIdempotency(): Promise<number
})
}
-// ─── Quota counters ──────────────────────────────────────────────────────
-
-/** Sentinel period for eager SDK traffic before any workflow run exists. */
-export const PLUGIN_WORKLOAD_SDK_EAGER_QUOTA_PERIOD = new Date(0)
-
-/**
- * Resolve the quota counter bucket for per-run limits. Uses the active
- * workflow run's start time when one exists; otherwise the eager sentinel.
- *
- * When a run is created concurrently with the first SDK call, the run row may
- * not be visible yet — callers fall back to the eager sentinel until the next
- * attempt sees the committed run.
- */
-export async function resolveQuotaPeriodStart(
- recipeNamespace: string,
- recipeName: string
-): Promise<Date> {
- const result = await pool.query(
- `SELECT COALESCE(started_at, created_at) AS period_start
- FROM workflow_runs
- WHERE recipe_namespace = $1
- AND recipe_name = $2
- AND phase NOT IN ('Succeeded', 'Failed', 'Canceled')
- ORDER BY COALESCE(started_at, created_at) DESC
- LIMIT 1`,
- [recipeNamespace, recipeName]
- )
- const row = result.rows[0] as { period_start?: Date | string } | undefined
- if (!row?.period_start) return PLUGIN_WORKLOAD_SDK_EAGER_QUOTA_PERIOD
- return new Date(row.period_start)
-}
+// ─── Quota counters (historical-only, issue #348) ────────────────────────
+// Per-run/period quota enforcement was removed (issue #348): nothing writes
+// plugin_workload_sdk_quota_counters anymore (the enforcement writers
+// consumePeriodQuota / resolveQuotaPeriodStart / getPeriodQuotaUsage and the
+// eager epoch sentinel were deleted so a future re-wire cannot resurrect the
+// never-resetting epoch bucket). Existing rows — including stale epoch
+// sentinels — are inert historical data; getQuotaCounters keeps serving them
+// to the admin read path. Hard removal of the table is a separate follow-up.
export interface QuotaCounterRow {
recipeNamespace: string
@@ -2089,106 +2066,6 @@ export async function getQuotaCounters(
}))
}
-export async function getPeriodQuotaUsage(
- recipeNamespace: string,
- recipeName: string,
- family: PluginWorkloadSdkFamily,
- periodStart: Date
-): Promise<number> {
- const column = family === 'promptBridge' ? 'prompt_bridge_count' : 'notification_count'
- const result = await pool.query(
- `SELECT ${column} AS usage_count
- FROM plugin_workload_sdk_quota_counters
- WHERE recipe_namespace = $1 AND recipe_name = $2 AND period_start = $3`,
- [recipeNamespace, recipeName, periodStart]
- )
- const row = result.rows[0] as { usage_count?: number | string } | undefined
- return Number(row?.usage_count ?? 0)
-}
-
-/**
- * Atomically consume one unit of period quota. The conditional UPDATE only
- * increments while the post-increment count stays within `limit`, so two
- * concurrent calls can never both pass a remaining-1 budget.
- *
- * `foldEagerUsage` (default `false`) folds the eager-sentinel usage into the
- * same atomic conditional — when set, the run-period decision becomes
- * `runCount + 1 + eagerUsage <= limit`, where `eagerUsage` is the count
- * already booked under the eager sentinel period
- * (`PLUGIN_WORKLOAD_SDK_EAGER_QUOTA_PERIOD`). That eager usage is read with a
- * correlated subquery INSIDE the same conditional-upsert statement, so there
- * is no TOCTOU window: two concurrent run-period consumers can never both pass
- * a budget the eager usage already exhausted.
- *
- * The eager-period `$6` bind is appended to the parameter array ONLY when
- * `foldEagerUsage` is `true`. When it is `false` the eager-usage SQL fragment
- * is the literal `'0'` and never references `$6`, so binding it would raise a
- * parameter-count mismatch; the conditional bind keeps both paths valid.
- *
- * Returns false when the limit is hit (caller maps to quota_exceeded,
- * retryable=false).
- */
-export async function consumePeriodQuota(
- recipeNamespace: string,
- recipeName: string,
- family: PluginWorkloadSdkFamily,
- limit: number,
- periodStart: Date = PLUGIN_WORKLOAD_SDK_EAGER_QUOTA_PERIOD,
- foldEagerUsage = false
-): Promise<boolean> {
- const column = family === 'promptBridge' ? 'prompt_bridge_count' : 'notification_count'
- // When `foldEagerUsage` is set, the run-period decision must account for
- // usage already booked under the eager sentinel (so the run cap isn't
- // doubled). We read that eager usage with a correlated subquery INSIDE the
- // same conditional-upsert statement, eliminating the read-then-consume
- // TOCTOU: two concurrent run-period consumers evaluate the gate against the
- // committed counter row under the ON CONFLICT row lock, so they cannot both
- // pass a budget the eager usage already exhausted.
- const eagerUsageExpr = foldEagerUsage
- ? `COALESCE((
- SELECT eager.${column}
- FROM plugin_workload_sdk_quota_counters eager
- WHERE eager.recipe_namespace = $1
- AND eager.recipe_name = $2
- AND eager.period_start = $6
- ), 0)`
- : '0'
- // Single conditional upsert. INSERT path (fresh run period → count becomes 1)
- // is gated by the `SELECT ... WHERE`; UPDATE path (existing row) is gated by
- // the `ON CONFLICT ... WHERE` on the post-increment count. Both fold in the
- // live eager usage so the decision is atomic.
- //
- // The $6 (eager period) bind is appended ONLY when foldEagerUsage is set —
- // otherwise eagerUsageExpr is the literal '0' and the SQL never references
- // $6, so binding it would raise "bind message supplies 6 parameters, but
- // prepared statement requires 5" and break every quota consumption.
- const params: Array<string | number | Date> = [
- recipeNamespace,
- recipeName,
- periodStart,
- family,
- limit,
- ]
- if (foldEagerUsage) {
- params.push(PLUGIN_WORKLOAD_SDK_EAGER_QUOTA_PERIOD)
- }
- const result = await pool.query(
- `INSERT INTO plugin_workload_sdk_quota_counters
- (recipe_namespace, recipe_name, period_start, prompt_bridge_count, notification_count)
- SELECT $1, $2, $3,
- CASE WHEN $4 = 'promptBridge' THEN 1 ELSE 0 END,
- CASE WHEN $4 = 'clientNotifications' THEN 1 ELSE 0 END
- WHERE 1 + ${eagerUsageExpr} <= $5
- ON CONFLICT (recipe_namespace, recipe_name, period_start)
- DO UPDATE SET ${column} = plugin_workload_sdk_quota_counters.${column} + 1,
- last_updated = now()
- WHERE plugin_workload_sdk_quota_counters.${column} + 1 + ${eagerUsageExpr} <= $5
- RETURNING ${column}`,
- params
- )
- return (result.rowCount ?? 0) > 0
-}
-
/**
* Per-minute rate limiting derived from the invocation audit trail itself
* (no separate window table): counts invocations recorded in the trailing
diff --git a/control-api/src/services/pluginWorkloadSdkQuotaTracker.ts b/control-api/src/services/pluginWorkloadSdkQuotaTracker.ts
index 58a75dce1..4d0f2f685 100644
--- a/control-api/src/services/pluginWorkloadSdkQuotaTracker.ts
+++ b/control-api/src/services/pluginWorkloadSdkQuotaTracker.ts
@@ -1,22 +1,22 @@
+import { config } from '../config.js'
import {
- PLUGIN_WORKLOAD_SDK_EAGER_QUOTA_PERIOD,
type PluginWorkloadSdkFamily,
type PluginWorkloadSdkGrant,
- consumePeriodQuota,
countRecentInvocations,
- resolveQuotaPeriodStart,
} from './pluginWorkloadSdkDb.js'
-// ─── Plugin Workload SDK — quota tracker (plan §2.3) ─────────────────────
-// Two enforcement layers per invocation:
-// 1. Per-minute rate limit (recipe + method, narrowed to eventType for
-// clientNotifications) — derived from the invocation audit trail.
-// 2. Per-period quota (maxRequestsPerRun / maxNotificationsPerRun) —
-// atomic conditional increment on plugin_workload_sdk_quota_counters,
-// bucketed by active workflow run (or eager sentinel when no run).
-
-const DEFAULT_MAX_INVOCATIONS_PER_MINUTE = 60
-const DEFAULT_MAX_NOTIFICATIONS_PER_MINUTE = 120
+// ─── Plugin Workload SDK — quota tracker (plan §2.3, issue #348) ─────────
+// Single enforcement layer per invocation: a per-minute platform rate limit
+// (recipe + method, narrowed to eventType for clientNotifications), derived
+// from the invocation audit trail. Defaults come from ENV-backed config
+// (platform protection against control-plane DoS); a grant-level per-minute
+// override still wins (decision §3.1).
+//
+// The former per-period leg (`consumeQuota`, backed by
+// plugin_workload_sdk_quota_counters) was DELETED (issue #348): the deprecated
+// per-run caps (maxRequestsPerRun / maxNotificationsPerRun) trapped stepless
+// recipes in an immortal epoch-sentinel bucket and are now ignored. Deleting
+// the function (not stubbing it) makes any future caller a compile error.
export type QuotaDecision =
| { ok: true }
@@ -42,8 +42,8 @@ export async function checkRateLimit(
): Promise<QuotaDecision> {
const limit =
family === 'promptBridge'
- ? (grant.quotaLimits.maxInvocationsPerMinute ?? DEFAULT_MAX_INVOCATIONS_PER_MINUTE)
- : (grant.quotaLimits.maxNotificationsPerMinute ?? DEFAULT_MAX_NOTIFICATIONS_PER_MINUTE)
+ ? (grant.quotaLimits.maxInvocationsPerMinute ?? config.pluginSdkPromptBridgeRlPerMin)
+ : (grant.quotaLimits.maxNotificationsPerMinute ?? config.pluginSdkNotificationsRlPerMin)
// The audit record for THIS invocation is inserted before the rate check, so
// `recent` already counts the current in-progress call. Deny only once the
// window EXCEEDS the limit (`> limit`, not `>= limit`) so exactly `limit`
@@ -57,39 +57,3 @@ export async function checkRateLimit(
}
return { ok: true }
}
-
-/**
- * Atomically consume one unit of period quota. No-op success when the grant
- * declares no per-run cap for the family.
- */
-export async function consumeQuota(
- recipeNamespace: string,
- recipeName: string,
- family: PluginWorkloadSdkFamily,
- grant: PluginWorkloadSdkGrant
-): Promise<QuotaDecision> {
- const limit =
- family === 'promptBridge'
- ? grant.quotaLimits.maxRequestsPerRun
- : grant.quotaLimits.maxNotificationsPerRun
- if (limit === undefined) return { ok: true }
- const periodStart = await resolveQuotaPeriodStart(recipeNamespace, recipeName)
- // For an active run period, eager-phase usage counts against the run cap
- // (prevents 2× per-run budget). The subtraction is now folded INTO the
- // atomic consumePeriodQuota statement (foldEagerUsage), so there is no
- // read-then-consume TOCTOU: concurrent run-period consumers cannot both
- // pass a budget the eager usage already exhausted.
- const foldEagerUsage = periodStart.getTime() !== PLUGIN_WORKLOAD_SDK_EAGER_QUOTA_PERIOD.getTime()
- const consumed = await consumePeriodQuota(
- recipeNamespace,
- recipeName,
- family,
- limit,
- periodStart,
- foldEagerUsage
- )
- if (!consumed) {
- return exceeded(`period quota of ${limit} reached for ${family}`)
- }
- return { ok: true }
-}
diff --git a/control-api/test/config.pluginSdkRateLimits.test.ts b/control-api/test/config.pluginSdkRateLimits.test.ts
new file mode 100644
index 000000000..87257e0c4
--- /dev/null
+++ b/control-api/test/config.pluginSdkRateLimits.test.ts
@@ -0,0 +1,162 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { readFileSync } from 'node:fs'
+
+/**
+ * Plugin Workload SDK platform rate-limit config (issue #348, plan D2).
+ *
+ * RED-FIRST (plan §6.6): this suite asserts the POST-change target behavior.
+ * Against pre-change code the four `pluginSdk*RlPerMin` config fields and the
+ * four `CONTROL_API_PLUGIN_SDK_*_PER_MIN` ConfigMap keys do not exist yet, so
+ * every test here FAILS until Phase 1 (step 1.1) and Phase 3 (D1) land. Do
+ * not weaken these assertions to pass early.
+ *
+ * Covered:
+ * 1. Code defaults 200/180/600/600 (decision Q3: recalibrated upward from
+ * the old hardcoded 120/60; request-bucket and pre-auth unchanged at 600
+ * but moved to ENV).
+ * 2. Each ENV override honored.
+ * 3. Invalid values fail loudly at import (positiveIntegerFromEnv).
+ * 4. Empty string falls back to the code default.
+ * 5. Deploy mirror: the base ConfigMap AND the full-copy minikube overlay
+ * both register every key at the code default (plan D1/R1 — omitting a
+ * key in the minikube full-copy overlay silently falls back to code
+ * defaults, so drift must fail HERE in CI).
+ */
+
+const RATE_LIMIT_KEYS = [
+ 'CONTROL_API_PLUGIN_SDK_NOTIFICATIONS_PER_MIN',
+ 'CONTROL_API_PLUGIN_SDK_PROMPTBRIDGE_PER_MIN',
+ 'CONTROL_API_PLUGIN_SDK_REQUEST_BUCKET_PER_MIN',
+ 'CONTROL_API_PLUGIN_SDK_PREAUTH_PER_MIN',
+] as const
+
+type RateLimitKey = (typeof RATE_LIMIT_KEYS)[number]
+
+/** Canonical config field per ENV key with its locked default (plan §5). */
+const EXPECTED: Array<{ env: RateLimitKey; field: string; defaultValue: number }> = [
+ {
+ env: 'CONTROL_API_PLUGIN_SDK_NOTIFICATIONS_PER_MIN',
+ field: 'pluginSdkNotificationsRlPerMin',
+ defaultValue: 200,
+ },
+ {
+ env: 'CONTROL_API_PLUGIN_SDK_PROMPTBRIDGE_PER_MIN',
+ field: 'pluginSdkPromptBridgeRlPerMin',
+ defaultValue: 180,
+ },
+ {
+ env: 'CONTROL_API_PLUGIN_SDK_REQUEST_BUCKET_PER_MIN',
+ field: 'pluginSdkRequestBucketRlPerMin',
+ defaultValue: 600,
+ },
+ {
+ env: 'CONTROL_API_PLUGIN_SDK_PREAUTH_PER_MIN',
+ field: 'pluginSdkPreauthRlPerMin',
+ defaultValue: 600,
+ },
+]
+
+async function loadConfigWith(overrides: Partial<Record<RateLimitKey, string>>) {
+ const originalValues = new Map<string, string | undefined>()
+ for (const key of RATE_LIMIT_KEYS) {
+ originalValues.set(key, process.env[key])
+ delete process.env[key]
+ }
+ Object.assign(process.env, overrides)
+ vi.resetModules()
+ try {
+ const mod = await import('../src/config.js')
+ // The four fields are added by Phase 1 step 1.1; index access keeps the
+ // TARGET assertion expressible before the Config type gains the fields
+ // (the values are still asserted strictly below — no soft pass).
+ return mod.config as typeof mod.config & Record<string, unknown>
+ } finally {
+ for (const key of RATE_LIMIT_KEYS) {
+ const value = originalValues.get(key)
+ if (value === undefined) delete process.env[key]
+ else process.env[key] = value
+ }
+ }
+}
+
+function read(relativeFromThisFile: string): string {
+ return readFileSync(new URL(relativeFromThisFile, import.meta.url), 'utf-8')
+}
+
+/** Fail-loud single-match extraction — a miss means the key is unregistered. */
+function extractOne(source: string, pattern: RegExp, label: string): string {
+ const match = source.match(pattern)
+ if (!match || match[1] === undefined) {
+ throw new Error(`Could not extract ${label} with ${pattern} — register the key (plan D1)`)
+ }
+ return match[1]
+}
+
+describe('plugin SDK platform rate-limit config (issue #348)', () => {
+ afterEach(() => {
+ vi.resetModules()
+ })
+
+ it('defaults the four platform rate limits to 200/180/600/600', async () => {
+ const config = await loadConfigWith({})
+
+ expect(config.pluginSdkNotificationsRlPerMin).toBe(200)
+ expect(config.pluginSdkPromptBridgeRlPerMin).toBe(180)
+ expect(config.pluginSdkRequestBucketRlPerMin).toBe(600)
+ expect(config.pluginSdkPreauthRlPerMin).toBe(600)
+ })
+
+ it.each(EXPECTED)('honors the $env override', async ({ env, field }) => {
+ const config = await loadConfigWith({ [env]: '60' })
+
+ expect(config[field]).toBe(60)
+ })
+
+ it.each(
+ EXPECTED.flatMap(({ env }) => ['abc', '0', '-5', '1.5'].map(invalid => ({ env, invalid })))
+ )('rejects $env=$invalid loudly at import', async ({ env, invalid }) => {
+ await expect(loadConfigWith({ [env]: invalid })).rejects.toThrow(/must be a positive integer/)
+ })
+
+ it('treats an empty string as unset and falls back to the defaults', async () => {
+ const config = await loadConfigWith({
+ CONTROL_API_PLUGIN_SDK_NOTIFICATIONS_PER_MIN: '',
+ CONTROL_API_PLUGIN_SDK_PROMPTBRIDGE_PER_MIN: '',
+ CONTROL_API_PLUGIN_SDK_REQUEST_BUCKET_PER_MIN: '',
+ CONTROL_API_PLUGIN_SDK_PREAUTH_PER_MIN: '',
+ })
+
+ expect(config.pluginSdkNotificationsRlPerMin).toBe(200)
+ expect(config.pluginSdkPromptBridgeRlPerMin).toBe(180)
+ expect(config.pluginSdkRequestBucketRlPerMin).toBe(600)
+ expect(config.pluginSdkPreauthRlPerMin).toBe(600)
+ })
+
+ it('registers every key at the code default in the base ConfigMap', async () => {
+ const config = await loadConfigWith({})
+ const source = read('../../deploy/base/control-plane/configmaps.yaml')
+
+ for (const { env, field } of EXPECTED) {
+ const value = extractOne(
+ source,
+ new RegExp(`${env}:\\s*"(\\d+)"`),
+ `${env} in deploy/base/control-plane/configmaps.yaml`
+ )
+ expect(Number(value), env).toBe(config[field])
+ }
+ })
+
+ it('registers every key at the code default in the minikube full-copy overlay', async () => {
+ const config = await loadConfigWith({})
+ const source = read('../../deploy/overlays/minikube/configmaps/control-api-config.yaml')
+
+ for (const { env, field } of EXPECTED) {
+ const value = extractOne(
+ source,
+ new RegExp(`${env}:\\s*"(\\d+)"`),
+ `${env} in deploy/overlays/minikube/configmaps/control-api-config.yaml`
+ )
+ expect(Number(value), env).toBe(config[field])
+ }
+ })
+})
diff --git a/control-api/test/pluginWorkloadSdkSteplessQuota.realPostgres.integration.test.ts b/control-api/test/pluginWorkloadSdkSteplessQuota.realPostgres.integration.test.ts
new file mode 100644
index 000000000..077b5a58f
--- /dev/null
+++ b/control-api/test/pluginWorkloadSdkSteplessQuota.realPostgres.integration.test.ts
@@ -0,0 +1,459 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { randomBytes, randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import type { PluginWorkloadSdkFamily } from '../src/services/pluginWorkloadSdkDb.js'
+import type { McpHostAccessClaims } from '../src/utils/auth/mcpHostJwtToken.js'
+
+/**
+ * Stepless / SDK-only quota regression on real PostgreSQL (issue #348,
+ * plan D4) — THE ACCEPTANCE-DEFINING RED-FIRST TEST.
+ *
+ * Test 1 asserts the POST-change target behavior and MUST FAIL against
+ * pre-change code (RED): today a stepless recipe (zero `workflow_runs` rows)
+ * books every per-run quota unit under the immortal epoch-sentinel bucket
+ * (`resolveQuotaPeriodStart` → `PLUGIN_WORKLOAD_SDK_EAGER_QUOTA_PERIOD =
+ * new Date(0)`), so a per-run cap becomes a lifetime cap that nothing ever
+ * resets. After Phase 1 the per-run leg is inert and every call is allowed.
+ * Do NOT weaken these assertions to pass early.
+ *
+ * POST-PHASE-1 NOTE (applied, audit finding 1): Phase 1 DELETED `consumeQuota`
+ * outright (plan decision §3.2 — delete, don't stub; the RED runs were
+ * captured against the pre-change `consumeQuota` API before the deletion).
+ * Tests 1 and 3 exercise the REAL enforcement entry points —
+ * `authorizePromptBridge` and (mirror) `authorizeClientNotification` in
+ * `src/services/pluginWorkloadSdkAuthorizer.ts` — against the real database.
+ * Pointing them at `checkRateLimit` alone would be near-vacuous: that function
+ * is the per-MINUTE gate and never consulted the per-RUN cap or
+ * `plugin_workload_sdk_quota_counters` even pre-change, so a future re-wire of
+ * the per-run leg inside the AUTHORIZER would not trip it. Going through the
+ * authorizer means ANY quota consultation reachable from the authorization
+ * pipeline (present or reintroduced) is under test. The assertions:
+ * (a) the authorizer never denies a stepless recipe past its declared
+ * per-run cap (the deprecated cap is inert), and
+ * (b) `plugin_workload_sdk_quota_counters` receives NO writes on that path
+ * (the epoch-sentinel bucket is never touched) — counted before/after.
+ * Test 2 stays on `checkRateLimit` deliberately: the per-minute window/reset
+ * semantics are exactly that function's contract.
+ *
+ * Real database, real `plugin_workload_sdk_quota_counters` and
+ * `plugin_workload_sdk_invocations` tables — NO db mock. The service module's
+ * pool (`src/db.ts` module-level `pool`, built from
+ * `CONTROL_API_PG_CONNECTION_STRING` at import time) is pointed at a fresh
+ * throwaway database by setting that env var BEFORE the src modules are
+ * dynamically imported in beforeAll; nothing from `src/` is value-imported
+ * statically in this file for exactly that reason.
+ */
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+// Repo convention (matches the other *.realPostgres.integration.test.ts suites):
+// gate on the DB env so the DB-less unit lane stays green. This suite is EXECUTED
+// for real in the DB-provisioned lane (T2 / minikube: point
+// CONTROL_API_REAL_PG_ADMIN_URL at the cluster Postgres). The T2 gate asserts this
+// suite actually ran (total>0, not skipped) so it can never pass by silent
+// omission (issue #348, plan D4; local run gated per owner decision).
+const describeRealPostgres = adminUrl ? describe : describe.skip
+
+const database = `control_api_sdk_stepless_${randomBytes(6).toString('hex')}`
+
+function databaseUrl(baseUrl: string, databaseName: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${databaseName}`
+ return url.toString()
+}
+
+// Redirect the module-level pool of src/db.ts to the throwaway database.
+// This runs at import time, strictly before the dynamic src imports below.
+// Guarded on adminUrl so the DB-less (skipped) lane never builds a URL from undefined.
+const previousPgConnectionString = process.env.CONTROL_API_PG_CONNECTION_STRING
+if (adminUrl) {
+ process.env.CONTROL_API_PG_CONNECTION_STRING = databaseUrl(adminUrl, database)
+}
+
+const NS = 'sandbox-recipes'
+const CALLER_REF = 'api'
+
+/** Claims fixture mirrored from test/services.pluginWorkloadSdkAuthorizer.test.ts. */
+function claimsFor(recipeName: string): McpHostAccessClaims {
+ return {
+ sub: `${NS}/${recipeName}`,
+ recipeNamespace: NS,
+ recipeName,
+ hostRefs: [`${NS}/${recipeName}`],
+ scope: 'workflow:approval:request',
+ workflowControlScopes: ['plugin-workload-sdk'] as McpHostAccessClaims['workflowControlScopes'],
+ iss: 'control-api',
+ aud: 'workflow-approvals',
+ jti: 'test-jti',
+ exp: Math.floor(Date.now() / 1000) + 300,
+ }
+}
+
+describeRealPostgres(
+ 'Plugin Workload SDK stepless quota enforcement on real PostgreSQL (issue #348)',
+ () => {
+ let adminPool: Pool
+ let db: typeof import('../src/db.js')
+ let quotaTracker: typeof import('../src/services/pluginWorkloadSdkQuotaTracker.js')
+ let authorizer: typeof import('../src/services/pluginWorkloadSdkAuthorizer.js')
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)
+ // Import AFTER the database exists and AFTER the env override above so
+ // the module-level pool binds to the fresh database.
+ db = await import('../src/db.js')
+ await db.initDb()
+ quotaTracker = await import('../src/services/pluginWorkloadSdkQuotaTracker.js')
+ authorizer = await import('../src/services/pluginWorkloadSdkAuthorizer.js')
+ })
+
+ afterAll(async () => {
+ await db?.pool.end()
+ if (previousPgConnectionString === undefined) {
+ delete process.env.CONTROL_API_PG_CONNECTION_STRING
+ } else {
+ process.env.CONTROL_API_PG_CONNECTION_STRING = previousPgConnectionString
+ }
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid)
+ FROM pg_stat_activity
+ WHERE datname = $1
+ AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ await adminPool.end()
+ }
+ })
+
+ /** Fail-loud stepless precondition: the recipe has ZERO workflow_runs rows. */
+ async function assertStepless(recipeName: string): Promise<void> {
+ const runs = await db.pool.query<{ n: number }>(
+ `SELECT count(*)::int AS n FROM workflow_runs
+ WHERE recipe_namespace = $1 AND recipe_name = $2`,
+ [NS, recipeName]
+ )
+ expect(runs.rows[0]?.n, `stepless precondition for ${recipeName}`).toBe(0)
+ }
+
+ /** Rows currently booked in the (deprecated) per-run counter bucket table. */
+ async function quotaCounterRowCount(recipeName: string): Promise<number> {
+ const result = await db.pool.query<{ n: number }>(
+ `SELECT count(*)::int AS n FROM plugin_workload_sdk_quota_counters
+ WHERE recipe_namespace = $1 AND recipe_name = $2`,
+ [NS, recipeName]
+ )
+ return result.rows[0]?.n ?? 0
+ }
+
+ /**
+ * Seed an operator-reviewed, ACTIVE promptBridge grant exactly as the
+ * authorizer requires it (policy_revision >= 1, first ordered target ==
+ * default_target_ref, durable review provenance). The INSERT mirrors the
+ * grant seeding of pluginWorkloadSdkPolicyReview.realPostgres.integration
+ * .test.ts, extended with quota_limits so the deprecated per-run cap is on
+ * the row the authorizer actually loads via findGrant.
+ */
+ async function seedPromptBridgeGrant(
+ recipeName: string,
+ quotaLimits: Record<string, number>
+ ): Promise<void> {
+ await db.pool.query(
+ `INSERT INTO plugin_workload_sdk_grants
+ (recipe_namespace, recipe_name, capability_family, provider,
+ allowed_callers, quota_limits, prompt_targets, default_target_ref,
+ policy_revision, policy_state, policy_reviewed_at, policy_reviewed_by)
+ VALUES ($1, $2, 'promptBridge', 'openai',
+ '["${CALLER_REF}"]'::jsonb, $3::jsonb,
+ '[{"targetRef":"primary","provider":"openai","model":"gpt-4o-mini","credentialSlot":"openai-api-key"}]'::jsonb,
+ 'primary', 1, 'active', now(), 'operator-1')`,
+ [NS, recipeName, JSON.stringify(quotaLimits)]
+ )
+ }
+
+ /**
+ * Seed an ACTIVE clientNotifications grant plus the real recipient row the
+ * authorizer's `hasUsableClientNotificationRecipients` check resolves
+ * against (a `users` row with a non-empty email). Same INSERT mirror as the
+ * promptBridge seeding above.
+ */
+ async function seedClientNotificationsGrant(
+ recipeName: string,
+ eventType: string,
+ quotaLimits: Record<string, number>
+ ): Promise<void> {
+ const userId = randomUUID()
+ await db.pool.query(`INSERT INTO users (id, email) VALUES ($1::uuid, $2)`, [
+ userId,
+ `sdk-stepless-${recipeName}@e2e.local`,
+ ])
+ await db.pool.query(
+ `INSERT INTO plugin_workload_sdk_grants
+ (recipe_namespace, recipe_name, capability_family,
+ allowed_event_types, allowed_user_refs, allowed_callers, quota_limits,
+ policy_revision, policy_state, policy_reviewed_at, policy_reviewed_by)
+ VALUES ($1, $2, 'clientNotifications',
+ $3::jsonb, $4::jsonb, '["${CALLER_REF}"]'::jsonb, $5::jsonb,
+ 1, 'active', now(), 'operator-1')`,
+ [
+ NS,
+ recipeName,
+ JSON.stringify([eventType]),
+ JSON.stringify([userId]),
+ JSON.stringify(quotaLimits),
+ ]
+ )
+ }
+
+ /**
+ * Seed invocation-audit rows inside the trailing per-minute window
+ * (created_at defaults to now()). contract_version 1 + status 'complete'
+ * keeps the rows clear of the v2 lease constraint; the per-row idempotency
+ * suffix satisfies the (namespace, name, method, hash) unique index.
+ */
+ async function seedInvocationWindowRows(
+ recipeName: string,
+ method: PluginWorkloadSdkFamily,
+ detail: string,
+ count: number
+ ): Promise<void> {
+ const result = await db.pool.query(
+ `INSERT INTO plugin_workload_sdk_invocations
+ (recipe_namespace, recipe_name, caller_ref, method, detail,
+ idempotency_key_hash, payload_hash, status, authorization_decision,
+ contract_version, attempt_generation)
+ SELECT $1, $2, 'stepless-quota-integration', $3, $4,
+ $2 || '-' || $3 || '-window-' || g::text, '', 'complete', 'authorized', 1, 1
+ FROM generate_series(1, $5::int) AS g`,
+ [NS, recipeName, method, detail, count]
+ )
+ if (result.rowCount !== count) {
+ throw new Error(
+ `window seed for ${recipeName}/${method} inserted ${result.rowCount} rows, expected ${count}`
+ )
+ }
+ }
+
+ it('never denies a stepless recipe on per-run caps through the AUTHORIZER and books nothing in quota counters (RED vs pre-change code)', async () => {
+ const recipeName = `stepless-run-cap-${randomBytes(4).toString('hex')}`
+ await assertStepless(recipeName)
+ await seedPromptBridgeGrant(recipeName, { maxRequestsPerRun: 3 })
+ const claims = claimsFor(recipeName)
+
+ // The deprecated per-run bucket table starts empty for this recipe.
+ expect(await quotaCounterRowCount(recipeName), 'counters before any call').toBe(0)
+
+ // FOUR full authorization passes — one PAST the declared per-run cap of 3
+ // — through the real enforcement entry point (grant lookup, audit-record
+ // reservation, rate check; each with a fresh idempotency key so no replay
+ // short-circuit hides the quota path). TARGET behavior: the deprecated
+ // per-run cap is inert, so every call is authorized. Pre-change code
+ // denied the 4th — the epoch-sentinel bucket (period_start = 1970-01-01)
+ // booked every prior call under one immortal per-"run" counter (RED,
+ // captured).
+ for (let call = 1; call <= 4; call += 1) {
+ const result = await authorizer.authorizePromptBridge({
+ claims,
+ callerRef: CALLER_REF,
+ purpose: 'stepless-run-cap-probe',
+ idempotencyKey: `stepless-run-cap-${recipeName}-${call}`,
+ payload: { call },
+ })
+ expect(
+ result.ok,
+ `call ${call}/4: per-run caps are deprecated and the authorizer must not deny (issue #348)${
+ result.ok ? '' : ` — got ${result.error}: ${result.message}`
+ }`
+ ).toBe(true)
+ }
+
+ // Proves NO reset is required: even wiping the entire invocation audit
+ // trail changes nothing about the decision (pre-change code kept denying
+ // because the counter lives in plugin_workload_sdk_quota_counters, which
+ // nothing ever resets for a stepless recipe).
+ await db.pool.query(
+ `DELETE FROM plugin_workload_sdk_invocations
+ WHERE recipe_namespace = $1 AND recipe_name = $2`,
+ [NS, recipeName]
+ )
+ const fifth = await authorizer.authorizePromptBridge({
+ claims,
+ callerRef: CALLER_REF,
+ purpose: 'stepless-run-cap-probe',
+ idempotencyKey: `stepless-run-cap-${recipeName}-5`,
+ payload: { call: 5 },
+ })
+ expect(fifth.ok, '5th call after deleting every invocation row: still authorized').toBe(true)
+
+ // The epoch-sentinel bucket was never touched: the entire authorization
+ // path wrote ZERO rows to plugin_workload_sdk_quota_counters. A future
+ // re-wire of the per-run leg inside the authorizer trips this loudly.
+ expect(
+ await quotaCounterRowCount(recipeName),
+ 'plugin_workload_sdk_quota_counters must receive no rows from the authorizer path'
+ ).toBe(0)
+ })
+
+ it('mirrors the per-run-inert contract for clientNotifications through the AUTHORIZER', async () => {
+ const recipeName = `stepless-notif-cap-${randomBytes(4).toString('hex')}`
+ const eventType = 'lead.followup.due'
+ await assertStepless(recipeName)
+ await seedClientNotificationsGrant(recipeName, eventType, { maxNotificationsPerRun: 2 })
+ const claims = claimsFor(recipeName)
+
+ expect(await quotaCounterRowCount(recipeName), 'counters before any call').toBe(0)
+
+ // THREE notifications — one past the declared per-run cap of 2 — each
+ // with a fresh idempotency key. All must be authorized: the per-run cap
+ // is deprecated and inert on the real enforcement path.
+ for (let call = 1; call <= 3; call += 1) {
+ const result = await authorizer.authorizeClientNotification({
+ claims,
+ callerRef: CALLER_REF,
+ eventType,
+ idempotencyKey: `stepless-notif-cap-${recipeName}-${call}`,
+ payload: { call },
+ })
+ expect(
+ result.ok,
+ `notification ${call}/3: per-run caps are deprecated and the authorizer must not deny (issue #348)${
+ result.ok ? '' : ` — got ${result.error}: ${result.message}`
+ }`
+ ).toBe(true)
+ }
+
+ expect(
+ await quotaCounterRowCount(recipeName),
+ 'plugin_workload_sdk_quota_counters must receive no rows from the notification authorizer path'
+ ).toBe(0)
+ })
+
+ it('enforces the per-minute window from the audit trail and frees after 61 seconds (backdated)', async () => {
+ // promptBridge at the 180/min platform default: 181 in-window rows deny.
+ const bridgeRecipe = `stepless-window-bridge-${randomBytes(4).toString('hex')}`
+ await assertStepless(bridgeRecipe)
+ await seedPromptBridgeGrant(bridgeRecipe, {})
+ const bridgeGrant = await (async () => {
+ const sdkDb = await import('../src/services/pluginWorkloadSdkDb.js')
+ const grant = await sdkDb.findGrant(NS, bridgeRecipe, 'promptBridge')
+ if (!grant) throw new Error(`seeded promptBridge grant not found for ${bridgeRecipe}`)
+ return grant
+ })()
+ await seedInvocationWindowRows(bridgeRecipe, 'promptBridge', 'window-probe', 181)
+
+ await expect(
+ quotaTracker.checkRateLimit(NS, bridgeRecipe, 'promptBridge', bridgeGrant)
+ ).resolves.toMatchObject({
+ ok: false,
+ error: 'quota_exceeded',
+ retryable: false,
+ message: expect.stringContaining('180/minute'),
+ })
+
+ // Backdate the whole burst out of the trailing minute (the window clock is
+ // Postgres now(), plan D9 R2 — no fake timers, no real waiting) → allowed.
+ await db.pool.query(
+ `UPDATE plugin_workload_sdk_invocations
+ SET created_at = now() - interval '61 seconds'
+ WHERE recipe_namespace = $1 AND recipe_name = $2`,
+ [NS, bridgeRecipe]
+ )
+ await expect(
+ quotaTracker.checkRateLimit(NS, bridgeRecipe, 'promptBridge', bridgeGrant)
+ ).resolves.toEqual({ ok: true })
+
+ // clientNotifications mirror at the 200/min platform default, narrowed to
+ // the eventType (detail column).
+ const notifRecipe = `stepless-window-notif-${randomBytes(4).toString('hex')}`
+ await assertStepless(notifRecipe)
+ await seedClientNotificationsGrant(notifRecipe, 'lead.followup.due', {})
+ const notifGrant = await (async () => {
+ const sdkDb = await import('../src/services/pluginWorkloadSdkDb.js')
+ const grant = await sdkDb.findGrant(NS, notifRecipe, 'clientNotifications')
+ if (!grant) throw new Error(`seeded clientNotifications grant not found for ${notifRecipe}`)
+ return grant
+ })()
+ await seedInvocationWindowRows(notifRecipe, 'clientNotifications', 'lead.followup.due', 201)
+
+ await expect(
+ quotaTracker.checkRateLimit(NS, notifRecipe, 'clientNotifications', notifGrant, {
+ eventType: 'lead.followup.due',
+ })
+ ).resolves.toMatchObject({
+ ok: false,
+ error: 'quota_exceeded',
+ retryable: false,
+ message: expect.stringContaining('200/minute'),
+ })
+
+ await db.pool.query(
+ `UPDATE plugin_workload_sdk_invocations
+ SET created_at = now() - interval '61 seconds'
+ WHERE recipe_namespace = $1 AND recipe_name = $2`,
+ [NS, notifRecipe]
+ )
+ await expect(
+ quotaTracker.checkRateLimit(NS, notifRecipe, 'clientNotifications', notifGrant, {
+ eventType: 'lead.followup.due',
+ })
+ ).resolves.toEqual({ ok: true })
+ })
+
+ it('leaves stale epoch-sentinel quota counters inert through the AUTHORIZER — upgraded clusters are freed without migration', async () => {
+ const recipeName = `stepless-stale-counter-${randomBytes(4).toString('hex')}`
+ await assertStepless(recipeName)
+ await seedPromptBridgeGrant(recipeName, { maxRequestsPerRun: 3 })
+ const claims = claimsFor(recipeName)
+
+ // A poisoned counter row exactly as a pre-#348 cluster would carry it:
+ // booked under the eager sentinel period (epoch) with a count far past
+ // any conceivable cap.
+ await db.pool.query(
+ `INSERT INTO plugin_workload_sdk_quota_counters
+ (recipe_namespace, recipe_name, period_start, prompt_bridge_count, notification_count)
+ VALUES ($1, $2, to_timestamp(0), 999999, 0)`,
+ [NS, recipeName]
+ )
+
+ // TARGET behavior: the stale sentinel row is historical data only — it
+ // must not deny anything. Pre-change code read it (999999 + 1 > 3) and
+ // denied (RED, captured); after Phase 1 the real enforcement entry point
+ // never consults plugin_workload_sdk_quota_counters, so upgraded clusters
+ // are freed with NO data migration (plan D8: rollout is non-breaking).
+ const result = await authorizer.authorizePromptBridge({
+ claims,
+ callerRef: CALLER_REF,
+ purpose: 'stale-sentinel-probe',
+ idempotencyKey: `stale-sentinel-${recipeName}-1`,
+ payload: { probe: 'stale-sentinel' },
+ })
+ expect(
+ result.ok,
+ `stale epoch-sentinel counter must be inert on the authorizer path${
+ result.ok ? '' : ` — got ${result.error}: ${result.message}`
+ }`
+ ).toBe(true)
+
+ // The poisoned row is untouched — historical data only, neither read for
+ // enforcement nor written by the authorization pipeline.
+ const counter = await db.pool.query<{
+ n: number
+ prompt_bridge_count: number
+ epoch: boolean
+ }>(
+ `SELECT count(*)::int AS n,
+ min(prompt_bridge_count)::int AS prompt_bridge_count,
+ bool_and(period_start = to_timestamp(0)) AS epoch
+ FROM plugin_workload_sdk_quota_counters
+ WHERE recipe_namespace = $1 AND recipe_name = $2`,
+ [NS, recipeName]
+ )
+ expect(counter.rows[0], 'sentinel row must remain exactly as seeded').toEqual({
+ n: 1,
+ prompt_bridge_count: 999999,
+ epoch: true,
+ })
+ })
+ }
+)
diff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
index 74c7ba2e1..178d43fce 100644
--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts
+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
@@ -470,7 +470,34 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
capabilityFamily: 'promptBridge',
provider: 'zai',
allowedCallers: ['api'],
- quotaLimits: { maxRequestsPerRun: 10 },
+ // Issue #348 (plan 2.6, RED until the strip lands): the deprecated
+ // per-run key is tolerated on write but STRIPPED before persistence —
+ // the persisted quotaLimits must be empty, not { maxRequestsPerRun: 10 }.
+ quotaLimits: {},
+ }),
+ '11111111-1111-4111-8111-111111111111'
+ )
+ })
+
+ it('accepts deprecated per-run keys, strips them, keeps active keys', async () => {
+ // Issue #348 (plan 2.6/2.7): deprecated per-run keys stay shape-validated
+ // (malformed still 400s, pinned above) but are dropped on write, while the
+ // active per-minute/token keys persist untouched.
+ vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'g1' } as never)
+ const res = await request(buildApp())
+ .post('/admin/plugin-workload-sdk/grants')
+ .send({
+ ...validGrantBody,
+ quotaLimits: {
+ maxRequestsPerRun: 5,
+ maxNotificationsPerRun: 7,
+ maxInvocationsPerMinute: 30,
+ },
+ })
+ expect(res.status).toBe(200)
+ expect(sdkDb.upsertGrant).toHaveBeenCalledWith(
+ expect.objectContaining({
+ quotaLimits: { maxInvocationsPerMinute: 30 },
}),
'11111111-1111-4111-8111-111111111111'
)
diff --git a/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts b/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts
index 1c4f4b09a..90c9787ec 100644
--- a/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts
@@ -17,6 +17,13 @@ vi.mock('../src/db.js', () => ({
withTransaction: vi.fn(),
}))
+// Issue #348: `consumePeriodQuota` was DELETED from pluginWorkloadSdkDb (the
+// per-run quota leg is gone; any production caller is now a compile error).
+// The hoisted spy keeps the legacy export name mocked so the per-run-inert
+// tests below can assert it is NEVER called — a regression that re-wired the
+// per-run leg through the old symbol would trip these assertions loudly.
+const consumePeriodQuotaSpy = vi.hoisted(() => vi.fn())
+
vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {
const actual = await vi.importActual<typeof import('../src/services/pluginWorkloadSdkDb.js')>(
'../src/services/pluginWorkloadSdkDb.js'
@@ -27,7 +34,7 @@ vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {
insertInvocation: vi.fn(),
reviveFailedInvocation: vi.fn(),
updateInvocationStatus: vi.fn(),
- consumePeriodQuota: vi.fn(),
+ consumePeriodQuota: consumePeriodQuotaSpy,
countRecentInvocations: vi.fn(),
getInvocationById: vi.fn(),
getPluginWorkloadSdkAttemptReceipt: vi.fn(),
@@ -83,6 +90,7 @@ function grant(
defaultTargetRef: 'primary-zai',
policyState: 'active',
policyRevision: 1,
+ revocationId: null,
createdAt: '2026-06-09T00:00:00.000Z',
updatedAt: '2026-06-09T00:00:00.000Z',
...overrides,
@@ -138,7 +146,7 @@ beforeEach(() => {
vi.mocked(sdkDb.insertInvocation).mockReset()
vi.mocked(sdkDb.reviveFailedInvocation).mockReset()
vi.mocked(sdkDb.updateInvocationStatus).mockReset()
- vi.mocked(sdkDb.consumePeriodQuota).mockReset()
+ consumePeriodQuotaSpy.mockReset()
vi.mocked(sdkDb.countRecentInvocations).mockReset()
vi.mocked(sdkDb.getInvocationById).mockReset()
vi.mocked(sdkDb.getPluginWorkloadSdkAttemptReceipt).mockReset()
@@ -147,7 +155,6 @@ beforeEach(() => {
vi.mocked(sdkDb.markPluginWorkloadSdkProviderAttemptStatus).mockReset()
vi.mocked(sdkDb.registerPluginWorkloadSdkCredentialTicketJti).mockReset()
vi.mocked(sdkDb.countRecentInvocations).mockResolvedValue(0)
- vi.mocked(sdkDb.consumePeriodQuota).mockResolvedValue(true)
vi.mocked(sdkDb.hasUsableClientNotificationRecipients).mockResolvedValue(true)
vi.mocked(sdkDb.registerPluginWorkloadSdkCredentialTicketJti).mockResolvedValue(true)
vi.mocked(sdkDb.getPluginWorkloadSdkAttemptReceipt).mockResolvedValue({
@@ -562,24 +569,23 @@ describe('authorizePromptBridge', () => {
value: { invocationId: 'inv-1', replay: true, status: 'complete' },
})
expect(sdkDb.countRecentInvocations).not.toHaveBeenCalled()
- expect(sdkDb.consumePeriodQuota).not.toHaveBeenCalled()
+ expect(consumePeriodQuotaSpy).not.toHaveBeenCalled()
})
- it('marks the invocation failed when period quota is exceeded', async () => {
- vi.mocked(sdkDb.findGrant).mockResolvedValue(grant({ quotaLimits: { maxRequestsPerRun: 3 } }))
- vi.mocked(sdkDb.consumePeriodQuota).mockResolvedValue(false)
+ it('ignores the deprecated maxRequestsPerRun cap — the per-run leg is inert (issue #348)', async () => {
+ // Pre-#348 this grant denied the invocation via consumeQuota once the
+ // per-run counter was exhausted. The per-run leg is now deleted: even the
+ // tightest possible cap (1) never denies and never touches the period
+ // quota counters.
+ vi.mocked(sdkDb.findGrant).mockResolvedValue(grant({ quotaLimits: { maxRequestsPerRun: 1 } }))
const result = await authorizePromptBridge({ claims: claims(), ...basePromptParams })
- expect(result).toMatchObject({ ok: false, error: 'quota_exceeded' })
- expect(sdkDb.updateInvocationStatus).toHaveBeenCalledWith(
- 'inv-1',
- 'failed',
- expect.objectContaining({
- completed: true,
- recipeNamespace: NS,
- recipeName: RECIPE,
- expectedAttemptGeneration: 1,
- })
- )
+ expect(result).toMatchObject({
+ ok: true,
+ value: { invocationId: 'inv-1', replay: false },
+ })
+ expect(sdkDb.insertInvocation).toHaveBeenCalledOnce()
+ expect(consumePeriodQuotaSpy).not.toHaveBeenCalled()
+ expect(sdkDb.updateInvocationStatus).not.toHaveBeenCalled()
})
it('authorizes a valid request and records the invocation', async () => {
@@ -596,7 +602,9 @@ describe('authorizePromptBridge', () => {
value: { invocationId: 'inv-1', replay: false, maxOutputTokens: 2048 },
})
expect(sdkDb.insertInvocation).toHaveBeenCalledOnce()
- expect(sdkDb.consumePeriodQuota).toHaveBeenCalledOnce()
+ // Issue #348: the per-run leg is inert — no period quota is consumed even
+ // though the grant still carries a legacy maxRequestsPerRun value.
+ expect(consumePeriodQuotaSpy).not.toHaveBeenCalled()
})
it('authorizes an explicitly approved non-default model', async () => {
@@ -637,10 +645,10 @@ describe('authorizePromptBridge', () => {
ok: true,
value: { invocationId: 'inv-1', replay: true, status: 'complete' },
})
- expect(sdkDb.consumePeriodQuota).not.toHaveBeenCalled()
+ expect(consumePeriodQuotaSpy).not.toHaveBeenCalled()
})
- it('re-consumes quota and revives status for a failed-replay retry', async () => {
+ it('revives status for a failed-replay retry without consuming period quota', async () => {
const currentGrant = grant({ quotaLimits: { maxRequestsPerRun: 10 } })
vi.mocked(sdkDb.findGrant).mockResolvedValue(currentGrant)
vi.mocked(sdkDb.reviveFailedInvocation).mockResolvedValue(2)
@@ -657,9 +665,9 @@ describe('authorizePromptBridge', () => {
})
const result = await authorizePromptBridge({ claims: claims(), ...basePromptParams })
// A failed replay is a new physical attempt, but it remains the same
- // logical idempotent invocation and therefore does not consume period
- // quota a second time.
- expect(sdkDb.consumePeriodQuota).not.toHaveBeenCalled()
+ // logical idempotent invocation; with the per-run leg deleted (issue
+ // #348) no path may consume period quota.
+ expect(consumePeriodQuotaSpy).not.toHaveBeenCalled()
// The retry transition is performed atomically by the DB revive operation.
expect(sdkDb.reviveFailedInvocation).toHaveBeenCalledWith({
id: 'inv-1',
@@ -900,6 +908,27 @@ describe('authorizeClientNotification', () => {
})
})
+ it('ignores the deprecated maxNotificationsPerRun cap — the per-run leg is inert (issue #348)', async () => {
+ // Pre-#348 the notification path consumed one period-quota unit per
+ // accepted notification and denied once maxNotificationsPerRun was
+ // exhausted. The per-run leg is now deleted: even the tightest possible
+ // cap (1) never denies and never touches the period quota counters.
+ vi.mocked(sdkDb.findGrant).mockResolvedValue(
+ notificationGrant({ quotaLimits: { maxNotificationsPerRun: 1 } })
+ )
+ const result = await authorizeClientNotification({
+ claims: claims(),
+ ...baseNotificationParams,
+ })
+ expect(result).toMatchObject({
+ ok: true,
+ value: { notificationId: 'inv-1', replay: false, status: 'accepted' },
+ })
+ expect(sdkDb.insertInvocation).toHaveBeenCalledOnce()
+ expect(consumePeriodQuotaSpy).not.toHaveBeenCalled()
+ expect(sdkDb.updateInvocationStatus).not.toHaveBeenCalled()
+ })
+
it('rate-limits per recipe + eventType', async () => {
vi.mocked(sdkDb.findGrant).mockResolvedValue(
notificationGrant({ quotaLimits: { maxNotificationsPerMinute: 2 } })
@@ -960,7 +989,7 @@ describe('authorizeListRecipients', () => {
expect(result).toMatchObject({ ok: true, value: { allowedUserRefs: refs } })
// Read-only: no invocation row, no quota consumption.
expect(sdkDb.insertInvocation).not.toHaveBeenCalled()
- expect(sdkDb.consumePeriodQuota).not.toHaveBeenCalled()
+ expect(consumePeriodQuotaSpy).not.toHaveBeenCalled()
})
it.each(['revoking', 'disabled'] as const)(
diff --git a/control-api/test/services.pluginWorkloadSdkDb.test.ts b/control-api/test/services.pluginWorkloadSdkDb.test.ts
index e2a302cc9..476997afa 100644
--- a/control-api/test/services.pluginWorkloadSdkDb.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkDb.test.ts
@@ -1,7 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { pool } from '../src/db.js'
import {
- consumePeriodQuota,
deleteGrant,
failStaleInvocations,
finalizePluginWorkloadSdkRevocation,
@@ -20,9 +19,8 @@ import {
const permissionEvents = vi.hoisted(() => ({ append: vi.fn() }))
-// Mock the pg pool so we can inspect the exact SQL + bind parameters that the
-// real consumePeriodQuota produces (the quota-tracker test mocks
-// consumePeriodQuota itself, so it never exercises this SQL/param path).
+// Mock the pg pool so we can inspect the exact SQL + bind parameters the real
+// db-layer functions produce.
vi.mock('../src/db.js', () => ({
...(() => {
const query = vi.fn().mockResolvedValue({ rows: [{ prompt_bridge_count: 1 }], rowCount: 1 })
@@ -38,12 +36,6 @@ vi.mock('../src/services/tracing/controlApiPermissionEvents.js', () => ({
permissionEvents.append(...args),
}))
-/** Highest $N placeholder referenced in a SQL string. */
-function maxPlaceholder(sql: string): number {
- const matches = sql.match(/\$(\d+)/g) ?? []
- return matches.reduce((max, p) => Math.max(max, Number(p.slice(1))), 0)
-}
-
function mockUpsertGrantQueries(row: Record<string, unknown>): void {
// recipe advisory lock → family row → recipe kill-switch guard → upsert.
const responses = [
@@ -65,43 +57,8 @@ function mockUpsertGrantQueries(row: Record<string, unknown>): void {
}
}
-describe('consumePeriodQuota — SQL bind parameter contract', () => {
- beforeEach(() => {
- vi.mocked(pool.query).mockClear()
- vi.mocked(pool.query).mockResolvedValue({
- rows: [{ prompt_bridge_count: 1 }],
- rowCount: 1,
- } as never)
- })
-
- // Regression: a malformed bind array (more params than placeholders) makes
- // node-postgres throw "bind message supplies N parameters, but prepared
- // statement requires M", which silently breaks every quota consumption.
- it('binds exactly as many params as the SQL references (foldEagerUsage=false → no $6)', async () => {
- await consumePeriodQuota('ns', 'name', 'promptBridge', 3, new Date(0), false)
- expect(pool.query).toHaveBeenCalledTimes(1)
- const [sql, params] = vi.mocked(pool.query).mock.calls[0] as unknown as [string, unknown[]]
- expect(sql).not.toContain('$6')
- expect(params).toHaveLength(maxPlaceholder(sql))
- expect(params).toHaveLength(5)
- })
-
- it('binds the eager period as $6 only when folding eager usage (foldEagerUsage=true)', async () => {
- await consumePeriodQuota(
- 'ns',
- 'name',
- 'promptBridge',
- 3,
- new Date('2026-06-10T12:00:00Z'),
- true
- )
- expect(pool.query).toHaveBeenCalledTimes(1)
- const [sql, params] = vi.mocked(pool.query).mock.calls[0] as unknown as [string, unknown[]]
- expect(sql).toContain('$6')
- expect(params).toHaveLength(maxPlaceholder(sql))
- expect(params).toHaveLength(6)
- })
-})
+// The `consumePeriodQuota — SQL bind parameter contract` block was removed
+// with the function itself (issue #348, plan §1.6 dead-code sweep).
describe('JIT credential ticket jti registry', () => {
beforeEach(() => {
diff --git a/control-api/test/services.pluginWorkloadSdkQuotaTracker.test.ts b/control-api/test/services.pluginWorkloadSdkQuotaTracker.test.ts
index 48a10a660..41c7551d6 100644
--- a/control-api/test/services.pluginWorkloadSdkQuotaTracker.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkQuotaTracker.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import * as sdkDb from '../src/services/pluginWorkloadSdkDb.js'
-import { consumeQuota } from '../src/services/pluginWorkloadSdkQuotaTracker.js'
+import { checkRateLimit } from '../src/services/pluginWorkloadSdkQuotaTracker.js'
vi.mock('../src/db.js', () => ({
pool: {
@@ -16,13 +16,10 @@ vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {
)
return {
...actual,
- resolveQuotaPeriodStart: vi.fn(),
- consumePeriodQuota: vi.fn(),
+ countRecentInvocations: vi.fn(),
}
})
-const runPeriod = new Date('2026-06-10T12:00:00.000Z')
-
const grant = (
overrides: Partial<sdkDb.PluginWorkloadSdkGrant> = {}
): sdkDb.PluginWorkloadSdkGrant => ({
@@ -42,76 +39,118 @@ const grant = (
defaultTargetRef: null,
policyState: 'active',
policyRevision: 0,
+ revocationId: null,
createdAt: '',
updatedAt: '',
...overrides,
})
-describe('consumeQuota', () => {
+// The former `consumeQuota` describe block was removed with the function
+// itself (issue #348, plan §1.5 — deleted outright, not stubbed, so any
+// missed production caller is a compile error).
+
+// ─── Issue #348 (plan D3) — platform per-minute defaults ─────────────────
+//
+// RED-FIRST (plan §6.6): these tests assert the POST-change ceilings
+// (promptBridge 180/min, clientNotifications 200/min, sourced from
+// config.pluginSdkPromptBridgeRlPerMin / config.pluginSdkNotificationsRlPerMin).
+// Against pre-change code the hardcoded defaults are 60/120, so the
+// exactly-at-the-ceiling cases FAIL until Phase 1 step 1.4 lands. Do not
+// weaken them to pass early.
+//
+// Plan D3.3 (per-run leg inert): after Phase 1, `consumeQuota` is DELETED
+// (decision §3.2 — delete, don't stub), so a mocked-db assertion here would
+// have no symbol to call. The per-run-inert behavior is asserted end-to-end
+// in the real-Postgres regression suite instead
+// (test/pluginWorkloadSdkSteplessQuota.realPostgres.integration.test.ts,
+// plan D4 Tests 1 and 3), where the enforcement path itself — not a mock —
+// proves the per-run cap never denies and never resets anything.
+describe('checkRateLimit — platform per-minute rate limits (issue #348)', () => {
beforeEach(() => {
- vi.mocked(sdkDb.resolveQuotaPeriodStart).mockReset()
- vi.mocked(sdkDb.consumePeriodQuota).mockReset()
+ vi.mocked(sdkDb.countRecentInvocations).mockReset()
})
- it('folds eager-period usage into the atomic run-cap consume (no TOCTOU read)', async () => {
- // For an active run period, the eager subtraction is now resolved INSIDE
- // consumePeriodQuota (foldEagerUsage=true) — a single atomic statement,
- // not a separate read-then-consume.
- vi.mocked(sdkDb.resolveQuotaPeriodStart).mockResolvedValue(runPeriod)
- vi.mocked(sdkDb.consumePeriodQuota).mockResolvedValue(true)
+ it('allows promptBridge at exactly 180/minute and denies at 181 (platform default)', async () => {
+ const noOverrides = grant({ quotaLimits: {} })
- const result = await consumeQuota('sandbox-recipes', 'sdk-recipe', 'promptBridge', grant())
+ vi.mocked(sdkDb.countRecentInvocations).mockResolvedValue(180)
+ await expect(
+ checkRateLimit('sandbox-recipes', 'sdk-recipe', 'promptBridge', noOverrides)
+ ).resolves.toEqual({ ok: true })
- expect(result).toEqual({ ok: true })
- expect(sdkDb.consumePeriodQuota).toHaveBeenCalledWith(
- 'sandbox-recipes',
- 'sdk-recipe',
- 'promptBridge',
- 10,
- runPeriod,
- true
- )
+ vi.mocked(sdkDb.countRecentInvocations).mockResolvedValue(181)
+ await expect(
+ checkRateLimit('sandbox-recipes', 'sdk-recipe', 'promptBridge', noOverrides)
+ ).resolves.toMatchObject({
+ ok: false,
+ error: 'quota_exceeded',
+ retryable: false,
+ message: expect.stringContaining('180/minute'),
+ })
})
- it('does not fold eager usage when consuming the eager sentinel period itself', async () => {
- vi.mocked(sdkDb.resolveQuotaPeriodStart).mockResolvedValue(
- sdkDb.PLUGIN_WORKLOAD_SDK_EAGER_QUOTA_PERIOD
- )
- vi.mocked(sdkDb.consumePeriodQuota).mockResolvedValue(true)
-
- const result = await consumeQuota('sandbox-recipes', 'sdk-recipe', 'promptBridge', grant())
+ it('allows clientNotifications at exactly 200/minute and denies at 201, narrowed to the eventType', async () => {
+ const noOverrides = grant({ capabilityFamily: 'clientNotifications', quotaLimits: {} })
- expect(result).toEqual({ ok: true })
- expect(sdkDb.consumePeriodQuota).toHaveBeenCalledWith(
+ vi.mocked(sdkDb.countRecentInvocations).mockResolvedValue(200)
+ await expect(
+ checkRateLimit('sandbox-recipes', 'sdk-recipe', 'clientNotifications', noOverrides, {
+ eventType: 'lead.followup.due',
+ })
+ ).resolves.toEqual({ ok: true })
+ expect(sdkDb.countRecentInvocations).toHaveBeenCalledWith(
'sandbox-recipes',
'sdk-recipe',
- 'promptBridge',
- 10,
- sdkDb.PLUGIN_WORKLOAD_SDK_EAGER_QUOTA_PERIOD,
- false
+ 'clientNotifications',
+ { detail: 'lead.followup.due' }
)
+
+ vi.mocked(sdkDb.countRecentInvocations).mockResolvedValue(201)
+ await expect(
+ checkRateLimit('sandbox-recipes', 'sdk-recipe', 'clientNotifications', noOverrides, {
+ eventType: 'lead.followup.due',
+ })
+ ).resolves.toMatchObject({
+ ok: false,
+ error: 'quota_exceeded',
+ retryable: false,
+ message: expect.stringContaining('200/minute'),
+ })
})
- it('denies when the atomic consume reports the run cap is exhausted', async () => {
- // The DB statement returns false when runCount+1+eagerUsed > limit. The
- // exhaustion decision now lives entirely in the single atomic statement,
- // so concurrent callers cannot both pass a remaining-1 budget.
- vi.mocked(sdkDb.resolveQuotaPeriodStart).mockResolvedValue(runPeriod)
- vi.mocked(sdkDb.consumePeriodQuota).mockResolvedValue(false)
+ it('frees the recipe once the trailing window drains (deny at 181, allow at 0)', async () => {
+ const noOverrides = grant({ quotaLimits: {} })
- const result = await consumeQuota('sandbox-recipes', 'sdk-recipe', 'promptBridge', grant())
+ vi.mocked(sdkDb.countRecentInvocations).mockResolvedValue(181)
+ await expect(
+ checkRateLimit('sandbox-recipes', 'sdk-recipe', 'promptBridge', noOverrides)
+ ).resolves.toMatchObject({ ok: false, error: 'quota_exceeded' })
- expect(result).toMatchObject({ ok: false, error: 'quota_exceeded' })
+ // The window is derived from the invocation audit trail (Postgres now()),
+ // so a drained window is simply a lower count — no counter to reset.
+ vi.mocked(sdkDb.countRecentInvocations).mockResolvedValue(0)
+ await expect(
+ checkRateLimit('sandbox-recipes', 'sdk-recipe', 'promptBridge', noOverrides)
+ ).resolves.toEqual({ ok: true })
})
- it('is a no-op success when the grant declares no per-run cap', async () => {
- const result = await consumeQuota(
- 'sandbox-recipes',
- 'sdk-recipe',
- 'promptBridge',
- grant({ quotaLimits: {} })
- )
- expect(result).toEqual({ ok: true })
- expect(sdkDb.consumePeriodQuota).not.toHaveBeenCalled()
+ it('lets a grant-level maxInvocationsPerMinute override win over the platform default', async () => {
+ // Decision §3.1: ENV replaces only the hardcoded fallback constants — a
+ // grant override still wins (`grant value ?? config default`).
+ const withOverride = grant({ quotaLimits: { maxInvocationsPerMinute: 5 } })
+
+ vi.mocked(sdkDb.countRecentInvocations).mockResolvedValue(5)
+ await expect(
+ checkRateLimit('sandbox-recipes', 'sdk-recipe', 'promptBridge', withOverride)
+ ).resolves.toEqual({ ok: true })
+
+ vi.mocked(sdkDb.countRecentInvocations).mockResolvedValue(6)
+ await expect(
+ checkRateLimit('sandbox-recipes', 'sdk-recipe', 'promptBridge', withOverride)
+ ).resolves.toMatchObject({
+ ok: false,
+ error: 'quota_exceeded',
+ message: expect.stringContaining('5/minute'),
+ })
})
})
diff --git a/control-ui/app/plugin-workload-sdk/Views.tsx b/control-ui/app/plugin-workload-sdk/Views.tsx
index 331836c36..4295e4fb6 100644
--- a/control-ui/app/plugin-workload-sdk/Views.tsx
+++ b/control-ui/app/plugin-workload-sdk/Views.tsx
@@ -131,10 +131,6 @@ export function GrantsView({
)
: grant.allowedEventTypes
const quotaParts: string[] = []
- if (grant.quotaLimits.maxRequestsPerRun)
- quotaParts.push(`${grant.quotaLimits.maxRequestsPerRun}/run`)
- if (grant.quotaLimits.maxNotificationsPerRun)
- quotaParts.push(`${grant.quotaLimits.maxNotificationsPerRun}/run`)
if (grant.quotaLimits.maxInvocationsPerMinute)
quotaParts.push(`${grant.quotaLimits.maxInvocationsPerMinute}/min`)
if (grant.quotaLimits.maxNotificationsPerMinute)
@@ -169,7 +165,8 @@ export function GrantsView({
<span className="cu-field__hint"> · users: {userRefsDisplay}</span>
) : null}
</td>
- <td>{quotaParts.length === 0 ? '-' : quotaParts.join(', ')}</td>
+ {/* No grant-level overrides: the platform per-minute ENV rate limits apply. */}
+ <td>{quotaParts.length === 0 ? 'platform defaults' : quotaParts.join(', ')}</td>
<td className="cu-cell--right">
<Button type="button" variant="ghost" size="sm" onClick={() => onEdit(grant)}>
Edit
diff --git a/control-ui/app/plugin-workload-sdk/page.tsx b/control-ui/app/plugin-workload-sdk/page.tsx
index bacaf88cb..c7dae4004 100644
--- a/control-ui/app/plugin-workload-sdk/page.tsx
+++ b/control-ui/app/plugin-workload-sdk/page.tsx
@@ -516,12 +516,6 @@ function GrantFormModal({
cancelled = true
}
}, [])
- const [maxRequestsPerRun, setMaxRequestsPerRun] = useState(
- grant?.quotaLimits.maxRequestsPerRun?.toString() ?? ''
- )
- const [maxNotificationsPerRun, setMaxNotificationsPerRun] = useState(
- grant?.quotaLimits.maxNotificationsPerRun?.toString() ?? ''
- )
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState('')
@@ -627,22 +621,18 @@ function GrantFormModal({
if (!canSubmit) return
setSubmitting(true)
setError('')
- const quotaLimits: PluginWorkloadSdkGrantInput['quotaLimits'] = {}
- const reqRun = Number.parseInt(maxRequestsPerRun, 10)
- if (Number.isFinite(reqRun) && reqRun > 0) quotaLimits.maxRequestsPerRun = reqRun
- const notifRun = Number.parseInt(maxNotificationsPerRun, 10)
- if (Number.isFinite(notifRun) && notifRun > 0) quotaLimits.maxNotificationsPerRun = notifRun
-
// Edit mode: the upsert is a full-column overwrite, and the form does not expose
- // every quota/model field. Round-trip the unexposed fields from the original grant
- // so editing does not silently wipe values configured outside this form.
+ // the quota fields. Round-trip every quota key from the original grant except the
+ // deprecated per-run keys (no longer enforced, issue #348) so editing does not
+ // silently wipe values configured outside this form.
+ const quotaLimits: PluginWorkloadSdkGrantInput['quotaLimits'] = {}
if (grant) {
- if (grant.quotaLimits.maxInvocationsPerMinute !== undefined)
- quotaLimits.maxInvocationsPerMinute = grant.quotaLimits.maxInvocationsPerMinute
- if (grant.quotaLimits.maxNotificationsPerMinute !== undefined)
- quotaLimits.maxNotificationsPerMinute = grant.quotaLimits.maxNotificationsPerMinute
- if (grant.quotaLimits.maxOutputTokens !== undefined)
- quotaLimits.maxOutputTokens = grant.quotaLimits.maxOutputTokens
+ const {
+ maxRequestsPerRun: _d1,
+ maxNotificationsPerRun: _d2,
+ ...keptQuotaLimits
+ } = grant.quotaLimits
+ Object.assign(quotaLimits, keptQuotaLimits)
}
const routingPolicy =
@@ -990,13 +980,13 @@ function GrantFormModal({
</FormSection>
)}
- <FormSection title="Callers & quota">
+ <FormSection title="Callers">
<Field
label="Allowed callers"
htmlFor="sdk-callers"
required
error={callersMissing ? 'At least one caller is required.' : undefined}
- description="Workload ids permitted to call. Comma- or newline-separated."
+ description="Workload ids permitted to call. Comma- or newline-separated. Request rate limits are enforced platform-wide (per-minute) and are not configured per grant."
>
<TextInput
id="sdk-callers"
@@ -1007,31 +997,6 @@ function GrantFormModal({
placeholder="api, worker"
/>
</Field>
- {family === 'promptBridge' ? (
- <Field label="Max requests per run" htmlFor="sdk-maxreq">
- <TextInput
- id="sdk-maxreq"
- compact
- narrow
- type="number"
- min={1}
- value={maxRequestsPerRun}
- onChange={e => setMaxRequestsPerRun(e.target.value)}
- />
- </Field>
- ) : (
- <Field label="Max notifications per run" htmlFor="sdk-maxnotif">
- <TextInput
- id="sdk-maxnotif"
- compact
- narrow
- type="number"
- min={1}
- value={maxNotificationsPerRun}
- onChange={e => setMaxNotificationsPerRun(e.target.value)}
- />
- </Field>
- )}
</FormSection>
{wildcardPresent ? (
diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.ts
index 664044b0e..cbf2c1a89 100644
--- a/control-ui/lib/api.ts
+++ b/control-ui/lib/api.ts
@@ -3228,7 +3228,15 @@ export type PluginWorkloadSdkPromptTarget = {
}
export type PluginWorkloadSdkQuotaLimits = {
+ /**
+ * @deprecated No longer enforced (issue #348); platform per-minute ENV rate
+ * limits apply. Still returned on legacy grants; never sent by this UI.
+ */
maxRequestsPerRun?: number
+ /**
+ * @deprecated No longer enforced (issue #348); platform per-minute ENV rate
+ * limits apply. Still returned on legacy grants; never sent by this UI.
+ */
maxNotificationsPerRun?: number
maxInvocationsPerMinute?: number
maxNotificationsPerMinute?: number
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 047434771..9791393c8 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.413",
+ "version": "0.1.414",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.413",
+ "version": "0.1.414",
"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 d692775df..7505209d4 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.413",
+ "version": "0.1.414",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/deploy/base/control-plane/configmaps.yaml b/deploy/base/control-plane/configmaps.yaml
index 10f0c0b48..ba66e12ca 100644
--- a/deploy/base/control-plane/configmaps.yaml
+++ b/deploy/base/control-plane/configmaps.yaml
@@ -56,6 +56,16 @@ data:
WORKFLOW_APPROVAL_NOTIFICATION_DELIVERY_INTERVAL_MS: "5000"
WORKFLOW_APPROVAL_NOTIFICATION_DELIVERY_BATCH_SIZE: "10"
APPROVAL_RL_REQUEST_PER_MIN: "120"
+ # Plugin Workload SDK platform rate limits (issue #348). Per-run SDK quotas
+ # (maxRequestsPerRun / maxNotificationsPerRun) are deprecated and ignored;
+ # these per-minute windows reset every 60s, so stepless recipes are never
+ # permanently trapped. Values MUST equal the code defaults in
+ # control-api/src/config.ts (200/180/600/600) — the config deploy-mirror
+ # test fails on drift.
+ CONTROL_API_PLUGIN_SDK_NOTIFICATIONS_PER_MIN: "200"
+ CONTROL_API_PLUGIN_SDK_PROMPTBRIDGE_PER_MIN: "180"
+ CONTROL_API_PLUGIN_SDK_REQUEST_BUCKET_PER_MIN: "600"
+ CONTROL_API_PLUGIN_SDK_PREAUTH_PER_MIN: "600"
# Hard ceiling for caller-provided ttlSeconds. Defaults to 48h so a client
# asking for ttlSeconds=604800 (code default) can't freeze a workflow step
# for a full week. Overlays may tighten further for stricter environments.
diff --git a/deploy/overlays/minikube/configmaps/control-api-config.yaml b/deploy/overlays/minikube/configmaps/control-api-config.yaml
index d4d5f41d0..54a4da804 100644
--- a/deploy/overlays/minikube/configmaps/control-api-config.yaml
+++ b/deploy/overlays/minikube/configmaps/control-api-config.yaml
@@ -53,6 +53,15 @@ data:
WORKFLOW_APPROVAL_DEFAULT_TTL_SEC: '86400'
WORKFLOW_APPROVAL_MAX_TTL_SEC: '172800'
WORKFLOW_APPROVAL_EXPIRY_INTERVAL_MS: '60000'
+ # Plugin Workload SDK platform rate limits (issue #348). This overlay is a
+ # FULL-COPY of the base ConfigMap — omitting a key here silently falls back
+ # to code defaults, so all four keys are registered at the code defaults
+ # (200/180/600/600). Per-run SDK quotas are deprecated and ignored; the
+ # per-minute windows reset every 60s.
+ CONTROL_API_PLUGIN_SDK_NOTIFICATIONS_PER_MIN: "200"
+ CONTROL_API_PLUGIN_SDK_PROMPTBRIDGE_PER_MIN: "180"
+ CONTROL_API_PLUGIN_SDK_REQUEST_BUCKET_PER_MIN: "600"
+ CONTROL_API_PLUGIN_SDK_PREAUTH_PER_MIN: "600"
# OSS default: point at the shared registry so a self-hoster browses the
# public catalog out of the box and can run the connect flow (register →
# approve → claim) against it. self-hosted is the only mode that fits an OSS
diff --git a/docs/crds/workflowrecipe.md b/docs/crds/workflowrecipe.md
index 6524194c7..cd6f82397 100644
--- a/docs/crds/workflowrecipe.md
+++ b/docs/crds/workflowrecipe.md
@@ -1375,13 +1375,13 @@ Declaring this block forces an always-on `mcp-host`. Runtime enforcement is addi
| -------------------------------------------- | -------- | --------- | --------------------------------------------------------------------------- |
| `promptBridge.allowedModels` | string[] | No | Max 32. |
| `promptBridge.maxOutputTokens` | integer | No | Min 1. |
-| `promptBridge.maxRequestsPerRun` | integer | No | Min 1. |
+| `promptBridge.maxRequestsPerRun` | integer | No | Min 1. **Deprecated:** accepted but ignored; platform per-minute rate limits apply. Removal planned. |
| `promptBridge.maxConcurrentInvocations` | integer | No | Min 1. Runtime default 5. |
-| `promptBridge.maxInvocationsPerMinute` | integer | No | Min 1. Runtime default 60. |
+| `promptBridge.maxInvocationsPerMinute` | integer | No | Min 1. Platform default 180 when unset (ENV `CONTROL_API_PLUGIN_SDK_PROMPTBRIDGE_PER_MIN`, issue #348). |
| `clientNotifications.allowedEventTypes` | string[] | **Yes**\† | 1–64 entries. |
| `clientNotifications.allowedTargetRefs` | string[] | No | Max 64. |
| `clientNotifications.allowedUserRefs` | boolean | No | Whether `userRef` targets are permitted. |
-| `clientNotifications.maxNotificationsPerRun` | integer | No | Min 1. |
+| `clientNotifications.maxNotificationsPerRun` | integer | No | Min 1. **Deprecated:** accepted but ignored; platform per-minute rate limits apply. Removal planned. |
| `allowedCallers` | string[] | No | Workload ids permitted to call the SDK. **Empty = all declared workloads.** |
| `idempotencyKeyPattern` | string | No | Regex; runtime default `^[a-zA-Z0-9_-]{1,128}$`. Must compile. |
diff --git a/docs/deploy/plugin-workload-sdk-upgrade.md b/docs/deploy/plugin-workload-sdk-upgrade.md
index 252a611a7..54988ad76 100644
--- a/docs/deploy/plugin-workload-sdk-upgrade.md
+++ b/docs/deploy/plugin-workload-sdk-upgrade.md
@@ -47,6 +47,43 @@ or deploy old binaries that cannot understand the attempt ledger. Keep the new
Control API and repair policy rows forward; after the inventory is clean,
re-enable a canary and repeat the readiness and ledger checks.
+## Platform rate limits (issue #348)
+
+The SDK enforces platform-level per-minute rate limits configured through the
+`control-api-config` ConfigMap. The per-run grant quotas `maxRequestsPerRun`
+and `maxNotificationsPerRun` are deprecated: they are still accepted in grant
+payloads for backward compatibility but are ignored by the authorizer. Each
+per-minute window resets every 60 seconds, so a stepless recipe that exhausts
+a window is throttled for at most one minute and is never permanently trapped
+(the failure mode the per-run counters had).
+
+| ENV variable | Default | Limits |
+|---|---|---|
+| `CONTROL_API_PLUGIN_SDK_NOTIFICATIONS_PER_MIN` | `200` | clientNotifications invocations per minute |
+| `CONTROL_API_PLUGIN_SDK_PROMPTBRIDGE_PER_MIN` | `180` | promptBridge invocations per minute |
+| `CONTROL_API_PLUGIN_SDK_REQUEST_BUCKET_PER_MIN` | `600` | shared SDK request bucket per minute |
+| `CONTROL_API_PLUGIN_SDK_PREAUTH_PER_MIN` | `600` | pre-authorization checks per minute |
+
+The defaults above equal the code defaults in `control-api/src/config.ts` and
+are registered in both `deploy/base/control-plane/configmaps.yaml` and the
+full-copy minikube overlay
+`deploy/overlays/minikube/configmaps/control-api-config.yaml`; a drift between
+code and manifests fails the config deploy-mirror test.
+
+### Tuning
+
+Limits are tunable without a code deploy. Edit the key in the
+`control-api-config` ConfigMap for the target environment, then restart the
+Control API so the new environment is picked up:
+
+```bash
+kubectl rollout restart deployment/control-api -n control-plane
+```
+
+Values must be positive integers; the Control API fails loudly at startup on
+an invalid value. See also [production.md](production.md) and
+[minikube.md](minikube.md) for environment-specific deployment procedures.
+
## Minikube gate
Use the branch-owned profile and generated random ports, then run:
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index 6bbe6e013..5afad9914 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.286",
+ "version": "0.1.287",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.286",
+ "version": "0.1.287",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
diff --git a/workflow-recipes/package.json b/workflow-recipes/package.json
index 67b8d7c50..f715aad51 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.286",
+ "version": "0.1.287",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/types.ts b/workflow-recipes/src/types.ts
index 0e26a2edb..4dee7b33c 100644
--- a/workflow-recipes/src/types.ts
+++ b/workflow-recipes/src/types.ts
@@ -483,12 +483,13 @@ export interface PluginWorkloadSdkSpec {
promptBridge?: {
allowedModels?: string[]
maxOutputTokens?: number
+ /** @deprecated Accepted for compatibility; no longer enforced (issue #348). Platform per-minute rate limits apply. */
maxRequestsPerRun?: number
/** Max total bytes across messages[].content. */
maxRequestContentBytes?: number
/** Max parallel promptBridge calls per workload; default 5. */
maxConcurrentInvocations?: number
- /** Rate limit per workload; default 60. */
+ /** Rate limit per workload; platform default 180 when unset (ENV CONTROL_API_PLUGIN_SDK_PROMPTBRIDGE_PER_MIN, issue #348). */
maxInvocationsPerMinute?: number
/** How long invocation results are queryable; default 24. */
resultRetentionHours?: number
@@ -501,8 +502,9 @@ export interface PluginWorkloadSdkSpec {
allowedEventTypes: string[]
allowedTargetRefs?: string[]
allowedUserRefs?: boolean
+ /** @deprecated Accepted for compatibility; no longer enforced (issue #348). Platform per-minute rate limits apply. */
maxNotificationsPerRun?: number
- /** Rate limit per workload; default 120. */
+ /** Rate limit per workload; platform default 200 when unset (ENV CONTROL_API_PLUGIN_SDK_NOTIFICATIONS_PER_MIN, issue #348). */
maxNotificationsPerMinute?: number
/** Default 256. */
maxTitleBytes?: number