Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(agent-platform): cap open approval requests per session (#67967)

Dylan Martin4162a9d057b9
diff --git a/products/agent_platform/docs/identity-and-tools.md b/products/agent_platform/docs/identity-and-tools.md
index f9417bc1f355..a057ccd6f65f 100644
--- a/products/agent_platform/docs/identity-and-tools.md
+++ b/products/agent_platform/docs/identity-and-tools.md
@@ -198,6 +198,14 @@ flowchart LR
q -.-> decide
```
+Open (queued) requests are capped per session by
+`spec.limits.max_open_approvals` (default 10).
+Args-hash dedupe collapses identical re-asks onto their existing row without consuming budget,
+but a model looping on a gated tool with distinct args would otherwise flood approvers —
+one Slack post per queued row.
+At the cap, further gated calls return a synthetic `approval_budget_exhausted` error to the model instead of queueing;
+decisions and TTL expiry free budget.
+
## The two MCP directions
MCP shows up on **both** sides of an agent — don't conflate them:
diff --git a/products/agent_platform/services/agent-runner/src/loop/approval.test.ts b/products/agent_platform/services/agent-runner/src/loop/approval.test.ts
index 565d34dccf85..fba9910db719 100644
--- a/products/agent_platform/services/agent-runner/src/loop/approval.test.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/approval.test.ts
@@ -49,12 +49,19 @@ function makeSession(over: Partial<AgentSession> = {}): AgentSession {
}
/**
- * Minimal stub: queueApprovalResult only calls `upsertQueued` + `findLatestByArgs`
- * on the happy path. The PG-backed wire path is covered by approval-gated e2e.
+ * Minimal stub: queueApprovalResult only calls `upsertQueued`,
+ * `findLatestByArgs`, and `countQueuedBySession`. The PG-backed wire path is
+ * covered by approval-gated e2e. `upserts` records writes so cap cases can
+ * assert no row was created; `queuedCount` / `previous` arm the cap branch.
*/
-function makeStubStore(): ApprovalStore {
+function makeStubStore(
+ opts: { queuedCount?: number; previous?: ApprovalRequest | null } = {}
+): ApprovalStore & { upserts: UpsertApprovalRequestInput[] } {
+ const upserts: UpsertApprovalRequestInput[] = []
return {
+ upserts,
async upsertQueued(input: UpsertApprovalRequestInput): Promise<UpsertApprovalRequestResult> {
+ upserts.push(input)
return {
request: {
id: input.id,
@@ -82,9 +89,12 @@ function makeStubStore(): ApprovalStore {
}
},
async findLatestByArgs(): Promise<ApprovalRequest | null> {
- return null
+ return opts.previous ?? null
},
- } as unknown as ApprovalStore
+ async countQueuedBySession(): Promise<number> {
+ return opts.queuedCount ?? 0
+ },
+ } as unknown as ApprovalStore & { upserts: UpsertApprovalRequestInput[] }
}
const POLICY: ApprovalPolicy = {
@@ -110,6 +120,7 @@ describe('queueApprovalResult: model-facing envelope', () => {
toolCallId: 'tc-1',
args: { note: 'apples' },
policy: POLICY,
+ maxOpenApprovals: 10,
})
const envelope = parseEnvelope((out.content[0] as { text: string }).text)
expect(envelope.approval).toMatchObject({
@@ -131,6 +142,7 @@ describe('queueApprovalResult: model-facing envelope', () => {
toolCallId: 'tc-1',
args: { note: 'apples' },
policy: { ...POLICY, type: 'agent' },
+ maxOpenApprovals: 10,
})
const envelope = parseEnvelope((out.content[0] as { text: string }).text)
expect(envelope.approval).toMatchObject({
@@ -163,11 +175,70 @@ describe('queueApprovalResult: model-facing envelope', () => {
toolCallId: 'tc-1',
args: { note: 'apples' },
policy: POLICY,
+ maxOpenApprovals: 10,
})
const envelope = parseEnvelope((out.content[0] as { text: string }).text)
expect(envelope.approval.approver_hint).not.toBeUndefined()
expect(envelope.approval.approval_url).not.toBeUndefined()
})
+
+ // Per-session cap (`spec.limits.max_open_approvals`): a model looping on
+ // a gated tool with distinct args must not flood approvers. The exhausted
+ // message must name the right decider per policy type (same hint the
+ // queued path uses) — an `agent` policy is decided by an owner/admin, not
+ // the session user, so the model must not tell the user to decide.
+ it.each<['principal' | 'agent', RegExp]>([
+ ['principal', /started this session/i],
+ ['agent', /owner or admin/i],
+ ])('returns approval_budget_exhausted with a %s-aware hint and writes no row at the cap', async (type, hint) => {
+ const store = makeStubStore({ queuedCount: 10 })
+ const out = await queueApprovalResult({
+ approvals: store,
+ session: makeSession(),
+ revisionId: TEST_REV_ID,
+ turn: 1,
+ toolName: '@posthog/memory-write',
+ toolCallId: 'tc-cap',
+ args: { note: 'one too many' },
+ policy: { ...POLICY, type },
+ maxOpenApprovals: 10,
+ })
+ const body = JSON.parse((out.content[0] as { text: string }).text) as {
+ error?: { code: string; message: string }
+ }
+ expect(body.error?.code).toBe('approval_budget_exhausted')
+ expect(body.error?.message).toContain('10')
+ expect(body.error?.message).toMatch(hint)
+ // No row written, and no `queued` details → the driver skips the
+ // approval card + Slack buttons for this result.
+ expect(store.upserts).toHaveLength(0)
+ expect(out.details?.queued).toBeUndefined()
+ expect(out.terminate).toBe(false)
+ })
+
+ it('an identical re-ask past the cap still dedupes onto its existing queued row', async () => {
+ const previous = {
+ state: 'queued',
+ decision_reason: null,
+ } as ApprovalRequest
+ const store = makeStubStore({ queuedCount: 10, previous })
+ const out = await queueApprovalResult({
+ approvals: store,
+ session: makeSession(),
+ revisionId: TEST_REV_ID,
+ turn: 2,
+ toolName: '@posthog/memory-write',
+ toolCallId: 'tc-dedupe',
+ args: { note: 'same ask again' },
+ policy: POLICY,
+ maxOpenApprovals: 10,
+ })
+ // The upsert dedupes server-side; the point is the cap didn't block
+ // the re-ask (which doesn't grow the approver queue).
+ const envelope = parseEnvelope((out.content[0] as { text: string }).text)
+ expect(envelope.approval.state).toBe('queued')
+ expect(store.upserts).toHaveLength(1)
+ })
})
describe('dispatchApprovedResult: proxy-routed resume', () => {
diff --git a/products/agent_platform/services/agent-runner/src/loop/approval.ts b/products/agent_platform/services/agent-runner/src/loop/approval.ts
index 2d40ad8011ae..1eaa5a491c0c 100644
--- a/products/agent_platform/services/agent-runner/src/loop/approval.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/approval.ts
@@ -63,6 +63,15 @@ export function approvalMarkerRequestId(msg: ConversationMessage): string | null
/**
* Gated-tool `execute`: upsert the queued row, return the synthetic queued
* result. `terminate` is false — the model reads the envelope and continues.
+ *
+ * Capped at `maxOpenApprovals` open (queued) rows per session
+ * (`spec.limits.max_open_approvals`): a model looping on a gated tool with
+ * distinct args would otherwise flood approvers — args-hash dedupe only
+ * collapses identical calls. An identical re-ask dedupes onto its existing
+ * queued row and is always allowed; only a call that would insert a NEW row
+ * counts against the cap. At the cap the model receives a synthetic
+ * `approval_budget_exhausted` error (no row written, no approver ping) and
+ * continues the turn.
*/
export async function queueApprovalResult(input: {
approvals: ApprovalStore
@@ -74,11 +83,48 @@ export async function queueApprovalResult(input: {
toolCallId: string
args: Record<string, unknown>
policy: ApprovalPolicy
+ maxOpenApprovals: number
}): Promise<AgentToolResult<ToolResultDetails>> {
const argsHash = hashCanonicalArgs(input.args)
const previous = await input.approvals.findLatestByArgs(input.session.id, input.toolName, argsHash)
const lastAssistant = findLastAssistant(input.session.conversation)
+ // An identical re-ask (existing `queued` row) is exempt from the cap: it
+ // dedupes onto that row via the partial unique index without growing the
+ // approver queue, so blocking it would spuriously reject a legitimate
+ // retry. Keep the dedupe exemption ahead of the cap check — reordering
+ // them so the cap runs first breaks that. The exemption opens a bounded
+ // TOCTOU: if an approver decides the queued row between `findLatestByArgs`
+ // and `upsertQueued`, the insert no longer conflicts and a new row lands
+ // uncapped (cap+1). It's self-correcting — that same decision freed a slot
+ // — so overshoot is bounded at 1 per concurrent decision.
+ if (previous?.state !== 'queued') {
+ const open = await input.approvals.countQueuedBySession(input.session.id)
+ if (open >= input.maxOpenApprovals) {
+ // Same policy-aware phrasing as the queued path's `approver_hint`:
+ // `agent` policies are decided by an owner/admin, not the session user.
+ const approverHint = input.policy.type === 'agent' ? APPROVER_HINT_AGENT : APPROVER_HINT_PRINCIPAL
+ return {
+ content: [
+ {
+ type: 'text',
+ text: JSON.stringify({
+ error: {
+ code: 'approval_budget_exhausted',
+ message:
+ `this session already has ${open} approval request(s) awaiting a decision ` +
+ `(limit ${input.maxOpenApprovals}). The call was NOT queued. Do not re-issue ` +
+ `gated calls; the pending requests must be decided by ${approverHint} first.`,
+ },
+ }),
+ },
+ ],
+ details: {},
+ terminate: false,
+ }
+ }
+ }
+
const upsert = await input.approvals.upsertQueued({
id: randomUUID(),
session_id: input.session.id,
diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.ts b/products/agent_platform/services/agent-runner/src/loop/driver.ts
index 8f84d73361a0..a75f4a6867b2 100644
--- a/products/agent_platform/services/agent-runner/src/loop/driver.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/driver.ts
@@ -552,6 +552,13 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps
}
{
const approvals = deps.approvals
+ // pi-agent-core Promise.alls a turn's tool calls, so two gated
+ // calls in one turn would both pass the max_open_approvals count
+ // check before either row lands. Chain the count+insert critical
+ // section instead: one worker owns a session run (queue claim is
+ // exclusive), so an in-process chain is a sufficient lock — no
+ // other process inserts queued rows for this session.
+ let gateChain: Promise<unknown> = Promise.resolve()
// Shared by the static wrap and the dynamic proxy wrap. Every gated
// call queues for a human decision — being the asker is not consent
// to the specific call (the model could have been steered by content
@@ -562,17 +569,22 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps
args: Record<string, unknown>,
policy: ApprovalPolicy
): Promise<AgentToolResult<ToolResultDetails>> => {
- const queued = await queueApprovalResult({
- approvals,
- buildApprovalUrl: deps.buildApprovalUrl,
- session,
- revisionId: rev.id,
- turn,
- toolName,
- toolCallId,
- args,
- policy,
- })
+ const run = gateChain.then(() =>
+ queueApprovalResult({
+ approvals,
+ buildApprovalUrl: deps.buildApprovalUrl,
+ session,
+ revisionId: rev.id,
+ turn,
+ toolName,
+ toolCallId,
+ args,
+ policy,
+ maxOpenApprovals: rev.spec.limits.max_open_approvals,
+ })
+ )
+ gateChain = run.catch(() => undefined)
+ const queued = await run
// `principal` + Slack: post Approve/Reject buttons in-thread
// (best-effort; skip a deduped re-queue).
const reqId = queued.details?.requestId
diff --git a/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts b/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts
index 3f0e7f815ad2..83f32d81f487 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts
@@ -201,6 +201,8 @@ export interface ApprovalStore {
countQueuedByTeam(teamId: number): Promise<number>
/** Count `queued` rows for one application — drives the per-agent badge. */
countQueuedByApplication(applicationId: string): Promise<number>
+ /** Count `queued` rows for one session — drives the per-session open-approvals cap. */
+ countQueuedBySession(sessionId: string): Promise<number>
}
/**
diff --git a/products/agent_platform/services/agent-shared/src/persistence/pg-approval-store.ts b/products/agent_platform/services/agent-shared/src/persistence/pg-approval-store.ts
index 7bef8c158205..523bea4de133 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/pg-approval-store.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/pg-approval-store.ts
@@ -187,6 +187,16 @@ export class PgApprovalStore implements ApprovalStore {
return Number(r.rows[0]?.count ?? 0)
}
+ async countQueuedBySession(sessionId: string): Promise<number> {
+ const r = await this.pool.query<{ count: string }>(
+ `SELECT COUNT(*)::text AS count
+ FROM agent_tool_approval_request
+ WHERE session_id = $1 AND state = 'queued'`,
+ [sessionId]
+ )
+ return Number(r.rows[0]?.count ?? 0)
+ }
+
private async runList(
whereSeed: string,
seedParams: unknown[],
diff --git a/products/agent_platform/services/agent-shared/src/spec/spec.ts b/products/agent_platform/services/agent-shared/src/spec/spec.ts
index 3cf576234e79..88a37c607e00 100644
--- a/products/agent_platform/services/agent-shared/src/spec/spec.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/spec.ts
@@ -771,6 +771,17 @@ export const SpecLimitsSchema = z.object({
// Per-turn provider max_tokens. Unset → reasoning-aware default in runner.
// Clamped at request time to model.maxTokens + operator override.
max_output_tokens: z.number().int().positive().max(200_000).optional(),
+ /**
+ * Cap on open (queued) approval requests per session. A model looping on
+ * an approval-gated tool can otherwise flood approvers — Slack posts per
+ * queued row, console badge inflation — because args-hash dedupe only
+ * collapses identical calls, not distinct-args floods. At the cap,
+ * further gated calls return a synthetic `approval_budget_exhausted`
+ * error to the model instead of queueing. Decisions and TTL expiry free
+ * budget; an identical re-ask dedupes onto its existing row and is
+ * always allowed.
+ */
+ max_open_approvals: z.number().int().positive().max(100).default(10),
})
export type AuthMode = z.infer<typeof AuthModeSchema>
@@ -1010,6 +1021,7 @@ export const AgentSpecSchema = z.object({
max_wall_seconds: 15 * 60,
max_memory_mb: 512,
max_cpu_cores: 0.25,
+ max_open_approvals: 10,
}),
reasoning: ReasoningEffortSchema.describe(
'Spec-wide default reasoning effort, applied to every model unless a model policy entry overrides it. Omit for the provider default.'
diff --git a/products/agent_platform/services/agent-tests/src/cases/approval-gated.test.ts b/products/agent_platform/services/agent-tests/src/cases/approval-gated.test.ts
index 838381b54b5b..7125fda3a795 100644
--- a/products/agent_platform/services/agent-tests/src/cases/approval-gated.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/approval-gated.test.ts
@@ -1,7 +1,7 @@
/**
* Approval-gated tools: real e2e contract for v0.
*
- * Pins the wire-level behaviour for approval-gated tools. The seven cases below
+ * Pins the wire-level behaviour for approval-gated tools. The cases below
* collectively cover the loop:
*
* model proposes a gated call
@@ -585,4 +585,50 @@ describe('approval-gated tools: real e2e', () => {
expect(queued!.approver_hint).not.toBeUndefined()
expect(session!.trigger_metadata).toEqual({ kind: 'chat', supported_client_tools: ['connect_mcp'] })
})
+
+ // ─────────────────────────────────────────────────────────────
+ // Case 9 — per-session open-approvals cap (spec.limits.max_open_approvals).
+ // Distinct-args gated calls past the cap must NOT queue (args-hash dedupe
+ // only collapses identical calls); the model gets a synthetic
+ // approval_budget_exhausted error and the turn continues.
+ // ─────────────────────────────────────────────────────────────
+ it('case 9: gated calls past max_open_approvals return budget-exhausted, not a new row', async () => {
+ c.setScript([
+ fauxToolUse([
+ fauxToolCall('@posthog/query', { project_id: 1, query: 'first — queues' }),
+ fauxToolCall('@posthog/query', { project_id: 1, query: 'second — over budget' }),
+ ]),
+ fauxText('cap done'),
+ ])
+ const { application } = await c.deployAgent({
+ slug: 'gated-9',
+ spec: {
+ tools: [
+ {
+ kind: 'native',
+ id: '@posthog/query',
+ requires_approval: true,
+ approval_policy: { allow_edit: false },
+ },
+ ],
+ limits: { max_open_approvals: 1 },
+ },
+ })
+ const run = await request(c.ingress).post('/agents/gated-9/run').send({ message: 'flood' })
+ await c.drain()
+
+ // Exactly one row queued — the second call was capped, not written.
+ const rows = await listApprovals(application.id, 'queued')
+ expect(rows).toHaveLength(1)
+
+ const session = await c.queue.get(run.body.session_id)
+ expect(findApproval(session!.conversation, 'queued')).not.toBeNull()
+ const exhausted = session!.conversation.filter((m) => {
+ const cast = m as { role: string; content?: unknown }
+ return (
+ cast.role === 'toolResult' && JSON.stringify(cast.content ?? '').includes('approval_budget_exhausted')
+ )
+ })
+ expect(exhausted).toHaveLength(1)
+ })
})