Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Hosted runs: a resend of a press never runs against a hold that went back

Adarsh6e0cd6a29311
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index ec95eb1e..be5fd569 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -31,7 +31,7 @@ import { runOnPool } from "@/server/hosted";
import { decidePlace, moderateRun, poolQuote, readWishes, reservePool, stepsProblem, type PlaceDecision, type Refusal } from "@/server/hosted-run";
import { withRunStamp, type RunStamp } from "@/server/run-stamp";
import { hostedRunsOn } from "@/server/hosted-switch";
-import { notePress, pressSeen, readPressId } from "@/server/run-requests";
+import { notePress, notePressRefused, pressSeen, readPressId, type PressRefusal, type PressSeen } from "@/server/run-requests";
/**
* List generations, newest first. Filters: kind / kinds, features (`x*` = prefix), models, statuses,
@@ -55,6 +55,23 @@ const BODY_TOO_BIG = "That request is over 4 MB. Upload pictures and clips first
const refuse = (status: number, error: string, extra: Record<string, unknown> = {}, headers: Record<string, string> = {}) =>
Response.json({ error, ...extra }, { status, headers: { "Cache-Control": "no-store", ...headers } });
+/** The answer to an account's run that can't go where it was planned: Connect your GPU, Add your key (the client opens either). */
+const accountRunAnswer = (r: AccountRunRefusal): PressRefusal => ({
+ status: 403,
+ body: { error: r.error, code: r.code, ...(r.provider && { provider: r.provider }) },
+ headers: r.code === "connect-gpu" ? { [CONNECT_GPU_HEADER]: "1" } : r.code === "add-key" && r.provider ? { [ADD_KEY_HEADER]: r.provider } : {},
+});
+
+/** The answer to a run the limits refuse as it is made (admitRun), or one with a step this install's GPUs don't take. */
+const limitAnswer = (r: AdmitRefused["refusal"]): PressRefusal => ({
+ status: r.status,
+ body: { error: r.error, code: r.code },
+ headers: r.code === "not-offered" ? { [BILLING_HEADER]: "not-offered" } : { "Retry-After": String(r.retryAfterS ?? 30) },
+});
+
+/** The answer to a run whose rows couldn't be made (as the route's own catch says it, for an account's run). */
+const thrownAnswer = (e: Error): PressRefusal => (e instanceof AccountRunError ? accountRunAnswer(e.refusal) : { status: 422, body: { error: e.message }, headers: {} });
+
/** Start a generation; `?preview=1` only says what it would run as (model, operation, jobs, outputs, cost). */
export async function POST(request: Request) {
const viewer = requestViewer(request);
@@ -108,8 +125,8 @@ export async function POST(request: Request) {
/** An account's run that can't go where it was planned: Connect your GPU, Add your key (the client opens either). */
const refused = (r: AccountRunRefusal) => {
if (account) unhit(`run:${account.id}`);
- const headers: Record<string, string> = r.code === "connect-gpu" ? { [CONNECT_GPU_HEADER]: "1" } : r.code === "add-key" && r.provider ? { [ADD_KEY_HEADER]: r.provider } : {};
- return refuse(403, r.error, { code: r.code, ...(r.provider && { provider: r.provider }) }, headers);
+ const a = accountRunAnswer(r);
+ return refuse(a.status, a.body.error, a.body, a.headers);
};
// Beside the request (never in it): the place the client prefers, and the price it showed (hosted runs, billing hook).
const { wish, shown } = readWishes(body);
@@ -123,10 +140,12 @@ export async function POST(request: Request) {
const pressId = account && !preview && hostedRunsOn() ? readPressId(body) : null;
const paused = () => refuse(503, BILLING_WAIT.run, { code: "paused" }, { [BILLING_HEADER]: "paused" });
const madeAlready = (ids: string[]) => Response.json({ items: ids.map((id) => getGeneration(id)).filter((g) => !!g) }, { status: 201 });
+ // The answer a press got before, for a resend of it: the same refusal, or the run it made.
+ const answerAgain = (seen: Exclude<PressSeen, null>) =>
+ seen === "gave-up" ? paused() : "refused" in seen ? refuse(seen.refused.status, seen.refused.body.error, seen.refused.body, seen.refused.headers) : madeAlready(seen.ids);
if (account && pressId) {
const seen = pressSeen(account.id, pressId);
- if (seen === "gave-up") return paused();
- if (seen) return madeAlready(seen.ids);
+ if (seen) return answerAgain(seen);
}
const notes: string[] = [];
if (account && !preview) {
@@ -280,8 +299,11 @@ export async function POST(request: Request) {
{
accountId: account.id,
pool: pool && !pool.light ? { policy: pool.policy, addr } : null,
- // A resend of this press that got here first made the run (or gave up): nothing is made twice.
+ // A resend of this press that got here first made the run (or gave up, or was refused): nothing is made twice.
...(pressId && { prior: () => pressSeen(account.id, pressId) }),
+ // Refused after its hold was made: the hold goes back, so a resend gets this same answer, never a run
+ // against that hold. Noted in the same transaction, before any resend can look.
+ ...(pressId && stamp?.hold && { refused: (why: AdmitRefused["refusal"] | Error) => notePressRefused(account.id, pressId, stamp?.hold ?? null, why instanceof Error ? thrownAnswer(why) : limitAnswer(why)) }),
},
() => {
const run = captureRun(make);
@@ -297,15 +319,16 @@ export async function POST(request: Request) {
if (!admitted.ok && "prior" in admitted) {
unhit(`run:${account.id}`);
const prior = admitted.prior;
- // The service gives one press one hold; a different one (a service that made a second) goes back.
- if (stamp?.hold && (prior === "gave-up" || stamp.hold !== prior.hold)) queueRelease(stamp.hold);
- return prior === "gave-up" ? paused() : madeAlready(prior.ids);
+ // The service gives one press one hold; a different one (a service that made a second) goes back, and so does
+ // the hold of a press that made no run.
+ if (stamp?.hold && (prior === "gave-up" || "refused" in prior || stamp.hold !== prior.hold)) queueRelease(stamp.hold);
+ return answerAgain(prior);
}
if (!admitted.ok) {
unhit(`run:${account.id}`);
if (stamp?.hold) queueRelease(stamp.hold);
- const r = admitted.refusal;
- return refuse(r.status, r.error, { code: r.code }, r.code === "not-offered" ? { [BILLING_HEADER]: "not-offered" } : { "Retry-After": String(r.retryAfterS ?? 30) });
+ const a = limitAnswer(admitted.refusal);
+ return refuse(a.status, a.body.error, a.body, a.headers);
}
items = admitted.value.value;
} else items = make();
diff --git a/src/server/db.ts b/src/server/db.ts
index ebbcd988..8760d417 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -890,6 +890,7 @@ export const HOOK_TABLES = `CREATE TABLE IF NOT EXISTS billing_outbox (
ids_json TEXT,
hold_id TEXT,
gave_up INTEGER NOT NULL DEFAULT 0,
+ refusal_json TEXT,
at INTEGER NOT NULL,
PRIMARY KEY (account, request_id)
);
@@ -1001,6 +1002,8 @@ const HOOK_COLUMNS: [string, string, string][] = [
// A report one app process is sending now, until when: no other process sends it meanwhile (billing-outbox.ts).
["billing_outbox", "sending_until", "INTEGER"],
["billing_outbox", "sending_by", "TEXT"],
+ // The answer a press of Run got when it was refused after its hold was made (run-requests.ts).
+ ["run_requests", "refusal_json", "TEXT"],
];
/**
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 126a5af1..e01b7c41 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -526,6 +526,7 @@ export const ASSET_FREE: Record<string, string> = {
"generations.external_meta_json": "the provider's job handles",
"billing_outbox.payload_json": "reports for the billing service: hold and run ids, counts and words, never a file",
"run_requests.ids_json": "the ids of the runs one press of Run made, never a file",
+ "run_requests.refusal_json": "the status, words and code a refused press of Run got, never a file",
"reports_inbox.target_json": "what a report is about: a run, asset or share id, never a file",
"admin_tokens.scopes_json": "an admin token's scope names",
"admin_audit.detail_json": "small facts about an admin action: counts, ids and names, never a file's URL",
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
index 11aaa012..0311ff76 100644
--- a/src/server/hosted-run.ts
+++ b/src/server/hosted-run.ts
@@ -36,6 +36,7 @@ import { hostedRunsOn } from "./hosted-switch";
import { checkRun, moderationConfigured } from "./moderation";
import { queueRequestRelease } from "./billing-outbox";
import { notePressGaveUp, reserveRequestId } from "./run-requests";
+import { db } from "./db";
import type { RunStamp } from "./run-stamp";
import { readRef } from "./storage";
import { readSnapshot } from "./gpu/snapshots";
@@ -446,8 +447,11 @@ export async function reservePool(
if (!a.ok) {
if (a.unsure) {
// A try may have made a hold the app never heard of: it goes back, and a resend of this press is refused at once.
- if (pressId) notePressGaveUp(account.id, pressId);
- queueRequestRelease(requestId);
+ // A resend of the press that got there first (it made the run, or was refused and gave its hold back) owns the
+ // press's one hold, so nothing is released by its request id. One statement decides, after any run it made.
+ db().transaction(() => {
+ if (!pressId || notePressGaveUp(account.id, pressId)) queueRequestRelease(requestId);
+ })();
}
return { ok: false, refusal: billingRefusal(a.code, a.text, { ...(a.quote && { quote: a.quote }), ...(a.action && { action: a.action }), ...(a.offer && { offer: a.offer }) }) };
}
diff --git a/src/server/pool-limits.ts b/src/server/pool-limits.ts
index 6860d0e7..5c6d1ed7 100644
--- a/src/server/pool-limits.ts
+++ b/src/server/pool-limits.ts
@@ -164,22 +164,49 @@ export class AdmitRefused extends Error {
* policy's limits on runs on this install's GPUs. All in one BEGIN IMMEDIATE transaction; a run on this install's GPUs is
* noted for the hourly counts in the same transaction. `make` may throw AdmitRefused (or anything else) to keep nothing.
* `prior`, looked at first in the same transaction: what this same request made already (a resend of one press of Run,
- * run-requests.ts); when it says anything, nothing is counted or made, and it is the answer.
+ * run-requests.ts); when it says anything, nothing is counted or made, and it is the answer. `refused`, called in the
+ * same transaction when the run is not made (a limit, AdmitRefused, or another error from `make`, which is thrown again
+ * once the transaction ends): what it writes is kept, while nothing `make` wrote is.
*/
export function admitRun<T, P = never>(
- o: { accountId: string; pool: { policy: Pick<Policy, "limits">; addr: string | null } | null; now?: number; prior?: () => P | null },
+ o: {
+ accountId: string;
+ pool: { policy: Pick<Policy, "limits">; addr: string | null } | null;
+ now?: number;
+ prior?: () => P | null;
+ refused?: (why: AdmitRefused["refusal"] | Error) => void;
+ },
make: () => T,
): { ok: true; value: T } | { ok: false; refusal: AdmitRefused["refusal"] } | { ok: false; prior: P } {
+ type Answer = { ok: true; value: T } | { ok: false; refusal: AdmitRefused["refusal"] } | { ok: false; prior: P };
const now = o.now ?? Date.now();
const d = db();
+ const refused = o.refused;
+ let failed: { e: unknown } | null = null;
+ let answer: Answer | null;
try {
- return d
- .transaction((): { ok: true; value: T } | { ok: false; refusal: AdmitRefused["refusal"] } | { ok: false; prior: P } => {
+ answer = d
+ .transaction((): Answer | null => {
const prior = o.prior?.() ?? null;
if (prior !== null) return { ok: false, prior };
const refusal = accountLimitRefusal(o.accountId) ?? (o.pool ? poolLimitRefusal(o.accountId, o.pool.policy, o.pool.addr, now) : null);
- if (refusal) return { ok: false, refusal };
- const value = make();
+ if (refusal) {
+ refused?.(refusal);
+ return { ok: false, refusal };
+ }
+ let value: T;
+ if (!refused) value = make();
+ else {
+ try {
+ // In a savepoint: a make that refuses or fails keeps nothing it wrote, and the refusal is still noted.
+ value = d.transaction(make)();
+ } catch (e) {
+ refused(e instanceof AdmitRefused ? e.refusal : e instanceof Error ? e : new Error(String(e)));
+ if (e instanceof AdmitRefused) return { ok: false, refusal: e.refusal };
+ failed = { e };
+ return null;
+ }
+ }
if (o.pool) {
d.prepare("INSERT INTO pool_admissions (account, addr, at) VALUES (?, ?, ?)").run(o.accountId, o.pool.addr, now);
prunePoolAdmissions(now, true);
@@ -191,4 +218,6 @@ export function admitRun<T, P = never>(
if (e instanceof AdmitRefused) return { ok: false, refusal: e.refusal };
throw e;
}
+ if (failed) throw (failed as { e: unknown }).e;
+ return answer!;
}
diff --git a/src/server/run-requests.ts b/src/server/run-requests.ts
index de711bf1..598d21ad 100644
--- a/src/server/run-requests.ts
+++ b/src/server/run-requests.ts
@@ -28,19 +28,34 @@ export const PRESS_KEEP_MS = 24 * 3_600_000;
export const reserveRequestId = (accountId: string, pressId: string): string =>
`r_${crypto.createHash("sha256").update(`${accountId}\n${pressId}`).digest("hex").slice(0, 32)}`;
+/** A refusal a press got after its price was set aside, as the route answered it: a resend of the press gets it again. */
+export interface PressRefusal {
+ status: number;
+ body: { error: string; code?: string; provider?: string };
+ headers: Record<string, string>;
+}
+
/**
* What a press made already: its run's rows (the first ones, as the route answered them) and the hold they carry;
- * "gave-up" when its reserve was given up (the billing service didn't answer in time and the press was refused); null
- * when it is new.
+ * "gave-up" when its reserve was given up (the billing service didn't answer in time and the press was refused);
+ * `refused` when it was refused after its hold was made (a limit, a step this install's GPUs don't take, rows that
+ * couldn't be made), so its hold went back; null when it is new.
*/
-export type PressSeen = { ids: string[]; hold: string | null } | "gave-up" | null;
+export type PressSeen = { ids: string[]; hold: string | null } | "gave-up" | { refused: PressRefusal } | null;
export function pressSeen(accountId: string, pressId: string, now = Date.now()): PressSeen {
const r = db()
- .prepare("SELECT ids_json, hold_id, gave_up FROM run_requests WHERE account = ? AND request_id = ? AND at > ?")
- .get(accountId, pressId, now - PRESS_KEEP_MS) as { ids_json: string | null; hold_id: string | null; gave_up: number } | undefined;
+ .prepare("SELECT ids_json, hold_id, gave_up, refusal_json FROM run_requests WHERE account = ? AND request_id = ? AND at > ?")
+ .get(accountId, pressId, now - PRESS_KEEP_MS) as { ids_json: string | null; hold_id: string | null; gave_up: number; refusal_json: string | null } | undefined;
if (!r) return null;
if (r.gave_up) return "gave-up";
+ if (r.refusal_json) {
+ try {
+ return { refused: JSON.parse(r.refusal_json) as PressRefusal };
+ } catch {
+ return "gave-up";
+ }
+ }
let ids: string[] = [];
try {
ids = JSON.parse(r.ids_json ?? "[]") as string[];
@@ -52,13 +67,27 @@ export function pressSeen(accountId: string, pressId: string, now = Date.now()):
export function notePress(accountId: string, pressId: string, ids: string[], hold: string | null, now = Date.now()): void {
const d = db();
d.prepare("DELETE FROM run_requests WHERE at < ?").run(now - PRESS_KEEP_MS);
- d.prepare("INSERT OR REPLACE INTO run_requests (account, request_id, ids_json, hold_id, gave_up, at) VALUES (?, ?, ?, ?, 0, ?)").run(accountId, pressId, JSON.stringify(ids), hold, now);
+ d.prepare("INSERT OR REPLACE INTO run_requests (account, request_id, ids_json, hold_id, gave_up, refusal_json, at) VALUES (?, ?, ?, ?, 0, NULL, ?)").run(accountId, pressId, JSON.stringify(ids), hold, now);
+}
+
+/**
+ * Note a press refused after its hold was made, with the answer it got (inside the transaction that refused it): its
+ * hold goes back, and a resend of the press gets the same answer instead of a run against that hold.
+ */
+export function notePressRefused(accountId: string, pressId: string, hold: string | null, refusal: PressRefusal, now = Date.now()): void {
+ db()
+ .prepare("INSERT OR REPLACE INTO run_requests (account, request_id, ids_json, hold_id, gave_up, refusal_json, at) VALUES (?, ?, NULL, ?, 0, ?, ?)")
+ .run(accountId, pressId, hold, JSON.stringify(refusal), now);
}
/**
* Note a press whose reserve was given up: a resend of it is refused at once (its hold, if the service made one, is
- * being released by its request id), and a new press of Run starts afresh.
+ * being released by its request id), and a new press of Run starts afresh. False when a resend of the press got there
+ * first (it made its run, was refused or gave up too): then the press's hold, if any, is that resend's to keep or give
+ * back, and nothing may be released by its request id.
*/
-export function notePressGaveUp(accountId: string, pressId: string, now = Date.now()): void {
- db().prepare("INSERT OR IGNORE INTO run_requests (account, request_id, ids_json, hold_id, gave_up, at) VALUES (?, ?, NULL, NULL, 1, ?)").run(accountId, pressId, now);
+export function notePressGaveUp(accountId: string, pressId: string, now = Date.now()): boolean {
+ const d = db();
+ d.prepare("DELETE FROM run_requests WHERE account = ? AND request_id = ? AND at <= ?").run(accountId, pressId, now - PRESS_KEEP_MS);
+ return d.prepare("INSERT OR IGNORE INTO run_requests (account, request_id, ids_json, hold_id, gave_up, at) VALUES (?, ?, NULL, NULL, 1, ?)").run(accountId, pressId, now).changes > 0;
}
diff --git a/tests/pool-limits.test.ts b/tests/pool-limits.test.ts
index ddc9f4c9..35979e83 100644
--- a/tests/pool-limits.test.ts
+++ b/tests/pool-limits.test.ts
@@ -215,6 +215,42 @@ describe("runs at once on this install's GPUs", () => {
expect(poolRuns(a.id)).toBe(1);
});
+ it("a run not made is noted in the same transaction: a limit, a refusal from inside, or an error, which is thrown again", () => {
+ const a = account();
+ const p = { limits: { activeRuns: 1, waiting: 0, runsPerHour: 0, outputsPerRun: 0, maxMegapixels: 0, maxSeconds: 0, keepDays: 0, spaceBytes: 0 } };
+ const insert = () =>
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', ?, '[]', ?, ?)")
+ .run(`tx-${++n}`, JSON.stringify({ account: a.id, place: "pool" }), Date.now(), Date.now());
+ const noted: string[] = [];
+ const note = (why: { error: string } | Error) => {
+ noted.push(why instanceof Error ? `error: ${why.message}` : why.error);
+ db().prepare("INSERT INTO settings (key, value) VALUES (?, ?)").run(`test.noted.${a.id}.${noted.length}`, "1");
+ };
+ const kept = () => (db().prepare("SELECT COUNT(*) AS n FROM settings WHERE key LIKE ?").get(`test.noted.${a.id}.%`) as { n: number }).n;
+ // A refusal from inside: nothing make wrote is kept, the note is.
+ const r = limits.admitRun({ accountId: a.id, pool: { policy: p, addr: null }, refused: note }, () => {
+ insert();
+ throw new limits.AdmitRefused({ status: 403, error: "no", code: "not-offered" });
+ });
+ expect(r.ok).toBe(false);
+ expect(poolRuns(a.id)).toBe(0);
+ // An error: thrown again once the note is kept.
+ expect(() =>
+ limits.admitRun({ accountId: a.id, pool: { policy: p, addr: null }, refused: note }, () => {
+ insert();
+ throw new Error("rows failed");
+ }),
+ ).toThrow("rows failed");
+ expect(poolRuns(a.id)).toBe(0);
+ // A limit.
+ expect(limits.admitRun({ accountId: a.id, pool: { policy: p, addr: null }, refused: note }, insert).ok).toBe(true);
+ expect(limits.admitRun({ accountId: a.id, pool: { policy: p, addr: null }, refused: note }, insert).ok).toBe(false);
+ expect(poolRuns(a.id)).toBe(1);
+ expect(noted).toEqual(["no", "error: rows failed", limits.POOL_LIMIT_WORDS.active(1)]);
+ expect(kept()).toBe(3);
+ });
+
it("runs on the account's own GPU never count against the policy, and keep the studio's own limit of 4", async () => {
withBilling({ limits: { activeRuns: 1, waiting: 0, runsPerHour: 0 } });
const a = account({ gpu: "online" });
diff --git a/tests/recovery-server.test.ts b/tests/recovery-server.test.ts
index 6136292c..d15d0b70 100644
--- a/tests/recovery-server.test.ts
+++ b/tests/recovery-server.test.ts
@@ -821,6 +821,86 @@ describe("a press of Run sent twice (a network drop at submit)", () => {
expect(svc.holds.size - holds, "holds made").toBe(1);
});
+ it("a send that stops waiting for the billing service after a resend of the same press made its run leaves that run's hold alone", async () => {
+ const w = standInWorker();
+ expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);
+ const rows = made();
+ const was = { ...billing.RESERVE_RETRY };
+ // One try for the first send, then its whole wait is over.
+ Object.assign(billing.RESERVE_RETRY, { forMs: 3000, firstMs: 200 });
+ const press = { ...IMAGE, requestId: `press-${crypto.randomUUID()}` };
+ try {
+ // The service answers the first send's reserve only after the app stopped waiting for it.
+ Object.assign(svc, { slowMs: 2500, slowPath: "/v1/reserve" });
+ const reserves = svc.callsOf("/v1/reserve").length;
+ const first = run(press);
+ for (let i = 0; i < 200 && svc.callsOf("/v1/reserve").length === reserves; i++) await sleep(10);
+ expect(svc.callsOf("/v1/reserve").length, "the first send's reserve reached the service").toBe(reserves + 1);
+ // The page sends the press again, and the service answers that one at once: it makes the run.
+ Object.assign(svc, { slowMs: 0, slowPath: null });
+ const again = await run(press);
+ expect(again.status, JSON.stringify(again.body)).toBe(201);
+ const id = again.body.items![0].id;
+ // Only then does the first send stop waiting.
+ expect((await first).status).toBe(503);
+ expect(made() - rows, "runs made").toBe(1);
+ const hold = svc.holds.get(holdOf(id)!)!;
+ const requestId = hold.requestId;
+ expect(db().prepare("SELECT COUNT(*) AS n FROM billing_outbox WHERE key = ?").get(`release:request:${requestId}`)).toEqual({ n: 0 });
+ await outbox.drainOutbox(Date.now() + outbox.REQUEST_RELEASE_AFTER_MS + 1000);
+ expect(hold.released, "the run's hold stays open").toBe(false);
+ expect(svc.callsOf("/v1/release").some((c) => (c.body as { requestId?: string }).requestId === requestId)).toBe(false);
+ // The run finishes and settles against its own hold.
+ const watch = watchOf(id);
+ const d = driver(w);
+ lookAtEveryStep(d, watch);
+ await workAll(d);
+ await expectOnce(id, watch, { place: 1 });
+ expect(hold.released).toBe(false);
+ } finally {
+ Object.assign(billing.RESERVE_RETRY, was);
+ }
+ });
+
+ it("a press refused by the limits after its hold was made gives the hold back, and a resend of it gets the same answer, never a run against that hold", async () => {
+ standInWorker();
+ (svc.policy as { limits: { activeRuns: number } }).limits.activeRuns = 1;
+ billing.resetBillingCache();
+ expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);
+ const rows = made();
+ const press = { ...IMAGE, requestId: `press-${crypto.randomUUID()}` };
+ // The first press's reserve is slow; meanwhile another press makes a run, so the first is over the limit once
+ // its hold is made.
+ Object.assign(svc, { slowMs: 800, slowPath: "/v1/reserve" });
+ const reserves = svc.callsOf("/v1/reserve").length;
+ const first = run(press);
+ for (let i = 0; i < 200 && svc.callsOf("/v1/reserve").length === reserves; i++) await sleep(10);
+ Object.assign(svc, { slowMs: 0, slowPath: null });
+ const other = await run({ ...IMAGE, requestId: `press-${crypto.randomUUID()}` });
+ expect(other.status, JSON.stringify(other.body)).toBe(201);
+ const a = await first;
+ expect(a.status, JSON.stringify(a.body)).toBe(429);
+ expect(made() - rows, "runs made").toBe(1);
+ const reserve = svc.callsOf("/v1/reserve").find((c, i) => i >= reserves && (c.body as { requestId?: string }).requestId !== undefined);
+ const requestId = (reserve!.body as { requestId: string }).requestId;
+ const hold = [...svc.holds.values()].find((h) => h.requestId === requestId)!;
+ for (let i = 0; i < 100 && !hold.released; i++) {
+ await outbox.sweepBilling();
+ await sleep(10);
+ }
+ expect(hold.released, "the refused press's hold goes back").toBe(true);
+ // The other run ends, so the limit would let the press through now; its answer was lost, and the page sends it again.
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE id = ?").run(other.body.items![0].id);
+ const before = svc.callsOf("/v1/reserve").length;
+ const again = await run(press);
+ expect(again.status).toBe(a.status);
+ expect(again.body).toEqual(a.body);
+ expect(svc.callsOf("/v1/reserve").length, "no second reserve").toBe(before);
+ expect(made() - rows, "runs made").toBe(1);
+ // A new press works.
+ expect((await run({ ...IMAGE, requestId: `press-${crypto.randomUUID()}` })).status).toBe(201);
+ });
+
it("with hosted runs off, a press id changes nothing: each request makes its run, as before", async () => {
delete process.env.FUOBE_HOSTED_RUNS;
delete process.env.FUOBE_BILLING_URL;