From f6139147fd989ffcf69900f8d0d6cb4dbd475efa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Filip=20Kujund=C5=BEi=C4=87?= <51266541+404oops@users.noreply.github.com> Date: Sat, 14 Nov 2026 08:23:04 +0100 Subject: [PATCH] Hold the AI concurrency slot until a detached chat completion settles (#4615) A chat completion keeps running for up to 10 minutes after the caller hangs up, so the upstream can report usage. It now counts against the caller's concurrency cap for as long as the upstream runs, instead of until the response closes. - The chat driver registers its upstream run with the request's concurrency slot, so `/drivers/call` keeps the slot until the upstream is done. The cleanup after it does not hold the slot. - The route concurrency gate now uses the same CallSlot as `/drivers/call`: the slot is held until the response is done and the work the handler registered has settled. The OpenAI- and Anthropic-compatible chat routes register the completion, so a non-streaming call counts until the upstream answers too. - CallSlot moves to core/http, since the route gate below the controllers uses it. The context key is renamed keepConcurrencySlot. - rate-limits-and-quotas.md says a completion counts until the model finishes it, even after a disconnect. Co-authored-by: Daniel Salazar --- .../DriverController.concurrent.test.ts | 2 +- .../controllers/drivers/DriverController.ts | 7 +- .../controllers/puterai/PuterAIController.ts | 9 +- src/backend/core/context.ts | 10 +- .../drivers => core/http}/callSlot.test.ts | 0 .../drivers => core/http}/callSlot.ts | 8 +- src/backend/core/http/middleware/rateLimit.js | 24 +- .../core/http/middleware/rateLimit.test.js | 22 ++ src/backend/core/http/types.ts | 18 +- ...tCompletionDriver.concurrency.http.test.ts | 225 ++++++++++++++++++ .../chat/ChatCompletionDriver.edges.test.ts | 37 +++ .../interfaces/chat/ChatCompletionDriver.ts | 14 +- src/backend/drivers/ai/shared/polling.test.ts | 2 +- src/backend/drivers/ai/shared/polling.ts | 2 +- src/backend/server.ts | 3 +- src/docs/src/rate-limits-and-quotas.md | 2 + 16 files changed, 340 insertions(+), 45 deletions(-) rename src/backend/{controllers/drivers => core/http}/callSlot.test.ts (100%) rename src/backend/{controllers/drivers => core/http}/callSlot.ts (90%) create mode 100644 src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.concurrency.http.test.ts diff --git a/src/backend/controllers/drivers/DriverController.concurrent.test.ts b/src/backend/controllers/drivers/DriverController.concurrent.test.ts index 81eeddcad..60dd59ea9 100644 --- a/src/backend/controllers/drivers/DriverController.concurrent.test.ts +++ b/src/backend/controllers/drivers/DriverController.concurrent.test.ts @@ -324,7 +324,7 @@ describe('DriverController — concurrent acquire/release', () => { const driver = { ...makeSyntheticDriver(), ping: async () => { - Context.get('keepDriverSlot')?.( + Context.get('keepConcurrencySlot')?.( new Promise((resolve) => { settleWork = resolve; }), diff --git a/src/backend/controllers/drivers/DriverController.ts b/src/backend/controllers/drivers/DriverController.ts index ed18e7f81..014dc636b 100644 --- a/src/backend/controllers/drivers/DriverController.ts +++ b/src/backend/controllers/drivers/DriverController.ts @@ -51,7 +51,7 @@ import { PermissionUtil } from '../../services/permission/permissionUtil.js'; import type { WithLifecycle } from '../../types'; import { withSpan } from '../../util/span.js'; import { PuterController } from '../types.js'; -import { CallSlot } from './callSlot.js'; +import { CallSlot } from '../../core/http/callSlot.js'; type DriverInstance = WithLifecycle & Record; @@ -337,8 +337,7 @@ export class DriverController extends PuterController { if (req.actor) { const permService = this.services.permission as unknown as - | PermissionService - | undefined; + PermissionService | undefined; if (permService) { // Build via PermissionUtil.join so any `:` in a driver or // interface name is escaped — raw interpolation would let a @@ -446,7 +445,7 @@ export class DriverController extends PuterController { }); } slot.attach(handle, res); - Context.set('keepDriverSlot', (work) => slot.keep(work)); + Context.set('keepConcurrencySlot', (work) => slot.keep(work)); } // Stash the requested driver name in Context so multi-provider diff --git a/src/backend/controllers/puterai/PuterAIController.ts b/src/backend/controllers/puterai/PuterAIController.ts index 0d2565666..28b226efa 100644 --- a/src/backend/controllers/puterai/PuterAIController.ts +++ b/src/backend/controllers/puterai/PuterAIController.ts @@ -1304,13 +1304,18 @@ export class PuterAIController extends PuterController { return driver; } - /** A completion that stops, and stops billing, when the caller hangs up. */ + /** + * A completion whose caller may hang up. It runs on to its usage report + * either way, so it holds the route's concurrency slot until it settles. + */ #complete( res: Response, args: ICompleteArguments, ): Promise { Context.set('abortSignal', abortOnDisconnect(res)); - return this.#driver().complete(args); + const completion = this.#driver().complete(args); + Context.get('keepConcurrencySlot')?.(completion); + return completion; } } diff --git a/src/backend/core/context.ts b/src/backend/core/context.ts index 02ccce4e2..f8f8cd637 100644 --- a/src/backend/core/context.ts +++ b/src/backend/core/context.ts @@ -69,11 +69,11 @@ export interface KnownContextFields { */ abortSignal: AbortSignal; /** - * Keeps the call's concurrency slot until `work` settles (set by - * DriverController when the method is capped), for work that outlives the - * response. + * Keeps the request's concurrency slot until `work` settles, for work that + * outlives the response. Set by DriverController for a capped method and by + * the route concurrency gate. */ - keepDriverSlot: (work: Promise) => void; + keepConcurrencySlot: (work: Promise) => void; /** * Aborts the chat driver's upstream request. A client disconnect doesn't * fire it: the upstream bills a request it has accepted either way, so the @@ -102,7 +102,7 @@ const KNOWN_KEY_FLAGS: Record = { requestId: true, driverName: true, abortSignal: true, - keepDriverSlot: true, + keepConcurrencySlot: true, upstreamSignal: true, strictUpstreamErrors: true, platformWrite: true, diff --git a/src/backend/controllers/drivers/callSlot.test.ts b/src/backend/core/http/callSlot.test.ts similarity index 100% rename from src/backend/controllers/drivers/callSlot.test.ts rename to src/backend/core/http/callSlot.test.ts diff --git a/src/backend/controllers/drivers/callSlot.ts b/src/backend/core/http/callSlot.ts similarity index 90% rename from src/backend/controllers/drivers/callSlot.ts rename to src/backend/core/http/callSlot.ts index 4402c828a..f4a959ff9 100644 --- a/src/backend/controllers/drivers/callSlot.ts +++ b/src/backend/core/http/callSlot.ts @@ -18,7 +18,7 @@ */ import type { Response } from 'express'; -import { onResponseClose } from '../../core/http/onResponseClose.js'; +import { onResponseClose } from './onResponseClose.js'; // Under the concurrency store's one-hour orphan TTL. const SLOT_RENEW_MS = 10 * 60 * 1000; @@ -29,9 +29,9 @@ interface SlotHandle { } /** - * A driver call's concurrency slot, held until the response is done and the - * call's work has settled, including work a driver carries on after the caller - * hung up or was answered. + * A request's concurrency slot, held until the response is done and the work + * registered with `keep` has settled, including work that carries on after the + * caller hung up or was answered. */ export class CallSlot { #handle?: SlotHandle; diff --git a/src/backend/core/http/middleware/rateLimit.js b/src/backend/core/http/middleware/rateLimit.js index 86f92f8ef..ea4453ee1 100644 --- a/src/backend/core/http/middleware/rateLimit.js +++ b/src/backend/core/http/middleware/rateLimit.js @@ -20,8 +20,9 @@ import crypto from 'node:crypto'; import { withSpan } from '../../../util/span.js'; +import { Context } from '../../context.js'; +import { CallSlot } from '../callSlot.js'; import { HttpError } from '../HttpError.js'; -import { onResponseClose } from '../onResponseClose.js'; import { subscriptionOverride } from '../../../services/metering/consts.js'; /** @@ -413,8 +414,8 @@ async function peekKv(kv, key, limit) { // // Lifecycle is the wedge between rate and concurrent limits: rate just // records a tick, concurrent has to track "still in flight" → "done" -// across a request boundary. The route middleware hooks `res.finish` / -// `res.close`; the driver helper wraps the invocation in `try/finally`. +// across a request boundary. The route middleware and the driver controller +// both hold the slot in a `CallSlot`. // Orphan TTL safety nets — used when the process dies between acquire // and release. Memory backend doesn't need one (the process is also @@ -1138,8 +1139,9 @@ async function resolveSubscriptionLimit(req, opts) { * bySubscription: { user_free: 2, unlimited: 50 } } } { concurrent: { limit: * 10, backend: 'redis', scope: 'expensive-op' } } * - * On accept, schedules release on `res.finish` / `res.close` so even aborted - * requests give their slot back. On reject, 429 with the same + * On accept, holds the slot until the response is done and any work the handler + * registered through `keepConcurrencySlot` has settled, so work that outlives a + * caller who hung up still counts. On reject, 429 with the same * `too_many_requests` legacyCode as the rate gate (clients already handle that * branch). Fails open on backend error. */ @@ -1165,13 +1167,11 @@ export function concurrencyGate(opts) { return; } - // `finish` (response sent) and `close` (connection closed, possibly - // aborted before finish) can both fire; the guard releases once. - const { release } = guardSlot(slot, '[concurrent]'); - const onDone = () => void release(); - res.once('finish', onDone); - onResponseClose(res, onDone); - if (res.destroyed || res.writableFinished) onDone(); + const held = new CallSlot(); + held.attach(guardSlot(slot, '[concurrent]'), res); + if (Context.current()) { + Context.set('keepConcurrencySlot', (work) => held.keep(work)); + } next(); }; } diff --git a/src/backend/core/http/middleware/rateLimit.test.js b/src/backend/core/http/middleware/rateLimit.test.js index 39f594aef..44cc8ffea 100644 --- a/src/backend/core/http/middleware/rateLimit.test.js +++ b/src/backend/core/http/middleware/rateLimit.test.js @@ -29,6 +29,7 @@ import { vi, } from 'vitest'; import { EventEmitter } from 'node:events'; +import { Context, runWithContext } from '../../context.js'; import { isHttpError } from '../HttpError.js'; import { setupTestServer } from '../../../testUtil.ts'; import { @@ -977,6 +978,27 @@ describe('concurrencyGate — memory backend', () => { expect(isHttpError(third.err)).toBe(true); }); + it('holds the slot past the response for work the handler keeps', async () => { + const opts = { limit: 1, key: 'ip', scope: 'cg-kept-work' }; + let finishWork; + const work = new Promise((resolve) => { + finishWork = resolve; + }); + const res = makeRes(); + await runWithContext({}, async () => { + await concurrencyGate(opts)(baseReq(), res, () => { + Context.get('keepConcurrencySlot')(work); + }); + }); + res.emit('close'); + await new Promise((r) => setImmediate(r)); + expect((await runGate(opts, baseReq())).err?.statusCode).toBe(429); + + finishWork(); + await new Promise((r) => setImmediate(r)); + expect((await runGate(opts, baseReq())).err).toBeUndefined(); + }); + it('different keys do not share slots', async () => { const opts = { limit: 1, key: 'ip', scope: 'cg-keyed' }; const a = await runGate(opts, baseReq({ ip: '1.1.1.1' })); diff --git a/src/backend/core/http/types.ts b/src/backend/core/http/types.ts index 3f84f6bd2..fc0edaa70 100644 --- a/src/backend/core/http/types.ts +++ b/src/backend/core/http/types.ts @@ -28,12 +28,7 @@ import type { Actor } from '../actor'; * it instead of accepting any token that authenticates. */ export type TokenSource = - | 'body' - | 'header' - | 'x-api-key' - | 'cookie' - | 'query' - | 'handshake'; + 'body' | 'header' | 'x-api-key' | 'cookie' | 'query' | 'handshake'; /** Express router methods plus the WebDAV verbs some endpoints use. */ export type RouteMethod = @@ -263,10 +258,10 @@ export interface RouteOptions { rateLimit?: RouteRateLimit | RouteRateLimit[]; /** - * Cap simultaneous in-flight requests per key; slots are released on - * response finish or close. `bySubscription` overrides `limit` per - * `SubscriptionPolicy.id` when metering is wired in. `key`, `scope`, - * `backend` as in `rateLimit`. + * Cap simultaneous in-flight requests per key; a slot is released once the + * response is done and any work the handler kept it for has settled. + * `bySubscription` overrides `limit` per `SubscriptionPolicy.id` when + * metering is wired in. `key`, `scope`, `backend` as in `rateLimit`. */ concurrent?: { limit: number; @@ -368,8 +363,7 @@ type AuthImplyingOptions = | { requireCardVerified: true } | { requireAnyVerified: - | readonly VerificationFactor[] - | VerificationFactor[]; + readonly VerificationFactor[] | VerificationFactor[]; } | { requireSubscription: true | readonly string[] | string[] } | { requireReputation: string }; diff --git a/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.concurrency.http.test.ts b/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.concurrency.http.test.ts new file mode 100644 index 000000000..467777a1c --- /dev/null +++ b/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.concurrency.http.test.ts @@ -0,0 +1,225 @@ +/* + * Copyright (C) 2024-present Puter Technologies Inc. + * + * This file is part of Puter. + * + * Puter is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import { createServer, type Server, type ServerResponse } from 'node:http'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { setupPuterTestEnv, type PuterTestEnv } from '../../../../testUtil.js'; + +/** + * A completion runs on to its usage report after the caller hangs up, so it + * keeps counting against the caller's concurrency cap until it settles. + */ +describe('chat concurrency over HTTP after the caller hangs up', () => { + let upstream: Server; + let env: PuterTestEnv; + let onRequest: (res: ServerResponse, body: string) => void; + + beforeAll(async () => { + upstream = createServer((req, res) => { + if (req.url === '/api/tags') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ models: [{ name: 'slot-test' }] })); + return; + } + let body = ''; + req.setEncoding('utf8'); + req.on('data', (chunk: string) => { + body += chunk; + }); + req.once('end', () => onRequest(res, body)); + }); + await new Promise((resolve) => + upstream.listen(0, '127.0.0.1', resolve), + ); + const port = (upstream.address() as { port: number }).port; + env = await setupPuterTestEnv({ + providers: { + ollama: { apiBaseUrl: `http://127.0.0.1:${port}` }, + }, + meteringEnforcement: { subscriptions: false }, + } as never); + await vi.waitFor(async () => { + expect( + (await env.server.drivers.aiChat.models()).some( + (model) => model.id === 'ollama:ollama/slot-test', + ), + ).toBe(true); + }); + }, 120_000); + + afterAll(async () => { + await env?.shutdown(); + upstream?.closeAllConnections(); + if (upstream) + await new Promise((resolve) => + upstream.close(() => resolve()), + ); + }); + + const call = (route: string, stream: boolean, signal?: AbortSignal) => { + const args = { + model: 'ollama:ollama/slot-test', + stream, + messages: [{ role: 'user', content: 'hi' }], + max_tokens: 16, + }; + return fetch(new URL(route, env.apiOrigin), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${env.users.user.apiToken}`, + Origin: env.apiOrigin, + }, + body: JSON.stringify( + route === '/drivers/call' + ? { + interface: 'puter-chat-completion', + method: 'complete', + args, + } + : args, + ), + signal, + }); + }; + + const usage = { prompt_tokens: 3, completion_tokens: 5, total_tokens: 8 }; + const chunk = (delta: object, finish: string | null, extra = {}) => + `data: ${JSON.stringify({ + id: 'chatcmpl_1', + object: 'chat.completion.chunk', + choices: [{ index: 0, delta, finish_reason: finish }], + ...extra, + })}\n\n`; + + const finishAnswer = (res: ServerResponse, body: string) => { + if (!(JSON.parse(body) as { stream?: boolean }).stream) { + res.setHeader('Content-Type', 'application/json'); + res.end( + JSON.stringify({ + id: 'chatcmpl_1', + object: 'chat.completion', + created: 0, + model: 'slot-test', + choices: [ + { + index: 0, + message: { role: 'assistant', content: 'done' }, + finish_reason: 'stop', + }, + ], + usage, + }), + ); + return; + } + if (!res.headersSent) + res.setHeader('Content-Type', 'text/event-stream'); + res.end( + `${chunk({ content: 'done' }, 'stop')}data: ${JSON.stringify({ + id: 'chatcmpl_1', + object: 'chat.completion.chunk', + choices: [], + usage, + })}\n\ndata: [DONE]\n\n`, + ); + }; + + /** Starts a completion, waits until it is generating, then hangs up. */ + const abandon = async (route: string, stream: boolean) => { + let received!: () => void; + const reached = new Promise((resolve) => { + received = resolve; + }); + const pending: { res: ServerResponse; body: string }[] = []; + onRequest = (res, body) => { + pending.push({ res, body }); + if (stream) { + res.setHeader('Content-Type', 'text/event-stream'); + res.write(chunk({ role: 'assistant', content: 'partial' }, null)); + } + received(); + }; + const abort = new AbortController(); + const request = call(route, stream, abort.signal); + const outcome = await Promise.race([ + reached.then(() => 'generating' as const), + request.then((response) => response), + ]); + if (outcome !== 'generating') { + return { refused: outcome, pending }; + } + if (stream) { + const response = await request; + const reader = response.body!.getReader(); + let text = ''; + while (!text.includes('partial')) { + const { value, done } = await reader.read(); + if (done) break; + text += new TextDecoder().decode(value); + } + } + abort.abort(); + await request.catch(() => undefined); + return { refused: undefined, pending }; + }; + + it.each([ + { route: '/drivers/call', stream: true }, + { route: '/drivers/call', stream: false }, + { route: '/puterai/openai/v1/chat/completions', stream: true }, + { route: '/puterai/openai/v1/chat/completions', stream: false }, + { route: '/puterai/anthropic/v1/messages', stream: true }, + ])( + 'counts an abandoned completion until it settles: $route (stream=$stream)', + async ({ route, stream }) => { + const running: { res: ServerResponse; body: string }[] = []; + let refused: Response | undefined; + try { + for (let i = 0; i < 25 && !refused; i++) { + const attempt = await abandon(route, stream); + running.push(...attempt.pending); + refused = attempt.refused; + // Let the server see the hang-up before the next call. + await new Promise((resolve) => setTimeout(resolve, 50)); + } + expect(refused?.status).toBe(429); + expect(await refused!.text()).toContain( + 'Too many concurrent requests', + ); + expect(running.length).toBeGreaterThan(0); + + for (const { res, body } of running.splice(0)) + finishAnswer(res, body); + onRequest = finishAnswer; + await expect + .poll(async () => (await call(route, false)).status, { + timeout: 15_000, + }) + .toBe(200); + } finally { + for (const { res, body } of running) finishAnswer(res, body); + upstream.closeAllConnections(); + // The next case starts with a fresh rate-limit window. + await new Promise((resolve) => setTimeout(resolve, 10_100)); + } + }, + 60_000, + ); +}); diff --git a/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.edges.test.ts b/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.edges.test.ts index 2e411dbc2..0c0ab3016 100644 --- a/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.edges.test.ts +++ b/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.edges.test.ts @@ -1231,4 +1231,41 @@ describe('ChatCompletionDriver streaming failure handling', () => { expect(events).toContainEqual({ type: 'text', text: 'hello' }); expect(cleanup).toHaveBeenCalledTimes(1); }); + + it('frees the concurrency slot before the provider cleanup hook finishes', async () => { + let finishCleanup!: () => void; + const cleanup = vi.fn( + () => + new Promise((resolve) => { + finishCleanup = resolve; + }), + ); + vi.spyOn(FakeChatProvider.prototype, 'complete').mockResolvedValue({ + stream: true, + init_chat_stream: async ({ + chatStream, + }: { + chatStream: { end: (usage?: Record) => void }; + }) => { + chatStream.end({ input_tokens: 1, output_tokens: 1 }); + }, + finally_fn: cleanup, + } as never); + + const kept: Promise[] = []; + const result = (await withTestActor(() => { + Context.set('keepConcurrencySlot', (work) => kept.push(work)); + return fakeOnlyDriver.complete({ + model: 'fake', + messages: [{ role: 'user', content: 'hi' }], + stream: true, + } as never); + })) as unknown as { stream: Readable }; + await collect(result.stream); + + expect(kept).toHaveLength(1); + await kept[0]; + await vi.waitFor(() => expect(cleanup).toHaveBeenCalledTimes(1)); + finishCleanup(); + }); }); diff --git a/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.ts b/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.ts index b6cf1932e..05c1d9d41 100644 --- a/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.ts +++ b/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.ts @@ -1308,8 +1308,17 @@ export class ChatCompletionDriver extends PuterDriver { }, HOLD_RENEW_INTERVAL_MS); renewHold.unref?.(); - // Fire-and-forget — the stream writes happen async while the - // response is being piped to the client. + // The upstream runs on after a caller hangs up, so the request + // keeps its concurrency slot until the upstream is done, not until + // the cleanup after it. + let upstreamDone!: () => void; + const upstreamRunning = new Promise((resolve) => { + upstreamDone = resolve; + }); + Context.get('keepConcurrencySlot')?.(upstreamRunning); + + // The stream writes happen async while the response is piped to + // the client. (async () => { try { await init({ chatStream }); @@ -1334,6 +1343,7 @@ export class ChatCompletionDriver extends PuterDriver { } passthrough.end(); } finally { + upstreamDone(); clearInterval(renewHold); clearTimeout(detachedLimit); abortSignal?.removeEventListener('abort', detachStream); diff --git a/src/backend/drivers/ai/shared/polling.test.ts b/src/backend/drivers/ai/shared/polling.test.ts index 7f1991f8a..e9535d786 100644 --- a/src/backend/drivers/ai/shared/polling.test.ts +++ b/src/backend/drivers/ai/shared/polling.test.ts @@ -362,7 +362,7 @@ describe('pollUntilSettled', () => { const kept: Promise[] = []; const rejection = rejectionOf( runWithContext({}, () => { - Context.set('keepDriverSlot', (work) => kept.push(work)); + Context.set('keepConcurrencySlot', (work) => kept.push(work)); return pollUntilSettled({ provider: 'together', providerLabel: 'Together AI', diff --git a/src/backend/drivers/ai/shared/polling.ts b/src/backend/drivers/ai/shared/polling.ts index a964c5a68..1c5928d32 100644 --- a/src/backend/drivers/ai/shared/polling.ts +++ b/src/backend/drivers/ai/shared/polling.ts @@ -184,7 +184,7 @@ export const pollUntilSettled = async (opts: PollOptions): Promise => { } if (Date.now() - start > windowMs) { const late = followLateJob(opts, job, opts.hold.take()); - Context.get('keepDriverSlot')?.(late); + Context.get('keepConcurrencySlot')?.(late); throw pollTimeoutError( opts.provider, opts.providerLabel, diff --git a/src/backend/server.ts b/src/backend/server.ts index 670a8f79a..10255f03e 100644 --- a/src/backend/server.ts +++ b/src/backend/server.ts @@ -1327,7 +1327,8 @@ export class PuterServer { // 2b'. Concurrent in-flight limiting. Same auth-ordering reason // (user key + bySubscription resolution needs req.actor); installed // after rateLimitGate so a rate-rejection short-circuits before - // we acquire a concurrency slot. Slot is released on res finish/close. + // we acquire a concurrency slot. The slot is released once the response + // is done and any work the handler kept it for has settled. if (opts.concurrent) { mwChain.push( concurrencyGate(opts.concurrent) as unknown as RequestHandler, diff --git a/src/docs/src/rate-limits-and-quotas.md b/src/docs/src/rate-limits-and-quotas.md index 499e76c71..0f329c55d 100644 --- a/src/docs/src/rate-limits-and-quotas.md +++ b/src/docs/src/rate-limits-and-quotas.md @@ -62,6 +62,8 @@ Shared by chat, image generation, video, TTS, speech and OCR. Each interface and | Requests per 10 s | 200 | 30 | 20 | | Concurrent requests | 20 | 3 | 2 | +A chat completion counts as a concurrent request until the model finishes it, even if your app disconnects first, because the model keeps generating and the completion is still billed. That's at most 10 minutes after the disconnect. + | Input | Limit | | ---------------------------------------------- | ---------------- | | Text for `txt2speech()` | 3,000 characters |