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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Hosted runs: a short outage of the billing service never stops a run
Adarshf6ac58e0aaf1
diff --git a/docs/billing-hook.md b/docs/billing-hook.mdindex c441f0f5..d460f4a6 100644--- a/docs/billing-hook.md+++ b/docs/billing-hook.md@@ -29,7 +29,7 @@ twice: the service must treat a repeated call (the same `requestId`, or the same| `GET /v1/policy?account=<id>` | 1 s | before a run on this install's GPUs, and for the status (cached for the answer's `ttlS`) || `GET /v1/policy` | 1 s | a guest's status and price check: the policy for someone not signed in (cached the same way) || `POST /v1/quote` | 1 s | the price check before Run (`POST /api/generations?preview=1`), asked again 300 ms after each change |-| `POST /v1/reserve` | 2 s, one retry with the same `requestId` | just before the run's rows are made |+| `POST /v1/reserve` | 2 s a try; with no answer, tried again with the same `requestId` for up to 60 s (backoff from 0.5 s, doubling, up to 8 s) | just before the run's rows are made || `POST /v1/release` | 5 s, through the outbox | the rows couldn't be made after a reserve || `POST /v1/settle` | 5 s, through the outbox | each row that succeeded || `POST /v1/refund` | 5 s, through the outbox | each row that failed, was stopped, or was removed by an output check |@@ -109,7 +109,9 @@ request names always wins, so the account can still pick its own GPU. When the arun named no place, Fuobe asks (409, `code: "own-gpu-offline"`, header `x-fuobe-place-ask`) instead of moving the runto this install's GPUs, but only for a run this install's GPUs would take. Any other run goes to the account's own GPU,as before. While the policy is cached, a run on an account's own GPU never waits for the service; when a policy call-gets no answer, the last answer (or none) stands for 5 seconds (60 for a guest) before the service is asked again.+gets no answer, the last answer (or none) stands for 5 seconds (60 for a guest) before the service is asked again. The+last answer the service gave stands for up to 10 minutes while it doesn't answer; after that, runs on this install's+GPUs wait until it answers again.| Call | Request | Answer ||---|---|---|@@ -186,7 +188,9 @@ client can never set it. Once none of a hold's rows is still queued or running,a row that succeeded, `refund` for any other, each with `rows` (how many rows share the hold), so the service knows whenthe hold is closed. Reports are written to an outbox table first and sent from there, retried with backoff (10 s,doubling, up to 10 minutes) for 7 days. A restart loses nothing: the outbox finds every finished row with a hold and no-report from what is stored. A run whose rows couldn't be made after its reserve sends one `release`.+report from what is stored. A run whose rows couldn't be made after its reserve sends one `release`. Two app processes+on one database (during a deploy) never send the same report: a process takes a report before it sends it, and only one+process saves a finished run's results.## When the service is down@@ -194,6 +198,6 @@ report from what is stored. A run whose rows couldn't be made after its reserve|---|---|| No `FUOBE_BILLING_URL` | No call. Runs on this install's GPUs are closed, or free and allowed with `FUOBE_HOSTED_FREE=1`. || Set, and it answers | As above. |-| Set, and no answer in time | Runs on this install's GPUs are refused (503, "Try again in a moment."). Before Run, the price slot says "Ready in a moment" and Run is off; the price check asks again by itself, and Run comes back on with its answer. Runs on the account's own GPU or key go on. Reports wait in the outbox and are sent when it is back. Runs that already have a hold keep running. |+| Set, and no answer in time | A press of Run waits while the reserve is tried again for up to 60 seconds (a restart of the service), then the run is made with its place in line. Past that, the run is refused (503, "Try again in a moment.") and nothing is made. The last policy stands for 10 minutes (above). Before Run, the price slot says "Ready in a moment" and Run is off; the price check asks again by itself, and Run comes back on with its answer. Runs on the account's own GPU or key go on. Reports wait in the outbox and are sent when it is back. Runs that already have a hold keep running. |The service's address and its errors are written to the server's log only. A browser never sees them.diff --git a/src/server/billing.ts b/src/server/billing.tsindex 957014fb..bd978a93 100644--- a/src/server/billing.ts+++ b/src/server/billing.ts@@ -197,7 +197,7 @@ function target(): HookTarget | null {declare global {var __fuobeBillingBadUrl: boolean | undefined;- var __fuobeBillingPolicies: Map<string, { at: number; ttlMs: number; policy: Policy | null }> | undefined;+ var __fuobeBillingPolicies: Map<string, PolicyEntry> | undefined;var __fuobeBillingBalances: Map<string, { at: number; balance: Balance }> | undefined;}@@ -239,10 +239,25 @@ export const OPEN_POLICY: Policy = {*/export const POLICY_RETRY_MS = { account: 5_000, guest: 60_000 };+/**+ * How long the last policy the service gave stands while it doesn't answer (a restart, a short outage): runs go on+ * under it, and only after this long without an answer are runs on this install's GPUs held until it answers again.+ */+export const POLICY_KEEP_MS = 10 * 60_000;++/** A policy as kept: when it was read, how long it stands, and when the service last answered (`goodAt`). */+interface PolicyEntry {+ at: number;+ ttlMs: number;+ policy: Policy | null;+ goodAt?: number;+}+/*** The account's policy (cached for its `ttlS`), or a guest's (`accountId` null: GET /v1/policy with no account). No- * service: OPEN_POLICY. The service down: the last answer, else null (the caller treats runs on this install's GPUs as- * paused). That stands for POLICY_RETRY_MS, so a service that doesn't answer isn't waited for on every call.+ * service: OPEN_POLICY. The service down: the last answer it gave, for up to POLICY_KEEP_MS after it gave it, else null+ * (the caller holds runs on this install's GPUs until it answers). That stands for POLICY_RETRY_MS, so a service that+ * doesn't answer isn't waited for on every call.*/export async function policy(accountId: string | null): Promise<Policy | null> {if (!billingConfigured()) return OPEN_POLICY;@@ -250,19 +265,23 @@ export async function policy(accountId: string | null): Promise<Policy | null> {const key = accountId ?? "";const hit = cache.get(key);if (hit && Date.now() - hit.at < hit.ttlMs) return hit.policy;- const keep = (entry: { at: number; ttlMs: number; policy: Policy | null }) => {+ const keep = (entry: PolicyEntry) => {cache.set(key, entry);if (cache.size > 5000) cache.delete(cache.keys().next().value!);};try {const p = await call<Policy>("GET", accountId ? `/v1/policy?account=${encodeURIComponent(accountId)}` : "/v1/policy", undefined, BILLING_TIMEOUTS.policy);const ttlMs = Math.max(0, Math.min(3600, Number(p.ttlS) || 0)) * 1000;- keep({ at: Date.now(), ttlMs, policy: p });+ keep({ at: Date.now(), ttlMs, policy: p, goodAt: Date.now() });return p;} catch (e) {logDown("policy", e);- const last = hit?.policy ?? null;- keep({ at: Date.now(), ttlMs: accountId ? POLICY_RETRY_MS.account : POLICY_RETRY_MS.guest, policy: last });+ const now = Date.now();+ const goodAt = hit?.goodAt;+ const last = goodAt !== undefined && now - goodAt < POLICY_KEEP_MS ? (hit?.policy ?? null) : null;+ // Never past the time the last answer may stand.+ const retryMs = accountId ? POLICY_RETRY_MS.account : POLICY_RETRY_MS.guest;+ keep({ at: now, ttlMs: last && goodAt !== undefined ? Math.min(retryMs, goodAt + POLICY_KEEP_MS - now) : retryMs, policy: last, ...(goodAt !== undefined && { goodAt }) });return last;}}@@ -292,12 +311,21 @@ export async function quote(account: AccountFacts | null, run: RunFacts, queue:}/**- * Set the run's price aside before it is created. No service: null (no hold; the run is free). The service down (one- * retry with the same request id): a `paused` refusal. Never throws.+ * How a reserve the service doesn't answer is tried again (ms): after `firstMs`, then twice as long each time up to+ * `mostMs`, for up to `forMs` in all. A press of Run waits through a short outage or a restart of the service, and the+ * run starts with its place once it answers.+ */+export const RESERVE_RETRY = { forMs: 60_000, firstMs: 500, mostMs: 8_000 };++/**+ * Set the run's price aside before it is created. No service: null (no hold; the run is free). The service down: tried+ * again with the same request id (RESERVE_RETRY: the service makes one hold for it however often it hears it), then a+ * `paused` refusal in plain words. Never throws.*/export async function reserve(input: { requestId: string; account: AccountFacts; run: RunFacts; queue: QueueFacts | null; shown: { amount: number; priceVersion: string } }): Promise<ReserveAnswer | null> {if (!billingConfigured()) return null;- for (let attempt = 0; attempt < 2; attempt++) {+ const start = Date.now();+ for (let attempt = 0; ; attempt++) {try {const a = await call<ReserveAnswer>("POST", "/v1/reserve", input, BILLING_TIMEOUTS.reserve);if (a.ok && (typeof a.holdId !== "string" || !a.holdId)) throw new HookDown(HOOK, "a reserve answer without a hold id");@@ -305,6 +333,9 @@ export async function reserve(input: { requestId: string; account: AccountFacts;} catch (e) {logDown(`reserve (try ${attempt + 1})`, e);}+ const wait = Math.min(RESERVE_RETRY.mostMs, RESERVE_RETRY.firstMs * 2 ** Math.min(attempt, 16));+ if (Date.now() - start + wait > RESERVE_RETRY.forMs) break;+ await new Promise((r) => setTimeout(r, wait));}return { ok: false, code: "paused", text: BILLING_WAIT.run };}diff --git a/tests/recovery-server.test.ts b/tests/recovery-server.test.tsindex b23535be..49cf5b49 100644--- a/tests/recovery-server.test.ts+++ b/tests/recovery-server.test.ts@@ -857,19 +857,92 @@ describe("the billing service down or restarting", () => {await expectOnce(id, watch, { prompts: 1, place: 1 });});- it("Run pressed while the service is down is refused at once today, and nothing is made: the reserve isn't tried again while the service comes back", async () => {- standInWorker();+ it("Run pressed while the service restarts waits for it: the run is made once, with one hold, and finishes", async () => {+ const w = standInWorker();// The account's policy is known from its price check.expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);const rows = made();const holds = svc.holds.size;+ const reserves = svc.callsOf("/v1/reserve").length;await svc.downFor(10_000);+ const t = Date.now();const r = await run(IMAGE);- expect(r.status, JSON.stringify(r.body)).toBe(503);- expect(r.body.code).toBe("paused");- expect(made()).toBe(rows);- await svc.start();- expect(svc.holds.size).toBe(holds);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ expect(Date.now() - t, "it waited for the service").toBeGreaterThanOrEqual(9_000);+ expect(made() - rows).toBe(1);+ expect(svc.holds.size - holds).toBe(1);+ // Every try was the same press: one request id.+ const ids = new Set(svc.callsOf("/v1/reserve").slice(reserves).map((c) => (c.body as { requestId?: string }).requestId));+ expect(ids.size).toBe(1);+ const id = r.body.items![0].id;+ const watch = watchOf(id);+ const d = driver(w);+ lookAtEveryStep(d, watch);+ await workAll(d);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("a service that stays down past the wait: Run says to try again in a moment, in plain words, and nothing is made", async () => {+ standInWorker();+ expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);+ const rows = made();+ const was = { ...billing.RESERVE_RETRY };+ Object.assign(billing.RESERVE_RETRY, { forMs: 1500, firstMs: 200 });+ try {+ await svc.stop();+ const r = await run(IMAGE);+ expect(r.status, JSON.stringify(r.body)).toBe(503);+ expect(r.body.error).toBe(billing.BILLING_WAIT.run);+ expect(r.body.error).not.toMatch(/paus|error|service|GPU|worker/i);+ expect(made()).toBe(rows);+ } finally {+ Object.assign(billing.RESERVE_RETRY, was);+ await svc.start();+ }+ });++ it("down for 30 s while one account presses Run and another's run settles: both finish, each settles once, and no error shows", async () => {+ const w = standInWorker();+ expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);+ const theirs = await pressRun(IMAGE, b1);+ await svc.downFor(30_000);+ // Account A presses Run during the outage; meanwhile the worker renders B's run, which finishes and can't settle yet.+ const press = run(IMAGE);+ const d = driver(w);+ d.onStep(() => tick());+ await d.beat();+ expect(await d.runOne()).toBe(true);+ await until(() => done(getGeneration(theirs.id)));+ expect(getGeneration(theirs.id)?.status).toBe("succeeded");+ await outbox.sweepBilling();+ expect(svc.reportsFor(theirs.id)).toEqual([]);+ const r = await press;+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ const id = r.body.items![0].id;+ const watch = watchOf(id);+ lookAtEveryStep(d, watch);+ await workAll(d);+ // The outbox's next try reaches the service again.+ await outbox.drainOutbox(Date.now() + 10 * MIN);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ expect(await reportsOf(theirs.id)).toEqual([{ holdId: holdOf(theirs.id), kind: "settle", status: "succeeded" }]);+ expect(svc.late).toEqual([]);+ });++ it("the last policy it gave stands for 10 minutes while it doesn't answer, then runs wait for it", async () => {+ clock();+ expect(await billing.policy(A)).toBeTruthy();+ await svc.stop();+ try {+ vi.setSystemTime(Date.now() + 9 * MIN);+ expect(await billing.policy(A), "9 minutes on").toBeTruthy();+ vi.setSystemTime(Date.now() + 2 * MIN);+ expect(await billing.policy(A), "11 minutes on").toBeNull();+ } finally {+ await svc.start();+ }+ vi.setSystemTime(Date.now() + MIN);+ expect(await billing.policy(A), "answered again").toBeTruthy();});});