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.

Runs on this install's GPUs always deliver: taken whatever the line, no wait limit when the policy says so

Adarshcf1dea78fc10
diff --git a/docs/SELF-HOSTING.md b/docs/SELF-HOSTING.md
index d4d3e2dc..32d70936 100644
--- a/docs/SELF-HOSTING.md
+++ b/docs/SELF-HOSTING.md
@@ -137,7 +137,7 @@ A file that looks like the note but was changed (it has a password or a sign-in
| `FUOBE_HOSTED_RUNS=1` | With public sign-up: accounts with no GPU of their own may run on this install's GPUs: its workers, or its own ComfyUI when that is on this machine ([Hosted runs](public-signup.md#hosted-runs)). Off by default. A billing service or `FUOBE_HOSTED_FREE=1` must answer for these runs |
| `FUOBE_HOSTED_FREE=1` | With no billing service: hosted runs are free for every account, within the install's own limits. Without it (and without a billing service) hosted runs stay closed |
| `FUOBE_PLACE_NAME` | The name visitors read for this install's GPUs while hosted runs are on ("Runs on Ana's render box", "Made on: Ana's render box"), at most 40 characters. Also Settings → Workers → Name for your GPUs, which wins over it; a billing service's own name for them wins over both. Unset: "Our GPUs". Nothing reads it while hosted runs are off. The table that keeps where each account picked its runs to go (`account_run_on`) is made on every install and stays empty, and unread, while hosted runs are off |
-| `FUOBE_POOL_WAIT_MIN` | How long a hosted run may wait in line before a GPU first takes it, in minutes (default `30`) |
+| `FUOBE_POOL_WAIT_MIN` | How long a hosted run may wait in line before a GPU first takes it, in minutes (default `30`). A billing service's policy (`limits.giveUpS`, 0: no limit) or reserve answer wins over it. With hosted runs on and no billing service, a run that waits this long ends with one plain sentence, "Sorry, this one couldn't be made." |
| `FUOBE_POOL_MEDIA_INPUTS` | The kinds of input file a run on the workers may send them, comma-separated: `image` (default) or `image,video,audio`. Clips and sound go only to workers that make each clip and sound again before their ComfyUI reads it (worker protocol 2 with ffmpeg set, [Clips and sound](gpu-workers.md#clips-and-sound)). A hosted run takes a kind only when this and the billing service's policy (`uploads`) both allow it, so set it together with `FUOBE_HOSTED_RUNS` and `FUOBE_BILLING_URL` when the policy opens clips and sound |
| `FUOBE_CATALOG_VERSION` | The catalog version accounts' job tickets are made for ([Job tickets and the PC's ceiling](gpu-workers.md#job-tickets-and-the-pcs-ceiling)), as 64 hex characters. Unset: the studio computes it from its own composer and catalog files, which is what a server running from its own checkout wants. Set it only when the server runs without those files |
| `FUOBE_WORKER_TOKEN_DAYS` | How many days a pool worker's token lasts; the worker gets its next one in a beat answer ([gpu-workers.md](gpu-workers.md#the-protocol)). Unset or `0`: tokens never expire |
diff --git a/docs/billing-hook.md b/docs/billing-hook.md
index 9643407f..39f7e635 100644
--- a/docs/billing-hook.md
+++ b/docs/billing-hook.md
@@ -61,7 +61,12 @@ type Policy = {
hosted: boolean; // may this account use this install's GPUs at all
pool: { allow?: string[]; deny?: string[]; apps?: { allow?: string[]; deny?: string[] } }; // models and apps there
uploads: { image: boolean; video: boolean; audio: boolean }; // which of its own files those runs may use
- limits: { activeRuns: number; waiting: number; runsPerHour: number; outputsPerRun: number; maxMegapixels: number; maxSeconds: number; keepDays: number; spaceBytes: number; addressRunsPerHour?: number };
+ limits: {
+ activeRuns: number; waiting: number; runsPerHour: number; outputsPerRun: number; maxMegapixels: number; maxSeconds: number;
+ keepDays: number; spaceBytes: number; addressRunsPerHour?: number;
+ giveUpS?: number; // longest wait before a GPU first takes a run (0: none)
+ offerAfterS?: number; // a wait after which an account's own GPU or key is offered (absent: 1200)
+ };
prefer?: "pool" | "own"; // the default place (absent: "own")
kinds?: { image?: boolean; video?: boolean; audio?: boolean; text?: boolean; model3d?: boolean }; // absent: all
cardText?: string; // preset cards' words for a run there (absent: none)
@@ -74,6 +79,19 @@ type Policy = {
(at most 40 characters). With a service set, the cards say only these words, and nothing when the policy has none.
With no service, runs there are free (`FUOBE_HOSTED_FREE=1`), and the cards say "Try free".
+`limits.giveUpS` is how long a run on this install's GPUs may wait before a GPU first takes it, in seconds. `0`: as long
+as it takes (the run never fails for a wait). Present, it wins over the reserve answer's `maxWaitMs`; absent, that
+answer says, and with none `FUOBE_POOL_WAIT_MIN`. `limits.offerAfterS` is the wait (in seconds, as the price check
+estimates it) after which the line before Run offers an account its own GPU, or a key that runs the item's cloud
+version at its price, for that one run. Absent: 1200. A wait with no end known (every GPU that could run it is away)
+counts as past it.
+
+While the service doesn't answer, a run that would go to this install's GPUs because the service's last answer put them
+first (`prefer: "pool"`) waits for the service; it is never moved to the account's own GPU for that.
+
+`queue.nextOpenAt` is when the first GPU that could run the run is due back (the start of its hours, or the end of a
+pause on its PC that has one), when every such GPU is away and one says; otherwise null.
+
`placeName` is the name visitors read for this install's GPUs ("Runs on Studio North GPUs", "Made on: Studio North
GPUs"), at most 40 characters. Absent: the install's own name for them (Settings → Workers → Name for your GPUs, else
`FUOBE_PLACE_NAME`), else "Our GPUs". Fuobe writes every sentence so that no verb has to agree with the name.
@@ -216,7 +234,7 @@ a run started without a price check (a result's Upscale, a retry, Run again) run
A reserve's `text` is shown on the result once it succeeded ("7 units"). A run that fails or is removed says "Not
charged" only when its reserve answer set an amount aside (`amount` above 0). `maxWaitMs` is how long the run may wait
-in line before a GPU first takes it; past it the row fails and is refunded. Once a GPU has taken it, the limit is over:
+in line before a GPU first takes it (unless the policy's `limits.giveUpS` says); past it the row fails and is refunded. Once a GPU has taken it, the limit is over:
a run that goes back in line (a GPU paused or restarted) keeps its place and waits there.
`timing` says how long the hold must stay open after a GPU first takes the run, so the run's reports always come
diff --git a/docs/public-signup.md b/docs/public-signup.md
index c02390ba..e56ce42a 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -699,9 +699,21 @@ With it on:
account's own GPU or key.
- A new account goes back to where it was after sign-up, not to "Connect your GPU". Connecting a GPU stays in
Settings → Your GPU and at `/connect`; the account menu says "Your GPU · Optional".
-- A run waiting for the studio's GPUs shows its place in line ("In line · 3rd · about 40 s"). A run may wait
- `FUOBE_POOL_WAIT_MIN` minutes (30 by default), or what the billing service says, before a GPU first takes it; past
- that it fails, not charged.
+- Before Run, the line under the toolbar says when the result would be ready ("Ready in about 2 min", "Ready in
+ seconds" for light work such as a join or a trim). A run waiting for the studio's GPUs shows its place in line and
+ the same wait on its tile ("In line · 3rd · ready in about 2 min"). Once a GPU takes it, its tile says "Working ·
+ getting ready" while its model loads (the GPU had another one loaded), then "Working" with its progress.
+- A run is taken whatever the line, and Run stays on: while every GPU that could run it is paused, outside its hours,
+ silent or built from the catalog before an update, the run waits in line and says "starts when a GPU is free" (or
+ "starts in about 3 h" when the first is due back at a known time). An account whose runs go to the studio's GPUs is
+ never moved to its own GPU for that, nor while the billing service is quiet; only what those GPUs can't run at all
+ goes there. After a long wait (the policy's `limits.offerAfterS`, 20 minutes by default, or a wait with no end
+ known) an account with its own GPU, or a key that runs the item's cloud version, is offered it for that one run
+ ("Run it now on your GPU", "Run it now with your fal.ai key · ≈ $0.04"), and its pick of where runs go stays.
+- How long a run may wait before a GPU first takes it: the billing service's `limits.giveUpS` when its policy says
+ (0: as long as it takes), else what its reserve answer says, else `FUOBE_POOL_WAIT_MIN` minutes (30 by default).
+ Past that it fails with one plain sentence, not charged. A later step of a run (a chain's next step) keeps the run's
+ place in line and has no wait limit.
- The account's usual limits apply: runs at once, runs per hour, outputs per run, and its space.
Two optional services can go with it:
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index bca150d7..72ff17c8 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -25,7 +25,7 @@ import { connectNeeds } from "@/server/connect-refusal";
import { BILLING_HEADER, BILLING_WAIT } from "@/server/billing";
import { queueRelease } from "@/server/billing-outbox";
import { runOnPool } from "@/server/hosted";
-import { decidePlace, moderateRun, poolQuote, readWishes, reservePool, stepsProblem, type PlaceDecision, type Refusal } from "@/server/hosted-run";
+import { decidePlace, moderateRun, policyWait, 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 { endTry, notePressRun, pressPrior, pressRun, pressTries, pressTry, readPressId } from "@/server/run-requests";
@@ -270,9 +270,9 @@ export async function POST(request: Request) {
if (!mod.ok) return refusedBy(mod.refusal);
if (onPool?.light) {
// Light work only (joins, trims): free, so nothing is set aside, and it counts against none of the policy's limits.
- stamp = { place: "pool", light: true, ...(mod.checkOutputs && { checkOutputs: true }) };
+ stamp = { place: "pool", light: true, ...(mod.checkOutputs && { checkOutputs: true }), ...policyWait(onPool.policy) };
} else if (onPool) {
- const held = await reservePool(account, req, onPool.planned, shown, mod.checkOutputs, onPool.steps, poolTry === null ? null : pressTry(account.id, pressId!, poolTry));
+ const held = await reservePool(account, req, onPool.planned, shown, mod.checkOutputs, onPool.steps, poolTry === null ? null : pressTry(account.id, pressId!, poolTry), onPool.policy);
if (!held.ok) return refusedBy(held.refusal);
stamp = held.stamp;
} else if (mod.checkOutputs) stamp = { checkOutputs: true };
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index 76e2434f..719f730e 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -891,6 +891,17 @@ export function Composer({ docked }: { docked: boolean }) {
};
// "Run on Our GPUs": this run, once, on this studio's GPUs; the account's pick stays as it was.
const onRunOnSite = () => submitRef.current(undefined, undefined, "pool");
+ // A long wait on this studio's GPUs (past the policy's offer time, or until a GPU is free): an account with its own GPU,
+ // or a key that runs this item's cloud version (at its price, never without one), may run this run there now, once.
+ // Its pick stays as it was, and the run is taken in line all the same when it doesn't.
+ const waitOffer =
+ viewerInfo?.kind === "account" && poolState && !poolState.refused && poolState.long
+ ? viewerInfo.gpu.connected
+ ? { label: "Run it now on your GPU", run: () => submitRef.current(undefined, undefined, "own") }
+ : keyTwin && keyPrice
+ ? { label: `Run it now with your ${CLOUD_KEY[keyTwin.provider].label} key · ${keyPrice}`, run: () => submitRef.current(undefined, withKeyAction(keyTwin.provider, keyTwin.modelId, keyTwin.op, keyPrice)) }
+ : undefined
+ : undefined;
// A choice before Run for an item this studio's GPUs can't run, for an account whose key runs its cloud version (and no
// GPU): run it once on the key, at its price, or connect a GPU. Nothing runs until one is pressed.
const [keyChoice, setKeyChoice] = useState(false);
@@ -1953,7 +1964,7 @@ export function Composer({ docked }: { docked: boolean }) {
</p>
)}
{/* Folded (docked, not focused), the composer stays one line: the wait shows again once it opens. */}
- {!blocker && !gpuSetup && poolState && (poolState.refused || !collapsed) && <PoolNote state={poolState} />}
+ {!blocker && !gpuSetup && poolState && (poolState.refused || !collapsed) && <PoolNote state={poolState} offer={waitOffer} />}
{!blocker && priceNote && !poolRefused && (
<p data-price-note className="px-2 text-[12px] font-medium text-foreground">
{priceNote}
diff --git a/src/components/studio/pool-note.tsx b/src/components/studio/pool-note.tsx
index 26e23060..51a4afa4 100644
--- a/src/components/studio/pool-note.tsx
+++ b/src/components/studio/pool-note.tsx
@@ -1,23 +1,37 @@
"use client";
import { safeLink, useInterest, type poolRunState } from "@/lib/hosted";
+import { capitalFirst } from "@/lib/pool-line";
import { cn } from "@/lib/utils";
type PoolState = NonNullable<ReturnType<typeof poolRunState>>;
/**
- * The line under a composer's toolbar for a run on this studio's GPUs: where it would stand in line and the wait, about,
- * before Run is pressed; or, when the price check refused it, the words (the toolbar's price slot has no room for them
- * on a phone), with the link or offer the answer carries.
+ * The line under a composer's toolbar for a run on this studio's GPUs: when it would be ready, before Run is pressed
+ * ("Ready in about 2 min", "Starts when a GPU is free", "Ready in seconds"), with `offer` after a long wait (the account's
+ * own GPU or key for this run, once: "Run it now on your GPU"); or, when the price check refused it, the words (the
+ * toolbar's price slot has no room for them on a phone), with the link or offer the answer carries.
*/
-export function PoolNote({ state, className }: { state: PoolState; className?: string }) {
+export function PoolNote({ state, offer, className }: { state: PoolState; offer?: { label: string; run: () => void }; className?: string }) {
const interest = useInterest();
const href = safeLink(state.action?.url);
if (!state.refused) {
if (!state.wait) return null;
+ const press = state.long ? offer : undefined;
return (
- <p data-pool-note="wait" className={cn("px-2 text-[12px] text-muted-foreground tabular-nums", className)}>
- {state.wait}
+ <p data-pool-note="wait" className={cn("flex flex-wrap items-center gap-x-2 px-2 text-[12px] text-muted-foreground tabular-nums", className)}>
+ <span>{capitalFirst(state.wait)}</span>
+ {press && (
+ <button
+ type="button"
+ data-wait-offer
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={press.run}
+ className="inline-flex min-h-6 items-center font-medium text-brand-text underline-offset-2 hover:underline"
+ >
+ {press.label}
+ </button>
+ )}
</p>
);
}
diff --git a/src/components/studio/run-on.tsx b/src/components/studio/run-on.tsx
index c8b24f92..effb8087 100644
--- a/src/components/studio/run-on.tsx
+++ b/src/components/studio/run-on.tsx
@@ -101,7 +101,7 @@ const RunOnButton = forwardRef<HTMLButtonElement, React.ComponentProps<"button">
/**
* The composer's price chip with its Run on list: the price words and a caret; it opens a popover (desktop) or a bottom
- * sheet (phone) titled "Run on". `tooltip`: where the run goes and the wait ("Runs on our GPUs · Next in line").
+ * sheet (phone) titled "Run on". `tooltip`: where the run goes and the wait ("Runs on our GPUs · ready in about 2 min").
*/
export function RunOnChip({
rows,
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index cb73e4ad..132ad502 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -1491,8 +1491,12 @@ export interface Generation {
notCharged?: true;
/** "checking": its outputs wait for the moderation service before they show (on this install's GPUs: "Working"). */
stage?: "checking";
- /** A run waiting for this install's GPUs: its place in line and the wait, about (GET /api/generations/<id>). */
- queue?: { place: number; etaSeconds: number | null };
+ /**
+ * A run waiting for this install's GPUs: its place in line and the wait, about (GET /api/generations/<id>). `unknown`:
+ * no GPU that could run it can take it now, so it starts when one is free; `returnAt` (epoch ms): when the first of
+ * them is due back, when one says.
+ */
+ queue?: { place: number; etaSeconds: number | null; unknown?: true; returnAt?: number };
/**
* A run working on this install's GPUs: the address of its latest preview picture (a JPEG, for the run's own account
* only), while there is one.
diff --git a/src/lib/hosted.ts b/src/lib/hosted.ts
index a8cc1e6a..e365c4f3 100644
--- a/src/lib/hosted.ts
+++ b/src/lib/hosted.ts
@@ -4,7 +4,7 @@ import { useEffect, useState } from "react";
import { useMutation, useQuery, type QueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import type { GenerationRequest } from "./catalog/types";
-import { lineWords } from "./pool-line";
+import { lineWords, waitWords } from "./pool-line";
import type { OwnSetup } from "./own-setup";
/**
@@ -94,10 +94,19 @@ export function useSettled<T>(value: T, ms = 300): T {
return v;
}
-/** Where a new run would stand in line on this studio's GPUs right now (1: next), and the wait, about (null: unknown). */
+/**
+ * Where a new run would stand in line on this install's GPUs right now (1: next), and the wait, about (null: unknown).
+ * The run is taken whatever the line. `unknown`: no GPU that could run it can take it now, so it starts when one is free
+ * (`returnAt`: when the first is due back, when one says); `light`: light work, ready in seconds; `long`: a wait long
+ * enough that an account with its own GPU or key is offered it for this run, once.
+ */
export interface HostedLine {
place: number;
etaSeconds: number | null;
+ unknown?: true;
+ returnAt?: number;
+ light?: true;
+ long?: true;
}
/** The price check's answer for a run on this studio's GPUs: the quote, and where the run would stand in line. */
@@ -157,17 +166,19 @@ export function refreshPriceChecks(qc: QueryClient): void {
* - `refused`: the run wouldn't be taken now (busy, a limit, not offered here, closed, paused, a top-up): Run is off,
* and the price slot says the service's words (`text`), with its line under them (`sub`) and its link or offer;
* `setup`: it runs on the visitor's own setup, whose label is `text`, and Run opens that setup instead of staying off;
- * - otherwise the price (`text`: the service's words, empty when there is none) and, under it, where the run would stand
- * in line and the wait (`wait`).
+ * - otherwise the price (`text`: the service's words, empty when there is none) and, under it, when the run would be
+ * ready (`wait`, inside a sentence: "ready in about 2 min", "starts when a GPU is free", "ready in seconds"; none when
+ * nothing is known), and whether the wait is long (`long`: an account's own GPU or key may be offered for this run).
* Null while there is no answer yet.
*/
export function poolRunState(
check: HostedCheck | null | undefined,
-): { refused: boolean; text: string; sub?: string; wait?: string; action?: BillingAction; offer?: BillingOffer; setup?: OwnSetup } | null {
+): { refused: boolean; text: string; sub?: string; wait?: string; long?: boolean; action?: BillingAction; offer?: BillingOffer; setup?: OwnSetup } | null {
const q = check?.quote;
if (!q) return null;
if (!q.allowed) return { refused: true, text: q.text, ...(q.sub && { sub: q.sub }), ...(q.action && { action: q.action }), ...(q.offer && { offer: q.offer }), ...(q.ownSetup && { setup: q.ownSetup }) };
- return { refused: false, text: q.text, ...(q.sub && { sub: q.sub }), ...(check?.line && { wait: lineWords(check.line) }) };
+ const wait = check?.line ? waitWords(check.line) : null;
+ return { refused: false, text: q.text, ...(q.sub && { sub: q.sub }), ...(wait && { wait }), ...(check?.line?.long && { long: true }) };
}
/**
diff --git a/src/lib/pool-line.ts b/src/lib/pool-line.ts
index d1c9d696..52be624d 100644
--- a/src/lib/pool-line.ts
+++ b/src/lib/pool-line.ts
@@ -1,14 +1,52 @@
/**
- * The words for a run's place in line on this studio's GPUs (hosted runs), shared by the price check before Run and the
- * run's tile: "Next in line · about 40 s", "In line · 3rd · about 2 min". A run shows only "In line" (with its place and
- * wait), "Working" (with its progress), then its result.
+ * The words for a run's place in line on this install's GPUs (hosted runs). Before Run, the line under the toolbar says
+ * when the result would be ready ("Ready in about 2 min", "Starts when a GPU is free", "Ready in seconds"); a run's tile
+ * says where it is and when ("Next in line · ready in about 40 s", "In line · 3rd · starts when a GPU is free"). A run
+ * shows only "In line", "Working", then its result: it is taken whatever the line, and never ends for a wait.
*/
-/** "In line · 3rd · about 40 s": a run's place on this studio's GPUs (1: next), and the wait, about. */
-export function lineWords(q: { place: number; etaSeconds: number | null }): string {
- const n = Math.max(1, Math.floor(q.place));
- const ord = n % 100 >= 11 && n % 100 <= 13 ? "th" : ({ 1: "st", 2: "nd", 3: "rd" } as Record<number, string>)[n % 10] ?? "th";
+/**
+ * A place in line (1: next) and the wait, about (`etaSeconds`, until the result; null: unknown). `unknown`: no GPU that
+ * could run it can take it now, so it starts when one is free; `returnAt` (epoch ms): when the first of them is due
+ * back, when one says. `light`: light work only (joins, trims), which needs no GPU.
+ */
+export interface LineFacts {
+ place: number;
+ etaSeconds: number | null;
+ unknown?: boolean;
+ returnAt?: number;
+ light?: boolean;
+}
+
+/** "about 40 s", "about 2 min", "about 3 h". */
+export function aboutWords(seconds: number): string {
+ if (seconds < 60) return `about ${Math.max(5, Math.round(seconds / 5) * 5)} s`;
+ if (seconds < 90 * 60) return `about ${Math.max(1, Math.round(seconds / 60))} min`;
+ return `about ${Math.round(seconds / 3600)} h`;
+}
+
+/**
+ * When the run would be done, or start, in words inside a sentence: "ready in about 40 s", "ready in seconds", "starts
+ * when a GPU is free", "starts in about 3 h". Null when nothing is known (no estimate yet): nothing is guessed.
+ */
+export function waitWords(q: LineFacts, now = Date.now()): string | null {
+ if (q.light) return "ready in seconds";
+ if (q.unknown) {
+ const ms = q.returnAt ? q.returnAt - now : 0;
+ return ms > 0 ? `starts in ${aboutWords(ms / 1000)}` : "starts when a GPU is free";
+ }
const s = q.etaSeconds;
- const eta = s === null || !Number.isFinite(s) || s < 0 ? "" : s < 60 ? ` · about ${Math.max(5, Math.round(s / 5) * 5)} s` : ` · about ${Math.round(s / 60)} min`;
- return n === 1 ? `Next in line${eta}` : `In line · ${n}${ord}${eta}`;
+ return s === null || !Number.isFinite(s) || s < 0 ? null : `ready in ${aboutWords(s)}`;
+}
+
+/** The same words opening a line of their own ("Ready in about 2 min"). */
+export const capitalFirst = (s: string): string => (s ? s[0].toUpperCase() + s.slice(1) : s);
+
+/** "In line · 3rd · ready in about 2 min": a run's place on this install's GPUs (1: next), and its wait (waitWords). */
+export function lineWords(q: LineFacts, now = Date.now()): string {
+ const n = Math.max(1, Math.floor(q.place));
+ const ord = n % 100 >= 11 && n % 100 <= 13 ? "th" : (({ 1: "st", 2: "nd", 3: "rd" } as Record<number, string>)[n % 10] ?? "th");
+ const head = n === 1 ? "Next in line" : `In line · ${n}${ord}`;
+ const wait = waitWords(q, now);
+ return wait ? `${head} · ${wait}` : head;
}
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index 79c3ef5f..e2b3a6f1 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -469,6 +469,8 @@ export const RELAY_WORDS = {
export const POOL_WORDS = {
inLine: "In line",
working: "Working",
+ /** Working, with its model still loading (the GPU had another one loaded): no progress yet. */
+ gettingReady: "Working · getting ready",
failed: "Sorry, this one couldn't be made.",
} as const;
diff --git a/src/lib/run-place.ts b/src/lib/run-place.ts
index 73fc19b3..3fd5a09e 100644
--- a/src/lib/run-place.ts
+++ b/src/lib/run-place.ts
@@ -1,7 +1,7 @@
import { RUN_SHOWN_HEADER, shownHeader } from "./guest-access";
import { ownSetupDetail, ownSetupLabel, type OwnSetup } from "./own-setup";
import { placeOf, type Place } from "./place-name";
-import { lineWords } from "./pool-line";
+import { capitalFirst, waitWords, type LineFacts } from "./pool-line";
import { deviceLabel } from "./gpu/readiness";
import { billedTo, CLOUD_KEY, type CloudProvider } from "./your-keys";
@@ -144,7 +144,7 @@ export function runPlace(input: RunPlaceInput): RunPlace {
? "Placeholder results are on (Settings), so outputs are free stand-ins."
: refused
? (input.pool?.sub ?? refused)
- : `${input.pool?.sub ?? `Runs on ${place.text}${withModels}.`}${input.pool?.wait ? ` ${input.pool.wait}.` : ""}${signup ? " Free with an account." : ""}`;
+ : `${input.pool?.sub ?? `Runs on ${place.text}${withModels}.`}${input.pool?.wait ? ` ${capitalFirst(input.pool.wait)}.` : ""}${signup ? " Free with an account." : ""}`;
return {
where: "pool",
label: place.label,
@@ -282,7 +282,7 @@ export interface RunOnRow {
id: RunOnPick;
/** "Our GPUs", "Your GPU", "Your fal.ai key". */
label: string;
- /** "Free · Next in line · about 40 s", "Free · RTX 4090", "≈ $0.04 · billed to your fal.ai account". */
+ /** "Free · ready in about 40 s", "Free · RTX 4090", "≈ $0.04 · billed to your fal.ai account". */
sub: string;
/** Your GPU: it answers now (a green dot). Not answering is said in `sub`; the row can still be picked. */
online?: boolean;
@@ -364,7 +364,7 @@ export const IN_BROWSER: RunPlace = runPlace({ audience: "guest", engine: "brows
* `count`: runs one press starts (the quote is for one, said "each").
*/
export function checkedPool(
- check: { place?: "pool"; quote?: { text: string; sub?: string; allowed?: boolean; ownSetup?: OwnSetup }; line?: { place: number; etaSeconds: number | null } } | null | undefined,
+ check: { place?: "pool"; quote?: { text: string; sub?: string; allowed?: boolean; ownSetup?: OwnSetup }; line?: LineFacts } | null | undefined,
count = 1,
): { text: string; sub?: string; refused?: boolean; wait?: string; setup?: OwnSetup } | undefined {
if (check?.place !== "pool" || !check.quote) return undefined;
@@ -372,12 +372,13 @@ export function checkedPool(
// Refused before Run (busy, a limit, not offered here): its words, never priced "each"; with the visitor's own setup
// that runs it, when that is the answer.
if (check.quote.allowed === false) return { text, ...(sub && { sub }), refused: true, ...(ownSetup && { setup: ownSetup }) };
- return { text: count > 1 && text ? `${text} each` : text, ...(sub && { sub }), ...(check.line && { wait: lineWords(check.line) }) };
+ const wait = check.line ? waitWords(check.line) : null;
+ return { text: count > 1 && text ? `${text} each` : text, ...(sub && { sub }), ...(wait && { wait }) };
}
/** What a tool page's price slot and Run say for a run on this studio's GPUs (toolPoolPrice). */
export interface ToolPoolPrice {
- /** The service's words for the price, then where the run would stand in line ("Free · In line · 2nd · about 3 min"). */
+ /** The service's words for the price, then when the run would be ready ("Free · ready in about 3 min"). */
text: string;
/** The run wouldn't be taken now: Run is off, and `text` says why (unless `setup` runs it instead). */
refused: boolean;
@@ -395,7 +396,7 @@ export interface ToolPoolPrice {
*/
export function toolPoolPrice(check: unknown): ToolPoolPrice | null {
if (!check || typeof check !== "object") return null;
- const c = check as { place?: unknown; quote?: { allowed?: boolean; amount?: number; priceVersion?: string; text?: string; sub?: string; ownSetup?: OwnSetup }; line?: { place: number; etaSeconds: number | null } };
+ const c = check as { place?: unknown; quote?: { allowed?: boolean; amount?: number; priceVersion?: string; text?: string; sub?: string; ownSetup?: OwnSetup }; line?: LineFacts };
if (c.place !== "pool" || !c.quote || typeof c.quote.text !== "string") return null;
const pool = checkedPool({ place: "pool", quote: { ...c.quote, text: c.quote.text }, ...(c.line && { line: c.line }) });
if (!pool) return null;
diff --git a/src/server/account-tool-run.ts b/src/server/account-tool-run.ts
index 57bbbe3b..b3f8174f 100644
--- a/src/server/account-tool-run.ts
+++ b/src/server/account-tool-run.ts
@@ -19,7 +19,7 @@ import { queueRelease } from "./billing-outbox";
import { gateGeneration, GPU_SETUP_HEADER } from "./gpu/gate";
import { gpuTargetFor } from "./gpu/target";
import { runOnPool } from "./hosted";
-import { decideToolPlace, GUEST_PLAN, madeRunProblem, moderateRun, poolMayTake, poolOutputsCap, readWishes, reservePool, toolPoolQuote, type PlaceWish, type PoolLine, type Refusal, type ToolPoolRun } from "./hosted-run";
+import { decideToolPlace, GUEST_PLAN, madeRunProblem, moderateRun, policyWait, poolMayTake, poolOutputsCap, readWishes, reservePool, toolPoolQuote, type PlaceWish, type PoolLine, type Refusal, type ToolPoolRun } from "./hosted-run";
import { cancelGeneration, captureRun } from "./generations";
import { accountActiveRuns, AdmitRefused, admitRun, clientAddress, closeAdmission, forgetAdmission, openAdmission, poolLimitRefusal } from "./pool-limits";
import { hit, unhit } from "./rate";
@@ -550,10 +550,10 @@ async function startOnPool<T>(
const claim = await claimToolPress();
if (claim && "answer" in claim) return back(fromAnswer(claim.answer));
let stamp: RunStamp;
- if (pool.light) stamp = { place: "pool", light: true, ...(mod.checkOutputs && { checkOutputs: true }) };
+ if (pool.light) stamp = { place: "pool", light: true, ...(mod.checkOutputs && { checkOutputs: true }), ...policyWait(pool.policy) };
else {
// One hold per try of a press of Run: every send of the try asks for it by the same request id.
- const held = await reservePool(account, pool.main.req, pool.main.planned, run.shown ?? null, mod.checkOutputs, pool.steps, claim?.press ?? null);
+ const held = await reservePool(account, pool.main.req, pool.main.planned, run.shown ?? null, mod.checkOutputs, pool.steps, claim?.press ?? null, pool.policy);
if (!held.ok) return back(refuse(held.refusal.status, held.refusal.body.error, held.refusal.body, held.refusal.headers));
stamp = held.stamp;
}
diff --git a/src/server/billing.ts b/src/server/billing.ts
index 06fc82a5..7d858dcd 100644
--- a/src/server/billing.ts
+++ b/src/server/billing.ts
@@ -102,8 +102,24 @@ export interface Policy {
/**
* Limits on runs on this install's GPUs, counted on those runs only (never on runs on the account's own GPU or key).
* 0 or absent: no such limit. `addressRunsPerHour`: runs there from one client address an hour.
+ *
+ * `giveUpS`: how long a run there may wait before it first starts (s; 0: as long as it takes). Present, it wins over
+ * the reserve answer's `maxWaitMs`; absent, that answer (else FUOBE_POOL_WAIT_MIN) says. `offerAfterS`: after how
+ * long a wait the line before Run offers an account its own GPU or key for that run, once (absent: POOL_OFFER_AFTER_S).
*/
- limits: { activeRuns: number; waiting: number; runsPerHour: number; outputsPerRun: number; maxMegapixels: number; maxSeconds: number; keepDays: number; spaceBytes: number; addressRunsPerHour?: number };
+ limits: {
+ activeRuns: number;
+ waiting: number;
+ runsPerHour: number;
+ outputsPerRun: number;
+ maxMegapixels: number;
+ maxSeconds: number;
+ keepDays: number;
+ spaceBytes: number;
+ addressRunsPerHour?: number;
+ giveUpS?: number;
+ offerAfterS?: number;
+ };
/**
* Where a run goes when the account could run it on its own GPU and on this install's: "pool" for this install's, "own"
* (or absent) for its own GPU, as before. A place the request names always wins.
@@ -250,12 +266,16 @@ export const POLICY_RETRY_MS = { account: 5_000, guest: 60_000 };
*/
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`). */
+/**
+ * A policy as kept: when it was read, how long it stands, when the service last answered (`goodAt`), and the place its
+ * last answer put first (`prefer`), kept for as long as the service doesn't answer (lastPrefer).
+ */
interface PolicyEntry {
at: number;
ttlMs: number;
policy: Policy | null;
goodAt?: number;
+ prefer?: Policy["prefer"];
}
/**
@@ -277,7 +297,7 @@ export async function policy(accountId: string | null): Promise<Policy | null> {
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, goodAt: Date.now() });
+ keep({ at: Date.now(), ttlMs, policy: p, goodAt: Date.now(), ...(p.prefer && { prefer: p.prefer }) });
return p;
} catch (e) {
logDown("policy", e);
@@ -286,11 +306,43 @@ export async function policy(accountId: string | null): Promise<Policy | null> {
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 }) });
+ keep({ at: now, ttlMs: last && goodAt !== undefined ? Math.min(retryMs, goodAt + POLICY_KEEP_MS - now) : retryMs, policy: last, ...(goodAt !== undefined && { goodAt }), ...(hit?.prefer && { prefer: hit.prefer }) });
return last;
}
}
+/**
+ * The place the service's last answer put first, however long ago it answered (kept while it doesn't): the account's,
+ * else a guest's. A run that would have gone to this install's GPUs keeps waiting for them while the service is quiet,
+ * never moved to the account's own GPU for that. Undefined: it never answered here, or put none first. No service:
+ * OPEN_POLICY's (none).
+ */
+export function lastPrefer(accountId: string | null): Policy["prefer"] {
+ if (!billingConfigured()) return OPEN_POLICY.prefer;
+ const cache = globalThis.__fuobeBillingPolicies;
+ const own = cache?.get(accountId ?? "");
+ // (Its own last answer, when the service ever answered for it; else a guest's.)
+ return own?.goodAt !== undefined ? own.prefer : cache?.get("")?.prefer;
+}
+
+/** After how long a wait the line before Run offers an account its own GPU or key for that run, when the policy says none (s). */
+export const POOL_OFFER_AFTER_S = 1200;
+
+/**
+ * How long a run on this install's GPUs may wait before it first starts, as the policy says (ms; 0: as long as it takes).
+ * Undefined when the policy says nothing: the reserve answer's `maxWaitMs`, else FUOBE_POOL_WAIT_MIN, decide as before.
+ */
+export function policyGiveUpMs(p: Pick<Policy, "limits"> | null | undefined): number | undefined {
+ const s = p?.limits?.giveUpS;
+ return typeof s === "number" && Number.isFinite(s) && s >= 0 ? Math.round(s * 1000) : undefined;
+}
+
+/** After how long a wait the line before Run offers an account its own GPU or key, as the policy says (s). */
+export function policyOfferAfterS(p: Pick<Policy, "limits"> | null | undefined): number {
+ const s = p?.limits?.offerAfterS;
+ return typeof s === "number" && Number.isFinite(s) && s >= 0 ? s : POOL_OFFER_AFTER_S;
+}
+
/**
* The policy as last read, with no call to the service: undefined when none is kept (or it is too old). No service:
* OPEN_POLICY.
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index f4c082fa..0a53f152 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -9,7 +9,7 @@ import { db } from "../db";
import { loadIndex } from "../gpu/index-file";
import { hostedRunsOn } from "../hosted-switch";
import { catalogVersion } from "./catalog-version";
-import { cleanFacts, dropProgress, endTask, json, logWorkerJob, noteProgress, setPoolClocks, setPoolGiveBack, setPoolLost, setTask, takeTask, taskById, type TaskRow } from "./tasks";
+import { cleanFacts, dropProgress, endTask, json, logWorkerJob, noteCold, noteProgress, setPoolClocks, setPoolGiveBack, setPoolLost, setTask, takeTask, taskById, taskCold, type TaskRow } from "./tasks";
import { queueSettings, runCeilingMs } from "../queue-settings";
import { createWorker, offerNextToken, revokeWorker, rotateWorker, type WorkerRow } from "./workers";
@@ -461,6 +461,9 @@ function claimed(t: TaskRow, w: WorkerRow, device: string, now: number): Claimed
// allows), puts it back as it was, so a task no worker ever ran keeps its wait limit.
const before = t.ticket_json && t.state === "waiting" ? { extra_json: JSON.stringify({ ...json<Record<string, unknown>>(t.extra_json, {}), claimedBefore: t.claimed_at ?? null, claimFor: now }) } : {};
const c = takeTask(t, device, now, { worker_id: w.id, ...before, ...(t.state !== "waiting" && t.device === device && t.claimed_at && { claimed_at: t.claimed_at }) });
+ // A GPU job taken by a worker with another model loaded (or none) loads its model first: it is "getting ready" until
+ // its first step reports. A light CPU job and a finishing job load none.
+ if (t.state === "waiting" && t.pools && t.slot !== "cpu" && !t.finish_json && !!t.lane && w.warm_lane !== t.lane) noteCold(t.id, now);
// A job given back once for running past its limit gets the whole run ceiling on its next try (a lane's times may
// come from shorter jobs than this one); past that, it fails. Light CPU work has the same limits in either slot. A
// finishing job has its lane's run ceiling (queue-settings.ts, the owner's to set).
@@ -826,14 +829,41 @@ function estFor(t: Pick<TaskRow, "lane" | "est_ms">, workers: WorkerRow[], typic
return (bench.length ? Math.min(...bench) : 0) || t.est_ms || typical(t.lane) || 60_000;
}
+/**
+ * A place in line: 1 is next. `etaSeconds`: about how long until it is done (null: unknown). `unknown`: no GPU that
+ * could run it can take it now, so it starts when one is free; `returnAt` (epoch ms): when the first of them is due
+ * back, when one says.
+ */
+export interface LinePlace {
+ place: number;
+ etaSeconds: number | null;
+ unknown?: true;
+ returnAt?: number;
+}
+
+/**
+ * When a worker that can't take work now is due back, when it says (null: it doesn't, or it is on): the start of its
+ * hours, or the end of a pause on its PC that has one ("Paused here until 16:30"). One that is silent, paused on the
+ * website, draining or too old for job tickets says nothing of when.
+ */
+function backAt(w: WorkerRow, now: number): number | null {
+ if (w.revoked_at || w.paused_server || w.drain || (w.protocol ?? 0) < MIN_PROTOCOL || !w.seen_at || now - w.seen_at > RELAY_TIMES.poolSilentMs) return null;
+ const until = w.paused_local ? (w.local_until && w.local_until > now ? w.local_until : null) : null;
+ if (w.paused_local && until === null) return null;
+ const h = hoursAt(hoursOf(w), until ?? now);
+ if (h.inside) return until;
+ return h.nextChangeAt && h.nextChangeAt > now ? h.nextChangeAt : null;
+}
+
/**
* Where a waiting task is in line, and about how long until it is done. Every task ahead of it counts, whatever its lane,
* in the order the workers serve them (LINE_ORDER), when a worker that may run this one may run that one too: one GPU
* serves every lane it has in that order. The wait adds what is left of the jobs those workers are running now, the
* load of its lane when none has it warm, and its own run. No worker able to run it right now (paused, outside its
- * hours): its place, with no estimate.
+ * hours, silent, built before this studio's update): its place, with no estimate (`unknown`), and the time the first of
+ * them is due back when one says (`returnAt`: its hours start, or the end of a pause on its PC).
*/
-export function placeInLine(t: TaskRow, now = Date.now()): { place: number; etaSeconds: number | null } {
+export function placeInLine(t: TaskRow, now = Date.now()): LinePlace {
const d = db();
const all = poolWorkers().filter((w) => sharePool({ pools: w.pool }, t));
// Each worker serves a task in one of its slots (slotFor): a slot's own line is the tasks that slot would take.
@@ -844,7 +874,10 @@ export function placeInLine(t: TaskRow, now = Date.now()): { place: number; etaS
// could run it at all).
const able = workers.length ? workers : all.filter((w) => serves(t, w));
const ahead = before.filter((x) => sharePool(x, t) && (!able.length || able.some((w) => serves(x, w))));
- if (!workers.length) return { place: ahead.length + 1, etaSeconds: null };
+ if (!workers.length) {
+ const back = able.map((w) => backAt(w, now)).filter((at): at is number => at !== null);
+ return { place: ahead.length + 1, etaSeconds: null, unknown: true, ...(back.length && { returnAt: Math.min(...back) }) };
+ }
const typical = memo(typicalPoolMs);
const own = estFor(t, workers, typical);
const warm = workers.some((w) => w.warm_lane === t.lane);
@@ -960,9 +993,9 @@ function onSoon(w: WorkerRow, now: number): boolean {
/**
* Is every worker that could run an account's job of this workflow (any workflow: null) away now: paused, draining,
* outside its hours, silent, or never connected? Only workers that take job tickets now count (ticketReady), as an
- * account's run goes as one. A run made then would wait for nothing until its wait limit ended it, so the price check
- * says "Starting soon" (Run is off), and a press of Run makes nothing. False when no worker could run it at all
- * (workersCanRun refuses that) or one is on.
+ * account's run goes as one. A run made then is taken all the same and waits in line until one is back: the price check
+ * says it starts when a GPU is free, and Run stays on. False when no worker could run it at all (workersCanRun refuses
+ * that) or one is on.
*/
export function workersAway(workflowId: string | null, now = Date.now()): boolean {
const able = ableWorkers(workflowId, { tickets: true });
@@ -1003,9 +1036,10 @@ export function lineFacts(accountId: string | null, asked: string | null, now =
// online, count those workers only).
const version = catalogVersion();
const probe = { id: "", principal: accountId ? `acct:${accountId}` : "guest", account: accountId ?? "guest", class: "free", pools: "pool", lane, needs_json: needs ? JSON.stringify({ ...needs, ...(version && { catalogVersion: version }) }) : null, rank_at: now, created_at: now, stop: 0, only_worker: null, est_ms: null, slot: workflowId && cpuWorkflow(workflowId) ? "cpu" : null, finish_json: null } as unknown as TaskRow;
- const p = lane ? placeInLine(probe, now) : { place: (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting'").get() as { n: number }).n + 1, etaSeconds: null };
+ const p: LinePlace = lane ? placeInLine(probe, now) : { place: (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting'").get() as { n: number }).n + 1, etaSeconds: null };
const online = poolWorkers().filter((w) => eligible(w, now) && (!lane || fitsSlot({ ...probe, created_at: 0 }, w, now, slotFor(probe, w)))).length;
- return { lane: lane ?? "small", ahead: p.place - 1, etaS: p.etaSeconds, workersOnline: online, nextOpenAt: null };
+ // With none of them on now: when the first is due back, when one says.
+ return { lane: lane ?? "small", ahead: p.place - 1, etaS: p.etaSeconds, workersOnline: online, nextOpenAt: p.returnAt ?? null };
}
/**
@@ -1051,12 +1085,14 @@ const SAME_PRESS = "(CASE WHEN @hold IS NOT NULL THEN json_extract(g.request_jso
* start). Null for a run's first job: it waits from now.
* - `started`: a worker took one of those jobs. The run's wait limit no longer applies then (it applies only before the
* run's first start).
+ * - `later`: the row is a later step of its run (it waits for a step the same press made). It has no wait limit: its run
+ * was taken in line already, so it waits at the run's place for as long as it takes.
*
* A chain's later step and a finishing job keep the run's place this way, instead of going behind every run sent after
* the run started. Only steps the same press made count (the same billing hold; with none, the same batch): a result
* kept from an earlier run that a step uses gives it neither that run's place nor its start. Null: no such row.
*/
-export function runPlaceOf(generationId: string): { class: "paid" | "free"; rankAt: number | null; started: boolean } | null {
+export function runPlaceOf(generationId: string): { class: "paid" | "free"; rankAt: number | null; started: boolean; later: boolean } | null {
const d = db();
const g = d
.prepare(
@@ -1080,10 +1116,21 @@ export function runPlaceOf(generationId: string): { class: "paid" | "free"; rank
)
.all(press) as Pick<TaskRow, "rank_at" | "claimed_at">[];
const boost = Math.max(0, Math.min(Number(g.boost) || 0, 24 * 60 * 60_000));
+ const later =
+ !!g.depends_on &&
+ !!d
+ .prepare(
+ `SELECT 1 FROM generations s,
+ json_each(CASE WHEN substr(s.depends_on, 1, 1) = '[' AND json_valid(s.depends_on) THEN s.depends_on ELSE json_array(s.depends_on) END) d
+ JOIN generations g ON g.id = d.value
+ WHERE s.id = @id AND s.depends_on IS NOT NULL AND ${SAME_PRESS} LIMIT 1`,
+ )
+ .get(press);
return {
class: g.cls === "paid" ? "paid" : "free",
rankAt: jobs[0]?.rank_at ?? (g.depends_on ? g.created_at - boost : null),
started: jobs.some((t) => t.claimed_at !== null),
+ later,
};
}
@@ -1096,11 +1143,20 @@ export function cpuWorkflow(workflowId: string): boolean {
}
/** The queue block for GET /api/generations/<id>: the task's place in its lane and the estimated wait. Null when no pool task waits. */
-export function queueOfGeneration(generationId: string, now = Date.now()): { place: number; etaSeconds: number | null } | null {
+export function queueOfGeneration(generationId: string, now = Date.now()): LinePlace | null {
const t = db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ? AND pools IS NOT NULL AND state = 'waiting' LIMIT 1").get(generationId) as TaskRow | undefined;
return t ? placeInLine(t, now) : null;
}
+/**
+ * Is a run's job with a worker still getting ready: taken by a worker that had another model loaded (or none), with no
+ * step reported yet (its model loads)?
+ */
+export function gettingReady(generationId: string): boolean {
+ const t = db().prepare("SELECT progress_json FROM relay_tasks WHERE generation_id = ? AND pools IS NOT NULL AND state IN ('sending','queued','running') ORDER BY created_at DESC LIMIT 1").get(generationId) as Pick<TaskRow, "progress_json"> | undefined;
+ return !!t && taskCold(t);
+}
+
/** FUOBE_POOL_WAIT_MIN: how long a task for workers waits before it fails (30 minutes). */
export const poolWaitMs = () => {
const m = Number(process.env.FUOBE_POOL_WAIT_MIN);
diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.ts
index 470d059c..b3ecffb3 100644
--- a/src/server/computer/tasks.ts
+++ b/src/server/computer/tasks.ts
@@ -65,6 +65,8 @@ export interface Progress {
node?: string;
nodesDone?: number;
position?: number;
+ /** Taken by a worker with another model loaded (or none): loading its model, until its first step reports. */
+ cold?: boolean;
at: number;
}
@@ -579,10 +581,24 @@ export function noteProgress(id: string, r: Record<string, unknown>, now: number
d.transaction(() => {
const cur = d.prepare(`SELECT progress_json FROM relay_tasks WHERE id = ? AND ${STILL_HELD}`).get(id, lease) as Pick<TaskRow, "progress_json"> | undefined;
if (!cur) return;
- d.prepare(`UPDATE relay_tasks SET progress_json = ? WHERE id = ? AND ${STILL_HELD}`).run(JSON.stringify({ ...taskProgress(cur), ...p }), id, lease);
+ const next = { ...taskProgress(cur), ...p };
+ // Its first step reported: its model is loaded (noteCold), so it is no longer getting ready.
+ if (p.value !== undefined) delete next.cold;
+ d.prepare(`UPDATE relay_tasks SET progress_json = ? WHERE id = ? AND ${STILL_HELD}`).run(JSON.stringify(next), id, lease);
}).immediate();
}
+/**
+ * Note that a task a worker just took starts with its model to load (the worker had another lane's model loaded, or
+ * none): it is "getting ready" until its first step reports (noteProgress). Over a fresh attempt's empty progress only.
+ */
+export function noteCold(id: string, now: number): void {
+ rdb().prepare("UPDATE relay_tasks SET progress_json = ? WHERE id = ? AND progress_json IS NULL").run(JSON.stringify({ cold: true, at: now } satisfies Progress), id);
+}
+
+/** Is a task still getting ready: taken cold (noteCold), with no step reported since? */
+export const taskCold = (t: Pick<TaskRow, "progress_json">): boolean => taskProgress(t)?.cold === true;
+
/** A task still sent to the computer or worker that holds the lease given (the query's last parameter). */
const STILL_HELD = `state IN (${SENT_STATES.map((x) => `'${x}'`).join(",")}) AND lease_hash IS ?`;
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 9bcf38dd..65a87356 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -129,7 +129,7 @@ import { FILE_TROUBLE_WORDS, POOL_WORDS, RELAY_WORDS } from "@/lib/relay";
import { placeInLine, poolOnWorkers, poolRunsProvider, poolWaitMs, runOnPool } from "./hosted";
import { hostedRunsOn } from "./hosted-switch";
import { catalogVersion } from "./computer/catalog-version";
-import { poolLane, queueOfGeneration } from "./computer/pool";
+import { gettingReady, poolLane, queueOfGeneration, type LinePlace } from "./computer/pool";
import { noteCatalogProcess, processStart } from "./computer/ticket-refresh";
import { runPreviewAt } from "./computer/tasks";
import { runCeilingMs } from "./queue-settings";
@@ -194,6 +194,9 @@ export function toGeneration(r: Row): Generation {
// sentence when it can't finish: never the technical reason, which the owner reads in the accounts' runs.
const pool = stored.place === "pool";
const checking = r.stage === "checking";
+ // Working on the workers with its model still loading (taken by a worker that had another model loaded): "getting
+ // ready", with no progress yet.
+ const ready = pool && r.status === "running" && !checking && gettingReady(r.id);
const model = getModel(r.model_id);
const ar = request.params?.aspectRatio ?? model?.defaults?.aspectRatio;
// Rows read without the library join (the runner's own SELECTs) look the trash and folder up.
@@ -217,8 +220,8 @@ export function toGeneration(r: Row): Generation {
kind: r.kind,
status: r.status,
// In line on this install's GPUs (again, after an attempt): no progress.
- progress: pool && r.status === "queued" ? null : r.progress,
- message: pool ? poolMessage(r) : r.message,
+ progress: (pool && r.status === "queued") || ready ? null : r.progress,
+ message: pool ? poolMessage(r, ready) : r.message,
prompt: r.prompt,
request,
// Held for the moderation service's check: nothing of it is shown until it passes.
@@ -260,7 +263,7 @@ export function toGeneration(r: Row): Generation {
}
/** The owner's job waiting for the workers: its place in their line, as the Generation field. */
-function workerQueue(id: string): { queue: { place: number; etaSeconds: number | null } } | Record<string, never> {
+function workerQueue(id: string): { queue: LinePlace } | Record<string, never> {
const q = queueOfGeneration(id);
return q ? { queue: q } : {};
}
@@ -299,10 +302,10 @@ export function shownError(id: string, raw: string | null): string | null {
return stored.place === "pool" ? poolError(id, raw, !!stored.hold && !!stored.charged) : raw;
}
-/** A pool row's words while it goes: in line, or working on it. */
-function poolMessage(r: Pick<Row, "status" | "message">): string | null {
+/** A pool row's words while it goes: in line, or working on it (`ready`: still getting ready, its model loading). */
+function poolMessage(r: Pick<Row, "status" | "message">, ready = false): string | null {
if (r.status === "queued") return POOL_WORDS.inLine;
- if (r.status === "running") return POOL_WORDS.working;
+ if (r.status === "running") return ready ? POOL_WORDS.gettingReady : POOL_WORDS.working;
return null;
}
@@ -351,7 +354,7 @@ const PLAIN_POOL_ERRORS = (() => {
})();
/** A pool row's place in line, as the Generation field (none once it has started). */
-function poolQueue(id: string): { queue: { place: number; etaSeconds: number | null } } | Record<string, never> {
+function poolQueue(id: string): { queue: LinePlace } | Record<string, never> {
const q = placeInLine(id);
return q ? { queue: q } : {};
}
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
index 312f08b8..107249a5 100644
--- a/src/server/hosted-run.ts
+++ b/src/server/hosted-run.ts
@@ -14,12 +14,16 @@ import {
cachedPolicy,
forgetBalance,
FREE_QUOTE,
+ lastPrefer,
policy as billingPolicy,
+ policyGiveUpMs,
+ policyOfferAfterS,
quote as billingQuote,
refusalStatus,
reserve,
type Policy,
type Quote,
+ type QueueFacts,
type RefuseCode,
type RunFacts,
} from "./billing";
@@ -44,7 +48,7 @@ import { poolLimitRefusal } from "./pool-limits";
import { runAsTenant } from "./tenant";
import { needsGpu, ownSetupHere, poolCardRefuses, requestOwnSetup } from "./pool-own-setup";
import { ADD_KEY_HEADER } from "@/lib/your-keys";
-import { placeOf, type Place } from "@/lib/place-name";
+import type { Place } from "@/lib/place-name";
import { placeFor, placeOfAccount } from "./place-name";
import { rememberedPlace } from "./run-on";
@@ -127,13 +131,6 @@ const OWN = { kind: "own" } as const;
/** What an account whose own GPU didn't answer is asked, when its run named no place (never moved and charged unasked). */
export const ownGpuQuiet = (place: Place): string => `Your GPU isn't answering right now. Run this on ${place.text} instead, or wait for your GPU.`;
-/**
- * Run pressed while every GPU here that could run it is away (it was there when the price check before Run asked): no
- * run is made, and the answer promises no start. It is no billing refusal, so no card opens for it: the page says the
- * words and asks the price check again, which now says "Starting soon" with Run off until one of those GPUs is back.
- */
-const awayRefusal = (): Refusal => ({ status: 503, body: { error: BILLING_WAIT.run, code: "busy" }, headers: { "Retry-After": "15" } });
-
/** A run this install's GPUs won't take, refused in the words the price check before Run gives too. */
const notOffered = (error: string): { kind: "refuse"; refusal: Refusal } => ({ kind: "refuse", refusal: { status: 403, body: { error, code: "not-offered" }, headers: { [BILLING_HEADER]: "not-offered" } } });
@@ -154,8 +151,6 @@ const ownSetupRefusal = (setup: OwnSetup): { kind: "refuse"; refusal: Refusal }
function gateRefusal(gate: GateRefusal, place: Place): { kind: "refuse"; refusal: Refusal } {
if (gate.reason === "ownSetup") return ownSetupRefusal(gate.setup ?? needsGpu());
const error = gateText(gate, false, place);
- // Not right now (the GPUs that could run it are being updated): refused as a busy moment, with Run off until then.
- if (gate.reason === "busy") return { kind: "refuse", refusal: billingRefusal("busy", error) };
if (gate.reason === "model3d") return { kind: "refuse", refusal: { status: 403, body: { error, code: "own-gpu-tool" }, headers: {} } };
const r = notOffered(error);
if (gate.setup) r.refusal.body.ownSetup = gate.setup;
@@ -176,8 +171,13 @@ const prefersPool = (p: Policy | null | undefined): boolean => !!p?.hosted && p.
*/
const pickedPlace = (account: Account | null, wish: PlaceWish): PlaceWish => (account && !wish ? rememberedPlace(account.id) : undefined);
-/** This install's GPUs go first for this run: the policy says so, or the account picked them. */
-const poolFirst = (p: Policy | null | undefined, picked: PlaceWish): boolean => prefersPool(p) || picked === "pool";
+/**
+ * This install's GPUs go first for this run: the policy says so, or the account picked them. With no policy to read (the
+ * billing service doesn't answer), the place its last answer put first: a run that would go to this install's GPUs keeps
+ * waiting for them, never moved to the account's own GPU because the service went quiet.
+ */
+const poolFirst = (p: Policy | null | undefined, picked: PlaceWish, accountId?: string | null): boolean =>
+ prefersPool(p) || picked === "pool" || (p === null && accountId !== undefined && lastPrefer(accountId) === "pool");
/** May a run of this kind use this install's GPUs under the policy (`kinds` absent: every kind)? */
export const kindAllowed = (p: Pick<Policy, "kinds">, kind: RunFacts["kind"]): boolean => p.kinds?.[kind] !== false;
@@ -321,10 +321,11 @@ export function pricedSteps(steps: PlannedStep[]): NonNullable<RunFacts["steps"]
* or kind not offered there, a model their card can't run, LoRAs, a kind of file, more outputs at once than a run there
* makes (`outputs`: a tool's run, which can't be cut down the way the studios' own runs are), one that runs on the
* visitor's own setup only (`ownSetup`: a static item of own-setup.ts, or a workflow none of this install's GPUs can
- * run right now: none holds its files, serves its lane, or has the memory), or (`busy`) not right now: the GPUs that
- * could run it are being updated.
+ * run right now: none holds its files, serves its lane, or has the memory). Each is a label the visitor reads before
+ * Run, with the setup that runs it. A run these GPUs take but can't start right now (every one that could is away, or
+ * being updated) is no reason: it waits in line (runWaits).
*/
-export type GateReason = "model3d" | "notOffered" | "rtxCard" | "loras" | "inputs" | "outputs" | "ownSetup" | "busy";
+export type GateReason = "model3d" | "notOffered" | "rtxCard" | "loras" | "inputs" | "outputs" | "ownSetup";
/**
* A gate's refusal: its reason, and the visitor's own setup that would run it (`setup`: always with "ownSetup"; with the
@@ -386,13 +387,22 @@ export function poolGate(
}
const problem = steps && p ? stepsProblem(p, steps) : null;
if (problem) return { ok: false, reason: problem === hostedWords(placeFor(p)).rtxCard ? "rtxCard" : "notOffered", setup: gpu };
- // A run its GPUs could take, but none of them can right now (every one that could is built from the catalog before
- // this studio's update): Run is off until one is updated, never a run that waits in line for nothing.
- const endpoints = [planned.route.endpoint, ...(steps ?? []).filter((s) => s.provider === "comfyui").map(stepEndpoint)];
- if (!endpoints.every((e) => poolTicketsReady(e))) return { ok: false, reason: "busy" };
return { ok: true, steps };
}
+/**
+ * Does a run these GPUs take wait for one of them to be free: every GPU that could run some GPU step of it is away now
+ * (paused, silent, outside its hours: runAway), or built from the catalog before this studio's update (it takes the run
+ * once updated)? It is taken all the same, and waits in line in its place ("starts when a GPU is free"). Light work only
+ * (joins, trims) never waits for a GPU.
+ */
+export function runWaits(planned: Pick<Planned, "route">, steps: PlannedStep[] | null | undefined): boolean {
+ if (lightRun(steps)) return false;
+ if (runAway(planned, steps)) return true;
+ const endpoints = [planned.route.endpoint, ...(steps ?? []).filter((s) => s.provider === "comfyui" && !freeStep(s)).map(stepEndpoint)];
+ return !endpoints.every((e) => poolTicketsReady(e));
+}
+
/**
* The account a guest's price check plans a chain's later steps under: no real account has it (account ids hold no
* colon), and nothing planned under it is kept (plannedSteps throws every row away).
@@ -433,10 +443,11 @@ export function poolRequest(req: GenerationRequest, p: Pick<Policy, "limits"> |
* Where an account's run goes (hosted.ts has the order). Only with hosted runs on; otherwise always "own" (today).
*
* An account with a GPU of its own keeps it as before: its own GPU first (unless the policy puts this install's first),
- * and every run this install's GPUs wouldn't take (the service down, hosted runs closed to it, a model or a kind not
- * offered, LoRAs, inputs, a step no worker takes, 3D) goes to its own GPU, even while that GPU doesn't answer. Only a run
- * this install's GPUs would take, that named no place, whose own GPU doesn't answer, is asked about (never moved there,
- * and charged, unasked).
+ * and every run this install's GPUs wouldn't take (hosted runs closed to it, a model or a kind not offered, LoRAs,
+ * inputs, a step no worker takes, 3D) goes to its own GPU, even while that GPU doesn't answer. Only a run this install's
+ * GPUs would take, that named no place, whose own GPU doesn't answer, is asked about (never moved there, and charged,
+ * unasked). A run that goes to this install's GPUs is never moved to its own GPU because they are busy, away or being
+ * updated, or because the billing service went quiet: it waits in line for them.
*
* One order (the place a run names, then what only one place can run, then the account's own pick, then the policy):
* a run that names no place follows the account's pick (run-on.ts): its own GPU, at once and never asked about; or this
@@ -464,16 +475,19 @@ export async function decidePlace(account: Account, asked: GenerationRequest, wi
// call to the billing service); when none is kept, it is read while the GPU is checked.
let p = cachedPolicy(account.id);
let ownOffline = false;
- if (ownFallback && !poolFirst(p, picked)) {
+ if (ownFallback && !poolFirst(p, picked, account.id)) {
const [online, read] = await Promise.all([ownGpuOnline(account.id), p === undefined ? billingPolicy(account.id) : Promise.resolve(p)]);
p = read;
- if (!poolFirst(p, picked)) {
+ if (!poolFirst(p, picked, account.id)) {
if (online) return OWN;
ownOffline = true;
}
}
if (p === undefined) p = await billingPolicy(account.id);
- if (!p) return ownFallback ? OWN : { kind: "refuse", refusal: billingRefusal("paused", BILLING_WAIT.run) };
+ // The billing service doesn't answer: a run whose own GPU goes first goes there as before; one that goes to this
+ // install's GPUs (the service's last answer put them first, or the account picked them) is never moved to its own GPU
+ // for that: it waits for the service.
+ if (!p) return ownFallback && !poolFirst(p, picked, account.id) ? OWN : { kind: "refuse", refusal: billingRefusal("paused", BILLING_WAIT.run) };
// Closed to this account: its own GPU (or today's "Connect your GPU"); asked for by name, said so.
if (!p.hosted) return wish === "pool" ? notOffered(hostedWords(placeFor(p)).notHosted) : OWN;
// Planned, checked and priced for the outputs it would make there (the policy's cap per run).
@@ -485,17 +499,15 @@ export async function decidePlace(account: Account, asked: GenerationRequest, wi
return OWN;
}
}
- // The same check as the price check before Run (poolGate): what this install's GPUs can't take goes to the account's
- // own GPU when it has one and didn't ask for this install's; otherwise it is refused in the same words.
+ // The same check as the price check before Run (poolGate): what this install's GPUs can't take (a label the person
+ // reads before Run) goes to the account's own GPU when it has one and didn't ask for this install's; otherwise it is
+ // refused in the same words. A run they take is taken even while every GPU that could run it is away or being updated:
+ // it waits in line in its place until one is free, never moved to the account's own GPU for that.
const gate = poolGate(p, planned, req, () => stepsFor(account, req));
if (!gate.ok) {
if (ownFallback) return OWN;
return gateRefusal(gate, placeFor(p));
}
- // Every GPU here that could run it is off for now (paused, silent, outside its hours): a run made now would only wait
- // until its wait limit ended it. It goes to the account's own GPU as any run these GPUs can't take now, else it isn't
- // made (awayRefusal).
- if (runAway(planned, gate.steps)) return ownFallback ? OWN : { kind: "refuse", refusal: awayRefusal() };
// Its own GPU didn't answer the check: asked, never moved to this install's GPUs (and charged) without a word.
if (ownOffline) return { kind: "refuse", refusal: askPlace(placeFor(p)) };
return { kind: "pool", planned, policy: p, steps: gate.steps ? pricedSteps(gate.steps) : undefined, req, capped, light: lightRun(gate.steps) };
@@ -564,12 +576,24 @@ export async function moderateRun(
return { ok: false, refusal: { status, body: { error, code: a.code }, headers: {} } };
}
+/**
+ * The wait limit the policy gives a run on this install's GPUs (`limits.giveUpS`; 0: as long as it takes), as a stamp's
+ * field, when it gives one: for a run that sets nothing aside (light work), as reservePool stamps it for the others.
+ */
+export function policyWait(p: Pick<Policy, "limits"> | null | undefined): Pick<RunStamp, "waitMs"> {
+ const ms = policyGiveUpMs(p);
+ return ms === undefined ? {} : { waitMs: ms };
+}
+
/**
* Set the run's price aside (no billing service: nothing to set aside; the run is free). Returns the stamp the run's
* rows carry, or the refusal (402, 409 with the new price, 429, 503, 403; docs/billing-hook.md). `press`: the press of
* Run it belongs to and its try (run-requests.ts), so every send of that try reserves under one request id, and a new try
* under one of its own; none (a script): an id of this request's own. A reserve given up after a try that may have made a
* hold releases it by its request id, unless a send of the same try owns that hold (`press.gaveUp`).
+ *
+ * How long the run may wait before it first starts: the policy's `limits.giveUpS` when it says (0: as long as it takes),
+ * which wins over the reserve answer's `maxWaitMs`; else that answer's; else the install's own (FUOBE_POOL_WAIT_MIN).
*/
export async function reservePool(
account: Account,
@@ -579,8 +603,10 @@ export async function reservePool(
checkOutputs: boolean,
steps?: RunFacts["steps"],
press: Press | null = null,
+ policy: Pick<Policy, "limits"> | null = null,
): Promise<{ ok: true; stamp: RunStamp } | { ok: false; refusal: Refusal }> {
- const base: RunStamp = { place: "pool", ...(checkOutputs && { checkOutputs: true }) };
+ const giveUp = policyGiveUpMs(policy);
+ const base: RunStamp = { place: "pool", ...(checkOutputs && { checkOutputs: true }), ...(giveUp !== undefined && { waitMs: giveUp }) };
if (!billingConfigured()) return { ok: true, stamp: base };
const kind = outputKind(planned.op, planned.model);
const run: RunFacts = { ...runOnPool(account.id, () => runFacts(req, planned, kind)), ...(steps?.length && { steps }) };
@@ -619,35 +645,54 @@ export async function reservePool(
...(a.text && { charge: a.text }),
// Something was set aside (a free run's hold sets aside nothing): only then can a run that ends early say so.
...(Number(a.amount) > 0 && { charged: true }),
- ...(a.maxWaitMs > 0 && { waitMs: a.maxWaitMs }),
+ ...(giveUp === undefined && a.maxWaitMs > 0 && { waitMs: a.maxWaitMs }),
...(a.class === "paid" && { class: "paid" as const }),
...(Number.isFinite(boost) && boost > 0 && { boostMs: Math.min(boost, 24 * 60 * 60_000) }),
},
};
}
-/** Where a new run would stand in line on this install's GPUs right now (1: next), and the wait, about (null: unknown). */
+/**
+ * Where a new run would stand in line on this install's GPUs right now (1: next), and the wait, about (null: unknown).
+ * The run is taken whatever the line: Run stays on.
+ *
+ * - `unknown`: no GPU that could run it can take it now (away, or being updated): it starts when one is free.
+ * `returnAt` (epoch ms): when the first of them is due back, when one says.
+ * - `light`: light work only (joins, trims): ready in seconds, with no GPU.
+ * - `long`: the wait passes the policy's `offerAfterS` (or is unknown): an account with its own GPU or key that runs it
+ * may be offered it for this run, once.
+ */
export interface PoolLine {
place: number;
etaSeconds: number | null;
+ unknown?: true;
+ returnAt?: number;
+ light?: true;
+ long?: true;
}
-/** A price check's answer while every GPU that could run it is off for now: Run is off, and the wait is said. */
-const startingSoonQuote = (): Quote => ({ allowed: false, amount: 0, priceVersion: "", text: hostedWords(placeOf(null)).startingSoon, code: "busy", etaS: null });
+/** The line a price check says, from the queue's facts (and the service's own estimate, `q.etaS`, when it gave one). */
+function poolLine(facts: Pick<QueueFacts, "ahead" | "etaS" | "nextOpenAt">, o: { light: boolean; waits: boolean; p: Policy | null; q?: Quote }, now = Date.now()): PoolLine {
+ const place = Math.max(0, facts.ahead) + 1;
+ if (o.light) return { place, etaSeconds: null, light: true };
+ const afterMs = policyOfferAfterS(o.p) * 1000;
+ if (o.waits) {
+ const back = facts.nextOpenAt && facts.nextOpenAt > now ? facts.nextOpenAt : undefined;
+ return { place, etaSeconds: null, unknown: true, ...(back && { returnAt: back }), ...((!back || back - now > afterMs) && { long: true }) };
+ }
+ const eta = o.q?.etaS ?? facts.etaS ?? null;
+ return { place, etaSeconds: eta, ...(eta !== null && eta * 1000 > afterMs && { long: true }) };
+}
-/** A price check's answer for a run this install's GPUs won't take, in the words the run itself would get. */
/**
* A price check refused for what this install's GPUs don't take: its words, and (`ownSetup`) the visitor's own setup
* that runs it, so Run opens that setup (Connect your GPU, Add your key, or a guest's sign-up) instead of staying off.
*/
const notOfferedQuote = (text: string, setup?: OwnSetup): Quote & { ownSetup?: OwnSetup } => ({ allowed: false, amount: 0, priceVersion: "", text, code: "not-offered", ...(setup && { ownSetup: setup }) });
-/**
- * A gate's refusal as the price check's quote (gateText: the label's words for an own setup). Busy (the GPUs that could
- * run it are being updated) is quoted as code "busy", shown like the other busy moments with Run off.
- */
+/** A gate's refusal as the price check's quote (gateText: the label's words for an own setup), with that setup. */
const gateQuote = (gate: GateRefusal, guest: boolean, place: Place): Quote & { ownSetup?: OwnSetup } =>
- gate.reason === "busy" ? { ...notOfferedQuote(gateText(gate, guest, place)), code: "busy" } : notOfferedQuote(gateText(gate, guest, place), gate.reason === "model3d" ? undefined : gate.setup);
+ notOfferedQuote(gateText(gate, guest, place), gate.reason === "model3d" ? undefined : gate.setup);
/**
* A price check on this install's GPUs (hosted runs on): the plan there, the billing service's quote (no service: free,
@@ -687,38 +732,31 @@ export async function poolQuote(
}
if (planned.route.provider !== "comfyui") return null;
const hasGpu = !!account && !!accountGpu(account.id);
- if (account && hasGpu && wish !== "pool" && !poolFirst(p, picked) && (await ownGpuOnline(account.id))) return null;
+ if (account && hasGpu && wish !== "pool" && !poolFirst(p, picked, account.id) && (await ownGpuOnline(account.id))) return null;
if (p && !p.hosted) return null;
- const line = (facts: { ahead: number; etaS: number | null }, q?: Quote): PoolLine => ({ place: Math.max(0, facts.ahead) + 1, etaSeconds: q?.etaS ?? facts.etaS ?? null });
// What this install's GPUs won't take goes to the viewer's own GPU when it has one (as the run would); otherwise the
- // price check says so, and Run stays off.
+ // price check says its label, and Run opens the setup that runs it.
const gate = poolGate(p, planned, req, () => stepsFor(account, req));
if (!gate.ok) {
if (hasGpu && wish !== "pool") return null;
- return { planned, quote: gateQuote(gate, !account, placeFor(p)), line: line(queueFacts(account?.id ?? null, planned.route.endpoint)) };
- }
- // Every GPU here that could run it is off for now: Run is off and says it starts soon (the price check asks again by
- // itself, and Run comes back on once one is back), never a run that would wait for nothing.
- if (runAway(planned, gate.steps)) {
- if (hasGpu && wish !== "pool") return null;
- return { planned, quote: startingSoonQuote(), line: line(queueFacts(account?.id ?? null, planned.route.endpoint)) };
+ return { planned, quote: gateQuote(gate, !account, placeFor(p)), line: poolLine(queueFacts(account?.id ?? null, planned.route.endpoint), { light: false, waits: false, p }) };
}
+ // Taken whatever the line: while every GPU here that could run it is away (or being updated), the line says it starts
+ // when one is free, and Run stays on.
+ const queue = queueFacts(account?.id ?? null, planned.route.endpoint);
+ const shape = { light: lightRun(gate.steps), waits: runWaits(planned, gate.steps), p };
// Light work only (joins, trims): free, and never counted against the policy's limits, so the service isn't asked.
- if (lightRun(gate.steps)) {
- const queue = queueFacts(account?.id ?? null, planned.route.endpoint);
- return { planned, quote: FREE_QUOTE, line: line(queue) };
- }
+ if (shape.light) return { planned, quote: FREE_QUOTE, line: poolLine(queue, shape) };
// Priced once for every step of a chain that uses this install's GPUs. Its facts are read as the viewer (an input's
// size from its own files only: another's file reads as none, and says nothing of whether it exists).
const facts = { ...runOnPool(account?.id ?? null, () => runFacts(req, planned, outputKind(planned.op, planned.model))), ...(gate.steps && { steps: pricedSteps(gate.steps) }) };
- const queue = queueFacts(account?.id ?? null, planned.route.endpoint);
let q = await billingQuote(account ? accountFacts(account) : null, facts, queue);
// The policy's limits on this account's runs here, as the run would meet them (pool-limits.ts): said before Run.
if (q.allowed && account && p) {
const over = poolLimitRefusal(account.id, p, o.addr ?? null);
if (over) q = { ...q, allowed: false, code: "limit", text: over.error };
}
- return { planned, quote: q, line: line(queue, q) };
+ return { planned, quote: q, line: poolLine(queue, { ...shape, q }) };
}
/**
@@ -811,17 +849,20 @@ export async function decideToolPlace(account: Account, steps: ToolRunStep[], wi
const ownFallback = !!accountGpu(account.id) && wish !== "pool";
let p = cachedPolicy(account.id);
let ownOffline = false;
- if (ownFallback && !poolFirst(p, picked)) {
+ if (ownFallback && !poolFirst(p, picked, account.id)) {
const [online, read] = await Promise.all([ownGpuOnline(account.id), p === undefined ? billingPolicy(account.id) : Promise.resolve(p)]);
p = read;
- if (!poolFirst(p, picked)) {
+ if (!poolFirst(p, picked, account.id)) {
if (online) return OWN;
ownOffline = true;
}
}
if (p === undefined) p = await billingPolicy(account.id);
- if (!p) return ownFallback ? OWN : { kind: "refuse", refusal: billingRefusal("paused", BILLING_WAIT.run) };
+ // As decidePlace: a run that goes to this install's GPUs waits for a quiet service, never moved to its own GPU for it.
+ if (!p) return ownFallback && !poolFirst(p, picked, account.id) ? OWN : { kind: "refuse", refusal: billingRefusal("paused", BILLING_WAIT.run) };
if (!p.hosted) return wish === "pool" ? notOffered(hostedWords(placeFor(p)).notHosted) : OWN;
+ // What these GPUs can't take (a label) goes to its own GPU; what they take is taken, even while every GPU that could
+ // run it is away or being updated: it waits in line until one is free.
const gate = toolGate(p, account.id, steps);
if (gate === "unplanned") return OWN;
if (!gate.ok) {
@@ -848,28 +889,25 @@ export async function toolPoolQuote(
if (picked === "own") return null;
const p = await billingPolicy(account?.id ?? null);
const hasGpu = !!account && !!accountGpu(account.id);
- if (account && hasGpu && wish !== "pool" && !poolFirst(p, picked) && (await ownGpuOnline(account.id))) return null;
+ if (account && hasGpu && wish !== "pool" && !poolFirst(p, picked, account.id) && (await ownGpuOnline(account.id))) return null;
if (p && !p.hosted) return null;
const gate = toolGate(p, account?.id ?? null, steps);
if (gate === "unplanned") return null;
- const lineOf = (endpoint: string | undefined, q?: Quote): PoolLine => {
- const facts = queueFacts(account?.id ?? null, endpoint);
- return { place: Math.max(0, facts.ahead) + 1, etaSeconds: q?.etaS ?? facts.etaS ?? null };
- };
if (!gate.ok) {
if (hasGpu && wish !== "pool") return null;
- return { quote: gateQuote(gate, !account, placeFor(p)), line: lineOf(undefined) };
+ return { quote: gateQuote(gate, !account, placeFor(p)), line: poolLine(queueFacts(account?.id ?? null, undefined), { light: false, waits: false, p }) };
}
- const endpoint = gate.main.planned.route.endpoint;
- if (lightRun(gate.rows)) return { quote: FREE_QUOTE, line: lineOf(endpoint) };
const { req, planned } = gate.main;
+ const queue = queueFacts(account?.id ?? null, planned.route.endpoint);
+ const shape = { light: lightRun(gate.rows), waits: runWaits(planned, gate.rows), p };
+ if (shape.light) return { quote: FREE_QUOTE, line: poolLine(queue, shape) };
const facts = { ...runOnPool(account?.id ?? null, () => runFacts(req, planned, outputKind(planned.op, planned.model))), steps: pricedSteps(gate.rows) };
- let q = await billingQuote(account ? accountFacts(account) : null, facts, queueFacts(account?.id ?? null, endpoint));
+ let q = await billingQuote(account ? accountFacts(account) : null, facts, queue);
if (q.allowed && account && p) {
const over = poolLimitRefusal(account.id, p, o.addr ?? null);
if (over) q = { ...q, allowed: false, code: "limit", text: over.error };
}
- return { quote: q, line: lineOf(endpoint, q) };
+ return { quote: q, line: poolLine(queue, { ...shape, q }) };
}
/**
@@ -881,5 +919,5 @@ export function poolMayTake(account: Account | null, wish: PlaceWish): boolean {
if (!hostedRunsOn() || wish === "own" || !poolReady()) return false;
const picked = pickedPlace(account, wish);
if (picked === "own") return false;
- return !account || !accountGpu(account.id) || wish === "pool" || poolFirst(cachedPolicy(account.id), picked);
+ return !account || !accountGpu(account.id) || wish === "pool" || poolFirst(cachedPolicy(account.id), picked, account.id);
}
diff --git a/src/server/hosted.ts b/src/server/hosted.ts
index 57935278..55d03492 100644
--- a/src/server/hosted.ts
+++ b/src/server/hosted.ts
@@ -4,9 +4,9 @@ import { computeDimensions, fitCanvas } from "@/lib/comfy";
import { h3Canvas, isH3Graph } from "@/lib/h3-prompt";
import { imageSize } from "@/lib/image-size";
import type { GenerationRequest } from "@/lib/catalog/types";
-import { placeOf, type Place } from "@/lib/place-name";
+import type { Place } from "@/lib/place-name";
import { billingConfigured, type Policy, type QueueFacts, type RunFacts } from "./billing";
-import { lineFacts, poolLane, queueOfGeneration, workersAway, workersCanRun } from "./computer/pool";
+import { lineFacts, poolLane, queueOfGeneration, workersAway, workersCanRun, type LinePlace } from "./computer/pool";
import { db } from "./db";
import { loadIndex } from "./gpu/index-file";
import { hostedRunsOn } from "./hosted-switch";
@@ -87,8 +87,8 @@ export function poolTakes(endpoint: string | undefined): boolean {
/**
* Are this install's GPUs all away for this endpoint now (on the workers: every worker that could run it paused, silent or
- * outside its hours)? Then a run waits for nothing: the price check says "Starting soon" (Run is off), and a press of
- * Run makes nothing. On this install's own ComfyUI: never.
+ * outside its hours)? A run made then waits in line until one is back: the price check says it starts when a GPU is
+ * free (hosted-run.ts runWaits), and Run stays on. On this install's own ComfyUI: never.
*/
export function poolAway(endpoint: string | undefined): boolean {
if (!endpoint || !poolOnWorkers()) return false;
@@ -153,9 +153,6 @@ export function hostedWords(place: Place) {
inputs: "This kind of file runs on your own GPU. Connect one in Settings, or use a picture.",
rtxCard: "This one needs an NVIDIA RTX card. Connect your own RTX GPU in Settings, or pick another choice.",
notHosted: `Your account can't run on ${place.text} right now. Your own GPU or key still works.`,
- busy: "Busy right now. Try again in a little while.",
- /** Every GPU that could run it is off for now: Run opens again by itself once one is back. */
- startingSoon: "Starting soon",
};
}
@@ -165,7 +162,6 @@ export type HostedReason = keyof ReturnType<typeof hostedWords>;
/** The same refusals for a guest, who has no Settings to connect a GPU in yet (no place name in them). */
export function hostedGuestWords() {
return {
- busy: hostedWords(placeOf(null)).busy,
notOffered: "This one isn't offered here. Pick another model.",
rtxCard: "This one isn't offered here right now. Pick another choice.",
loras: "Extra LoRAs aren't offered here. Run without them.",
@@ -218,8 +214,12 @@ export const POOL_LANE = "comfyui";
/** The pool's rows that wait or run (the route's place-in-line facts). */
const POOL_ROWS = "json_extract(g.request_json, '$.place') = 'pool' AND g.status IN ('queued', 'running')";
-/** How long a run on this install's GPUs may wait in line: the billing service's limit, else FUOBE_POOL_WAIT_MIN (30). */
+/**
+ * How long a run on this install's GPUs may wait in line: the limit stamped on it (the policy's or the billing service's;
+ * 0: as long as it takes), else FUOBE_POOL_WAIT_MIN (30).
+ */
export function poolWaitMs(stamped?: number): number {
+ if (stamped === 0) return Infinity;
if (stamped && stamped > 0) return stamped;
const m = Number(process.env.FUOBE_POOL_WAIT_MIN);
return (Number.isFinite(m) && m > 0 ? m : 30) * 60_000;
@@ -272,7 +272,7 @@ export function queueFacts(accountId: string | null, workflowId?: string | null)
}
/** A waiting row's place in line on this install's GPUs (1: next), and the wait, about. Null when it isn't waiting there. */
-export function placeInLine(generationId: string): { place: number; etaSeconds: number | null } | null {
+export function placeInLine(generationId: string): LinePlace | null {
// On the workers: its task's place in their line (back in line after an attempt, the same place).
const task = queueOfGeneration(generationId);
if (task || poolOnWorkers()) return task;
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index afcd4347..10f70acd 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -283,7 +283,8 @@ export const POOL_NOT_LOCAL = "This install's ComfyUI address isn't on this mach
* Where an account's job waits in line on the workers, in its run's class (paid before free). Its run's first job: at
* the time it came (with the billing service's head start), with the run's wait limit. A later job of the same run (a
* chain's next step, sent once the steps before it are done): at the run's place (pool.ts runPlaceOf), and with no wait
- * limit once a worker took any of the run's jobs (the wait limit applies only before the run's first start).
+ * limit (the run was taken in line once; the wait limit applies only before its first start). The run's wait limit is
+ * the one stamped on it (0: as long as it takes), else the install's own (FUOBE_POOL_WAIT_MIN).
*/
function accountPoolFields(workflowId: string, account: string, generationId: string | undefined, o: { size: NonNullable<Parameters<typeof poolFields>[1]>["size"]; catalogVersion?: string }) {
const stamp = runStamp();
@@ -293,7 +294,7 @@ function accountPoolFields(workflowId: string, account: string, generationId: st
class: stamp?.class ?? "free",
boostMs: stamp?.boostMs,
...(run?.rankAt != null && { rankAt: run.rankAt }),
- waitMs: run?.started ? undefined : stamp?.waitMs || poolWaitMs(),
+ waitMs: run?.started || run?.later ? undefined : (stamp?.waitMs ?? poolWaitMs()),
size: o.size,
catalogVersion: o.catalogVersion,
});
diff --git a/src/server/run-stamp.ts b/src/server/run-stamp.ts
index f8ee703a..44fa2b47 100644
--- a/src/server/run-stamp.ts
+++ b/src/server/run-stamp.ts
@@ -23,7 +23,10 @@ export interface RunStamp {
charge?: string;
charged?: boolean;
checkOutputs?: boolean;
- /** How long it may wait in line on this install's GPUs (ms), from the billing service. */
+ /**
+ * How long it may wait in line on this install's GPUs before it first starts (ms), from the billing service. 0: as long
+ * as it takes (no wait limit). Absent: the install's own limit (FUOBE_POOL_WAIT_MIN).
+ */
waitMs?: number;
/** Its class in the line on this install's GPUs, from the billing service (none: "free"). */
class?: "paid" | "free";
@@ -61,13 +64,16 @@ export function stamped(req: GenerationRequest): GenerationRequest {
...(s.charge && { charge: s.charge }),
...(s.charged && { charged: true }),
...(s.checkOutputs && { checkOutputs: true }),
- ...(s.waitMs && s.waitMs > 0 && { waitMs: s.waitMs }),
+ ...(waitOf(s.waitMs) !== undefined && { waitMs: s.waitMs }),
...(s.class === "paid" && { class: "paid" as const }),
...(s.boostMs && s.boostMs > 0 && { boostMs: s.boostMs }),
...(s.light && { light: true }),
};
}
+/** A stamped wait limit as kept (0: no limit), or undefined for none at all (the install's own limit applies). */
+const waitOf = (ms: unknown): number | undefined => (typeof ms === "number" && Number.isFinite(ms) && ms >= 0 ? ms : undefined);
+
/** A stored request's stamp, to run a later step of it (advanceDependents, polls) as it was decided. */
export function stampOf(req: Pick<GenerationRequest, (typeof STAMP_FIELDS)[number]>): RunStamp {
return {
@@ -76,7 +82,7 @@ export function stampOf(req: Pick<GenerationRequest, (typeof STAMP_FIELDS)[numbe
...(req.charge && { charge: req.charge }),
...(req.charged && { charged: true }),
...(req.checkOutputs && { checkOutputs: true }),
- ...(req.waitMs && { waitMs: req.waitMs }),
+ ...(waitOf(req.waitMs) !== undefined && { waitMs: req.waitMs }),
...(req.class === "paid" && { class: "paid" as const }),
...(req.boostMs && req.boostMs > 0 && { boostMs: req.boostMs }),
...(req.light && { light: true }),
diff --git a/tests/helpers/run-watch.ts b/tests/helpers/run-watch.ts
index 1eb24665..629f7bcb 100644
--- a/tests/helpers/run-watch.ts
+++ b/tests/helpers/run-watch.ts
@@ -14,7 +14,7 @@ export interface RunLike {
message?: string | null;
error?: string | null;
progress?: number | null;
- queue?: { place: number; etaSeconds: number | null } | null;
+ queue?: { place: number; etaSeconds: number | null; unknown?: true } | null;
outputs?: unknown[];
notCharged?: boolean;
fix?: unknown;
@@ -93,7 +93,7 @@ export class RunWatch {
if (!["queued", "running", "succeeded"].includes(s.status)) out.push(`a state that isn't In line, Working or the result (${at})`);
if (s.status === "queued" && s.message !== POOL_WORDS.inLine) out.push(`a waiting run that doesn't say In line (${at})`);
if (s.status === "queued" && s.place === null) out.push(`a waiting run with no place in line (${at})`);
- if (s.status === "running" && s.message !== POOL_WORDS.working) out.push(`a started run that doesn't say Working (${at})`);
+ if (s.status === "running" && s.message !== POOL_WORDS.working && s.message !== POOL_WORDS.gettingReady) out.push(`a started run that doesn't say Working (${at})`);
if (s.status === "succeeded" && s.outputs < 1) out.push(`a result with nothing in it (${at})`);
if (s.error) out.push(`an error (${at})`);
for (const w of [s.message, s.error]) if (w && MACHINE_WORDS.test(w)) out.push(`words about the machines (${at})`);
diff --git a/tests/hosted-quote-refresh.test.ts b/tests/hosted-quote-refresh.test.ts
index 8695d98f..b4d4084a 100644
--- a/tests/hosted-quote-refresh.test.ts
+++ b/tests/hosted-quote-refresh.test.ts
@@ -47,7 +47,7 @@ describe("the price check asks again by itself", () => {
// Both runs finish; nothing about the draft changes: the check is asked again, and Run is on.
await vi.advanceTimersByTimeAsync(15_000);
expect(sent).toEqual([body, body]);
- expect(poolRunState(observer.getCurrentResult().data)).toMatchObject({ refused: false, text: "Free", wait: "In line · 2nd · about 40 s" });
+ expect(poolRunState(observer.getCurrentResult().data)).toMatchObject({ refused: false, text: "Free", wait: "ready in about 40 s" });
// A run starts or ends: asked again at once, not only on the next tick.
refreshPriceChecks(qc);
await vi.advanceTimersByTimeAsync(0);
diff --git a/tests/hosted-run-button.test.ts b/tests/hosted-run-button.test.ts
index e2c906f5..5f451c60 100644
--- a/tests/hosted-run-button.test.ts
+++ b/tests/hosted-run-button.test.ts
@@ -18,20 +18,36 @@ const { lineWords } = await import("@/lib/pool-line");
const { poolRunState } = await import("@/lib/hosted");
const { checkedPool, runPlace } = await import("@/lib/run-place");
const { PoolNote } = await import("@/components/studio/pool-note");
+const { waitWords } = await import("@/lib/pool-line");
const { TooltipProvider } = await import("@/components/ui/tooltip");
const render = (node: ReactNode) => renderToStaticMarkup(createElement(QueryClientProvider, { client: new QueryClient() }, createElement(TooltipProvider, null, node)));
describe("the words for a place in line", () => {
- it("says next, or the place, with the wait about", () => {
+ it("says next, or the place, with when it would be ready", () => {
expect(lineWords({ place: 1, etaSeconds: null })).toBe("Next in line");
- expect(lineWords({ place: 1, etaSeconds: 38 })).toBe("Next in line · about 40 s");
- expect(lineWords({ place: 3, etaSeconds: 130 })).toBe("In line · 3rd · about 2 min");
+ expect(lineWords({ place: 1, etaSeconds: 38 })).toBe("Next in line · ready in about 40 s");
+ expect(lineWords({ place: 3, etaSeconds: 130 })).toBe("In line · 3rd · ready in about 2 min");
expect(lineWords({ place: 12, etaSeconds: null })).toBe("In line · 12th");
- expect(lineWords({ place: 22, etaSeconds: 3 })).toBe("In line · 22nd · about 5 s");
+ expect(lineWords({ place: 22, etaSeconds: 3 })).toBe("In line · 22nd · ready in about 5 s");
+ expect(lineWords({ place: 2, etaSeconds: 3 * 3600 })).toBe("In line · 2nd · ready in about 3 h");
// Never a place before the first, nor a wait that can't be.
expect(lineWords({ place: 0, etaSeconds: -5 })).toBe("Next in line");
});
+ it("no GPU can take it now: it starts when one is free, or when the first is due back", () => {
+ const now = 1_000_000_000_000;
+ expect(lineWords({ place: 3, etaSeconds: null, unknown: true }, now)).toBe("In line · 3rd · starts when a GPU is free");
+ expect(lineWords({ place: 1, etaSeconds: null, unknown: true, returnAt: now + 3 * 3600_000 }, now)).toBe("Next in line · starts in about 3 h");
+ // A return time already past says nothing it can't keep.
+ expect(lineWords({ place: 1, etaSeconds: null, unknown: true, returnAt: now - 1000 }, now)).toBe("Next in line · starts when a GPU is free");
+ });
+ it("before Run: when the result would be ready, and nothing when nothing is known", () => {
+ expect(waitWords({ place: 3, etaSeconds: 130 })).toBe("ready in about 2 min");
+ expect(waitWords({ place: 1, etaSeconds: 40 })).toBe("ready in about 40 s");
+ expect(waitWords({ place: 4, etaSeconds: null, unknown: true })).toBe("starts when a GPU is free");
+ expect(waitWords({ place: 1, etaSeconds: null, light: true })).toBe("ready in seconds");
+ expect(waitWords({ place: 1, etaSeconds: null })).toBeNull();
+ });
});
describe("Run before it is pressed (the price check's answer)", () => {
@@ -39,10 +55,17 @@ describe("Run before it is pressed (the price check's answer)", () => {
expect(poolRunState({ place: "pool", quote: { allowed: true, amount: 0, priceVersion: "v1", text: "Free" }, line: { place: 2, etaSeconds: 90 } })).toEqual({
refused: false,
text: "Free",
- wait: "In line · 2nd · about 2 min",
+ wait: "ready in about 2 min",
+ });
+ // No service: no words of its own (Run keeps its own); nothing known of the wait, nothing said.
+ expect(poolRunState({ place: "pool", quote: { allowed: true, amount: 0, priceVersion: "", text: "" }, line: { place: 1, etaSeconds: null } })).toEqual({ refused: false, text: "" });
+ // Every GPU away: Run stays on, the line says it starts when one is free, and the wait is long.
+ expect(poolRunState({ place: "pool", quote: { allowed: true, amount: 0, priceVersion: "", text: "Free" }, line: { place: 2, etaSeconds: null, unknown: true, long: true } })).toEqual({
+ refused: false,
+ text: "Free",
+ wait: "starts when a GPU is free",
+ long: true,
});
- // No service: no words of its own (Run keeps its own), still the place.
- expect(poolRunState({ place: "pool", quote: { allowed: true, amount: 0, priceVersion: "", text: "" }, line: { place: 1, etaSeconds: null } })).toEqual({ refused: false, text: "", wait: "Next in line" });
});
it("refused (busy, a limit, not offered, paused, a top-up): Run is off, with the words, the line under them and the link", () => {
for (const code of ["busy", "limit", "not-offered", "closed", "paused", "top-up"]) {
@@ -62,16 +85,22 @@ describe("Run before it is pressed (the price check's answer)", () => {
expect(off).toMatchObject({ where: "pool", refused: "You have 2 runs going. Start this one when one finishes.", send: "You have 2 runs going. Start this one when one finishes." });
expect(off.needs).toBeUndefined();
const ok = checkedPool({ place: "pool", quote: { allowed: true, text: "Free" }, line: { place: 1, etaSeconds: 40 } });
- expect(ok).toEqual({ text: "Free", wait: "Next in line · about 40 s" });
+ expect(ok).toEqual({ text: "Free", wait: "ready in about 40 s" });
const on = runPlace({ audience: "account", engine: "open", hosted: true, models: ["Qwen Image"], pool: ok, format: String });
expect(on.refused).toBeUndefined();
- expect(on.tip).toBe("Runs on our GPUs with Qwen Image. Next in line · about 40 s.");
+ expect(on.tip).toBe("Runs on our GPUs with Qwen Image. Ready in about 40 s.");
});
it("the line under the toolbar: the wait before Run, or the refusal's words with its link and offer", () => {
- const wait = render(createElement(PoolNote, { state: { refused: false, text: "Free", wait: "Next in line · about 40 s" } }));
+ const wait = render(createElement(PoolNote, { state: { refused: false, text: "Free", wait: "ready in about 40 s" } }));
expect(wait).toContain('data-pool-note="wait"');
- expect(wait).toContain("Next in line · about 40 s");
+ expect(wait).toContain("Ready in about 40 s");
expect(render(createElement(PoolNote, { state: { refused: false, text: "Free" } }))).toBe("");
+ // A long wait: the account's own GPU (or key, with its price) for this run, once; never on a short one.
+ const offer = { label: "Run it now on your GPU", run: () => {} };
+ const long = render(createElement(PoolNote, { state: { refused: false, text: "Free", wait: "starts when a GPU is free", long: true }, offer }));
+ expect(long).toContain("Starts when a GPU is free");
+ expect(long).toContain("Run it now on your GPU");
+ expect(render(createElement(PoolNote, { state: { refused: false, text: "Free", wait: "ready in about 40 s" }, offer }))).not.toContain("Run it now");
const refused = render(
createElement(PoolNote, { state: { refused: true, text: "Busy right now. Try again in about 10 min.", action: { label: "Get more", url: "javascript:alert(1)" }, offer: { key: "priority", text: "Skip the line", label: "Tell me when" } } }),
);
diff --git a/tests/hosted-run-tiles.test.ts b/tests/hosted-run-tiles.test.ts
index 1b16dee8..81524aae 100644
--- a/tests/hosted-run-tiles.test.ts
+++ b/tests/hosted-run-tiles.test.ts
@@ -54,10 +54,20 @@ describe("a run's tile on this studio's GPUs", () => {
it("in line: its place and wait, no progress (after a recovery too, whatever an earlier attempt reached)", () => {
const html = render(createElement(PendingTile, { g: gen({ place: "pool", status: "queued", message: POOL_WORDS.inLine, progress: 0.6, queue: { place: 3, etaSeconds: 130 } }), ratio: 1 }));
expect(html).toContain('data-run-state="in-line"');
- expect(html).toContain("In line · 3rd · about 2 min");
+ expect(html).toContain("In line · 3rd · ready in about 2 min");
expect(html).not.toContain("60%");
expect(html).not.toContain("scaleX");
});
+ it("in line while no GPU can take it now: its place, and it starts when one is free", () => {
+ const html = render(createElement(PendingTile, { g: gen({ place: "pool", status: "queued", message: POOL_WORDS.inLine, queue: { place: 3, etaSeconds: null, unknown: true } }), ratio: 1 }));
+ expect(html).toContain("In line · 3rd · starts when a GPU is free");
+ });
+ it("working while its model loads: Working · getting ready, with no %", () => {
+ const html = render(createElement(PendingTile, { g: gen({ place: "pool", status: "running", message: POOL_WORDS.gettingReady, progress: null }), ratio: 1 }));
+ expect(html).toContain('data-run-state="working"');
+ expect(html).toContain("Working · getting ready");
+ expect(html).not.toContain("%");
+ });
it("in line with no place known yet: In line", () => {
const html = render(createElement(PendingTile, { g: gen({ place: "pool", status: "queued", message: POOL_WORDS.inLine }), ratio: 1 }));
expect(html).toContain(">In line<");
diff --git a/tests/hosted-words.test.ts b/tests/hosted-words.test.ts
index 4732f390..345d1b11 100644
--- a/tests/hosted-words.test.ts
+++ b/tests/hosted-words.test.ts
@@ -109,7 +109,7 @@ afterEach(() => notePlaceName(null));
/** Every sentence a visitor reads from the server's word tables, for a place. */
function serverWords(place: ReturnType<typeof placeOf>): string[] {
- const reasons = ["notOffered", "rtxCard", "loras", "inputs", "busy"] as const;
+ const reasons = ["notOffered", "rtxCard", "loras", "inputs"] as const;
return [
...Object.values(hostedWords(place)),
...Object.values(hostedGuestWords()),
@@ -129,7 +129,7 @@ function serverWords(place: ReturnType<typeof placeOf>): string[] {
function chipWords(place: ReturnType<typeof placeOf>): string[] {
const out: string[] = [];
for (const audience of ["account", "guest"] as const)
- for (const pool of [undefined, { text: "" }, { text: "1 generation", wait: "Next in line · about 40 s" }, { text: "You have 2 runs going.", refused: true }])
+ for (const pool of [undefined, { text: "" }, { text: "1 generation", wait: "ready in about 40 s" }, { text: "Free", wait: "starts when a GPU is free" }, { text: "You have 2 runs going.", refused: true }])
for (const p of [runPlace({ audience, engine: "open", hosted: true, models: ["Z-Image Turbo"], pool, place, format: String })]) out.push(p.label, p.price, p.title, p.tip, p.send);
return out.filter(Boolean);
}
@@ -196,7 +196,7 @@ describe("the pages a visitor reads while hosted runs are on", () => {
render(createElement(StatusCover, { g: gen({ status: "running", message: POOL_WORDS.working, progress: 0.4 }) })),
render(createElement(StatusCover, { g: gen({ status: "failed", error: POOL_WORDS.failed }) })),
].map(textOf);
- expect(pages[3]).toContain("In line · 3rd · about 2 min");
+ expect(pages[3]).toContain("In line · 3rd · ready in about 2 min");
expect(pages[4]).toContain("Working");
expect(pages[5]).toContain("Sorry, this one couldn't be made.");
expect(pages[5]).not.toContain("Couldn't generate this one");
@@ -241,7 +241,7 @@ describe("where runs go: the Run on list, Settings and the one-time note", () =>
for (const place of [NAMED, DEFAULT]) {
const viewer = { kind: "account" as const, hosted: true, prefer: "pool" as const, placeName: place.label, gpu };
const rows = [
- ...placeRows(viewer, { key: { provider: "fal", price: "≈ $0.04" } }, { text: "Free", wait: "Next in line · about 40 s" })!.rows,
+ ...placeRows(viewer, { key: { provider: "fal", price: "≈ $0.04" } }, { text: "Free", wait: "ready in about 40 s" })!.rows,
...placeRows({ ...viewer, runOn: "gpu", gpu: { connected: true, online: false } }, { key: { provider: "replicate" } })!.rows,
].flatMap((r) => [r.label, r.sub]);
const note = placeRows({ ...viewer, runOn: "key" }, { key: null })!.note!;
diff --git a/tests/pool-limits.test.ts b/tests/pool-limits.test.ts
index 7a7bd9bf..612bc86b 100644
--- a/tests/pool-limits.test.ts
+++ b/tests/pool-limits.test.ts
@@ -505,6 +505,60 @@ describe("where a run goes", () => {
expect(lora.quote).toBeUndefined();
});
+ it("A17: with this install's GPUs first, a run keeps waiting for them while every one is away, behind an update, or the service is quiet: never moved to the account's own GPU", async () => {
+ withBilling({ prefer: "pool", limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const a = account({ gpu: "online" });
+ const acct = auth.accountById(a.id)!;
+ const req = { ...IMAGE, account: a.id } as never;
+ // Every worker here paused: taken on this install's GPUs; the line says it starts when one is free, and is long enough
+ // to offer the account's own GPU for that run (the composer's "Run it now on your GPU").
+ pool.patchWorker(worker.id, { paused: true });
+ expect((await hostedRun.decidePlace(acct, req, undefined)).kind).toBe("pool");
+ const away = await hostedRun.poolQuote(acct, req, undefined);
+ expect(away?.quote.allowed).toBe(true);
+ expect(away?.line).toMatchObject({ unknown: true, long: true });
+ const r = await post({ ...IMAGE, ...SHOWN }, a.cookie);
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ expect(r.body.items![0].place).toBe("pool");
+ expect(ownRuns(a.id)).toBe(0);
+ pool.patchWorker(worker.id, { paused: false });
+ beatWith(worker, catalogVersion());
+ // A short line offers nothing.
+ expect((await hostedRun.poolQuote(acct, req, undefined))?.line.long).toBeUndefined();
+ // Behind a catalog update: the same.
+ beatWith(worker, "e".repeat(64));
+ expect((await hostedRun.decidePlace(acct, req, undefined)).kind).toBe("pool");
+ expect((await hostedRun.poolQuote(acct, req, undefined))?.line).toMatchObject({ unknown: true });
+ beatWith(worker, catalogVersion());
+ // The service goes quiet for longer than its last answer stands: the run waits for it, never sent to the own GPU.
+ fake.down = "error";
+ try {
+ const kept = globalThis.__fuobeBillingPolicies!.get(a.id)!;
+ kept.at = 0;
+ kept.goodAt = Date.now() - billing.POLICY_KEEP_MS - 1000;
+ const quiet = await hostedRun.decidePlace(acct, req, undefined);
+ expect(quiet.kind).toBe("refuse");
+ expect(quiet.kind === "refuse" && quiet.refusal.body.code).toBe("paused");
+ expect((await hostedRun.decideToolPlace(acct, [{ request: req }], undefined)).kind).toBe("refuse");
+ } finally {
+ fake.down = false;
+ }
+ // A policy that puts the account's own GPU first keeps today's way while the service is quiet: its own GPU.
+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
+ const b = account({ gpu: "online" });
+ const bAcct = auth.accountById(b.id)!;
+ await hostedRun.poolQuote(bAcct, { ...IMAGE, account: b.id } as never, undefined);
+ fake.down = "error";
+ try {
+ const kept = globalThis.__fuobeBillingPolicies!.get(b.id)!;
+ kept.at = 0;
+ kept.goodAt = Date.now() - billing.POLICY_KEEP_MS - 1000;
+ expect((await hostedRun.decidePlace(bAcct, { ...IMAGE, account: b.id } as never, undefined)).kind).toBe("own");
+ } finally {
+ fake.down = false;
+ }
+ });
+
it("an own GPU that doesn't answer: a run that named no place is asked about, never moved and charged", async () => {
withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });
const a = account({ gpu: "offline" });
@@ -886,7 +940,7 @@ describe("the price check before Run and the run itself", async () => {
expect((await hostedRun.poolQuote(acct, req, undefined))?.quote).toMatchObject({ allowed: false, text: OWN_GPU_TOOL_MESSAGE });
});
- it("while every worker that could run it is built from the catalog before the studio's update, Run is off with plain words, never a run that waits for nothing", async () => {
+ it("while every worker that could run it is built from the catalog before the studio's update, the run is taken and waits in line until one is updated; Run stays on", async () => {
const a = account();
const acct = auth.accountById(a.id)!;
withBilling({ limits: NO_LIMITS });
@@ -897,15 +951,15 @@ describe("the price check before Run and the run itself", async () => {
expect(hosted.queueFacts(a.id, endpoint).workersOnline).toBe(1);
// The studio was updated; its only worker not yet.
beatWith(worker, "e".repeat(64));
- const before = db().prepare("SELECT COUNT(*) FROM generations").pluck().get();
const run = await hostedRun.decidePlace(acct, req, undefined);
- expect(run.kind).toBe("refuse");
- expect(run.kind === "refuse" && run.refusal).toMatchObject({ status: 503, body: { code: "busy", error: HOSTED_WORDS.busy } });
- expect((await hostedRun.poolQuote(acct, req, undefined))?.quote).toMatchObject({ allowed: false, code: "busy", text: HOSTED_WORDS.busy });
- expect((await hostedRun.poolQuote(null, IMAGE as never, undefined))?.quote).toMatchObject({ allowed: false, text: HOSTED_GUEST_WORDS.busy });
+ expect(run.kind).toBe("pool");
+ // The price check lets it run, and says it starts when a GPU is free (for a guest too).
+ const q = await hostedRun.poolQuote(acct, req, undefined);
+ expect(q?.quote.allowed).toBe(true);
+ expect(q?.line).toMatchObject({ unknown: true, long: true });
+ expect((await hostedRun.poolQuote(null, IMAGE as never, undefined))?.line).toMatchObject({ unknown: true });
// Its place in line and the workers there count only a worker that takes the run now.
expect(hosted.queueFacts(a.id, endpoint).workersOnline).toBe(0);
- expect(db().prepare("SELECT COUNT(*) FROM generations").pluck().get()).toBe(before);
// The owner's own jobs still go to it: a worker built from another catalog takes those.
expect(pool.workersCanRun(endpoint)).toBe(true);
// Updated: Run is on again.
diff --git a/tests/pool-line-order.test.ts b/tests/pool-line-order.test.ts
index a86c73aa..885740a4 100644
--- a/tests/pool-line-order.test.ts
+++ b/tests/pool-line-order.test.ts
@@ -316,7 +316,7 @@ describe("a run's later steps keep the run's place", () => {
expect(served(w)).toEqual([two.id, ...line]);
});
- it("a step sent before any job of its run was taken keeps the run's place and still has the run's wait limit", async () => {
+ it("a step sent before any job of its run was taken keeps the run's place and has no wait limit: it never fails for a wait", async () => {
standInWorker();
const wait = 5 * MIN;
const first = runRow({ batch: "chain-b" });
@@ -324,12 +324,12 @@ describe("a run's later steps keep the run's place", () => {
const two = await sendStep(runRow({ batch: "chain-b", dependsOn: first }), { waitMs: wait });
expect(two.rank_at).toBe(one.rank_at);
expect(two.class).toBe("free");
- expect(two.not_after).not.toBeNull();
- pool.sweepPool(Date.now() + 2 * wait);
- expect(rowOf(two.id).state).toBe("failed");
+ expect(two.not_after).toBeNull();
+ pool.sweepPool(Date.now() + 4 * wait);
+ expect(rowOf(two.id).state).toBe("waiting");
});
- it("a later step with no job of its run on the workers yet waits from the time its run was made", async () => {
+ it("a later step with no job of its run on the workers yet waits from the time its run was made, with no wait limit", async () => {
standInWorker();
const wait = 5 * MIN;
const first = runRow({ batch: "chain-c" });
@@ -339,7 +339,75 @@ describe("a run's later steps keep the run's place", () => {
const two = await sendStep(step, { waitMs: wait });
const made = (db().prepare("SELECT created_at FROM generations WHERE id = ?").get(step) as { created_at: number }).created_at;
expect(two.rank_at).toBe(made);
- expect(two.not_after).not.toBeNull();
+ expect(two.not_after).toBeNull();
+ });
+
+ it("A5: a 3-step chain under load: each later step ranks with step 1, ahead of runs sent after it, and nothing fails after 20 minutes", async () => {
+ const w = standInWorker();
+ const wait = 5 * MIN;
+ const first = runRow({ batch: "chain-e" });
+ const one = await sendStep(first, { waitMs: wait });
+ beatAs(w);
+ expect(claimAs(w)?.id).toBe(one.id);
+ done(one.id);
+ const line = [lineTask({ account: other }), lineTask({ account: other }), lineTask({ account: other })];
+ const second = runRow({ batch: "chain-e", dependsOn: first });
+ const two = await sendStep(second, { waitMs: wait });
+ const three = await sendStep(runRow({ batch: "chain-e", dependsOn: second }), { waitMs: wait });
+ for (const t of [two, three]) {
+ expect(t.rank_at).toBe(one.rank_at);
+ expect(t.not_after).toBeNull();
+ }
+ pool.sweepPool(Date.now() + 20 * MIN);
+ expect([rowOf(two.id).state, rowOf(three.id).state]).toEqual(["waiting", "waiting"]);
+ expect(served(w).slice(0, 2).sort()).toEqual([two.id, three.id].sort());
+ expect(served(w)).toEqual([]);
+ for (const id of line) expect(rowOf(id).state).toBe("done");
+ });
+
+ it("a run's first job: the policy's wait limit wins over the reserve's (0: none at all), and with none the reserve's stands", async () => {
+ standInWorker();
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ const press = async (prompt: string) => {
+ const r = await generationsRoute.POST(
+ new Request(`http://${HOST}/api/generations`, {
+ method: "POST",
+ headers: { ...SITE_HEADERS, cookie, "content-type": "application/json" },
+ body: JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt, shown: { amount: 7, priceVersion: "v7" } }),
+ }),
+ );
+ const body = (await r.json()) as { items?: { id: string }[] };
+ expect(r.status, JSON.stringify(body)).toBe(201);
+ const id = body.items![0].id;
+ let t = taskOf(id);
+ for (let i = 0; i < 100 && !t; i++) {
+ await globalThis.__fuobeRunner?.tick();
+ await new Promise((res) => setTimeout(res, 20));
+ t = taskOf(id);
+ }
+ return { id, t: t! };
+ };
+ const limits = (fake.policy as { limits: Record<string, number> }).limits;
+ // No word from the policy: the reserve answer's (700 s in the stand-in service).
+ fake.policy = { ...fake.policy, hosted: true, ttlS: 0, limits: { ...limits } };
+ const a = await press("the reserve's wait");
+ expect(a.t.not_after! - a.t.created_at).toBeGreaterThanOrEqual(700_000 - 1000);
+ expect(a.t.not_after! - a.t.created_at).toBeLessThanOrEqual(700_000 + 1000);
+ // giveUpS 0: as long as it takes. No wait limit on its task, and the stored run says so for its later steps.
+ fake.policy = { ...fake.policy, hosted: true, ttlS: 0, limits: { ...limits, giveUpS: 0 } };
+ const b = await press("no wait limit");
+ expect(b.t.not_after).toBeNull();
+ const stored = JSON.parse((db().prepare("SELECT request_json FROM generations WHERE id = ?").get(b.id) as { request_json: string }).request_json) as Record<string, unknown>;
+ expect(stored.waitMs).toBe(0);
+ expect((getGeneration(b.id) as unknown as { request?: Record<string, unknown> }).request?.waitMs).toBeUndefined();
+ pool.sweepPool(Date.now() + 10 * 3600_000);
+ expect(rowOf(b.t.id).state).toBe("waiting");
+ // giveUpS 600: ten minutes, whatever the reserve said.
+ fake.policy = { ...fake.policy, hosted: true, ttlS: 0, limits: { ...limits, giveUpS: 600 } };
+ const c = await press("ten minutes");
+ expect(c.t.not_after! - c.t.created_at).toBeGreaterThanOrEqual(600_000 - 1000);
+ expect(c.t.not_after! - c.t.created_at).toBeLessThanOrEqual(600_000 + 1000);
});
it("a step that uses a result kept from an earlier run waits as a new run: its own place, and the wait limit", async () => {
@@ -507,7 +575,34 @@ describe("the run ceiling", () => {
await tick();
const g = getGeneration(id)!;
expect(g.status).toBe("running");
- expect(g.message).toBe(POOL_WORDS.working);
+ // Taken afresh by a worker whose beats name no model loaded: Working, getting ready (no progress of the attempt before).
+ expect(g.message).toBe(POOL_WORDS.gettingReady);
+ expect(g.progress).toBeNull();
+ });
+
+ it("a worker with another model loaded: Working · getting ready until the first step reports; with its model loaded, Working at once", async () => {
+ const w = standInWorker();
+ const { id, t } = await accountRun("getting ready");
+ const lane = rowOf(t.id).lane!;
+ const beatWarm = (warmLane: string | null) =>
+ pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 3, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: catalogVersion(), warmLane }), Date.now());
+ beatWarm("another-lane");
+ const first = claimAs(w)!;
+ expect(first.id).toBe(t.id);
+ tasks.report(rowOf(t.id), { event: "sent", promptId: first.promptId }, () => ({ error: "unused" }));
+ await tick();
+ expect(getGeneration(id)).toMatchObject({ status: "running", message: POOL_WORDS.gettingReady, progress: null });
+ // Its first step: the model is loaded.
+ tasks.report(rowOf(t.id), { event: "running", value: 1, max: 4 }, () => ({ error: "unused" }));
+ await tick();
+ expect(getGeneration(id)?.message).toBe(POOL_WORDS.working);
+ // Given back, and taken by a worker that has its model loaded: Working, with no getting ready.
+ tasks.report(rowOf(t.id), { event: "give-back", why: "stalled" }, () => ({ error: "unused" }));
+ beatWarm(lane);
+ expect(claimAs(w)?.id).toBe(t.id);
+ tasks.report(rowOf(t.id), { event: "sent", promptId: first.promptId }, () => ({ error: "unused" }));
+ await tick();
+ expect(getGeneration(id)).toMatchObject({ status: "running", message: POOL_WORDS.working });
});
it("a poll that fails never ends a run in line by the runner's own wait, an account's or the owner's", async () => {
diff --git a/tests/recovery-server.test.ts b/tests/recovery-server.test.ts
index 2669f77b..d33ed435 100644
--- a/tests/recovery-server.test.ts
+++ b/tests/recovery-server.test.ts
@@ -73,8 +73,6 @@ const { loadIndex } = await import("@/server/gpu/index-file");
const { allLanes } = await import("@/lib/lanes");
const { getModel } = await import("@/lib/catalog");
const { POOL_WORDS } = await import("@/lib/relay");
-const { hostedWords } = await import("@/server/hosted");
-const HOSTED_WORDS = hostedWords((await import("@/lib/place-name")).placeOf(null));
const { ACCOUNT_MESSAGES } = await import("@/server/account-files");
type TaskRow = import("@/server/computer/tasks").TaskRow;
@@ -641,7 +639,10 @@ describe("a run's preview picture while it works", () => {
if (step === "claim" && !atClaim) atClaim = { ...taskOf(id)!, file: fs.existsSync(file) };
});
await workAll(d);
- expect(atClaim).toMatchObject({ progress_json: null, preview_at: null, file: false });
+ expect(atClaim).toMatchObject({ preview_at: null, file: false });
+ // Only the new attempt's own mark (getting ready: its worker said no model was loaded), no step of the attempt before.
+ const fresh = JSON.parse(atClaim!.progress_json ?? "{}") as Record<string, unknown>;
+ expect(Object.keys(fresh).filter((k) => k !== "at" && k !== "cold")).toEqual([]);
expect((await ended(id))?.status).toBe("succeeded");
});
@@ -1045,19 +1046,17 @@ describe("the worker steps aside for another program", () => {
expect(back.state).toBe("waiting");
expect(back.requeues, "a step aside costs no attempt").toBe(0);
// The game runs for 40 minutes, past the run's 20 minute wait limit. Near its end, another account presses Run: with
- // the only worker stepped aside, no run is made that would wait for nothing (the price check says it starts soon).
+ // the only worker stepped aside, its run is taken all the same and waits in line behind this one (the price check
+ // lets it run and says it starts when a GPU is free).
await pass(35 * MIN, [d], watch);
- const all = () => (db().prepare('SELECT COUNT(*) AS n FROM generations').get() as { n: number }).n;
- const rows = all();
- const holds = svc.holds.size;
+ const check = await priceCheck(IMAGE, b1);
+ expect(check.body.quote).toMatchObject({ allowed: true });
+ expect((check.body as { line?: unknown }).line).toMatchObject({ unknown: true });
const theirs = await run(IMAGE, b1);
- expect(theirs.status, JSON.stringify(theirs.body)).toBe(503);
- expect(theirs.body).toMatchObject({ error: billing.BILLING_WAIT.run, code: "busy" });
- expect((await priceCheck(IMAGE, b1)).body.quote).toMatchObject({ allowed: false, code: "busy", text: HOSTED_WORDS.startingSoon });
- expect(all()).toBe(rows);
- expect(svc.holds.size).toBe(holds);
+ expect(theirs.status, JSON.stringify(theirs.body)).toBe(201);
await pass(5 * MIN, [d], watch);
- expect(getGeneration(id)).toMatchObject({ status: "queued", message: POOL_WORDS.inLine, queue: { place: 1 } });
+ expect(getGeneration(id)).toMatchObject({ status: "queued", message: POOL_WORDS.inLine, queue: { place: 1, unknown: true } });
+ expect(getGeneration(theirs.body.items![0].id)).toMatchObject({ status: "queued", queue: { place: 2, unknown: true } });
// The game ends: it runs first, in its place, and settles against the hold it was given at Run.
const hold = holdOf(id);
d.pause(null);
@@ -1180,18 +1179,20 @@ describe("a run that can never succeed here", () => {
});
describe("no worker online", () => {
- it("with every worker paused, the price check says it starts soon, so Run is off", async () => {
+ it("with every worker paused, the price check lets the run go and says it starts when a GPU is free", async () => {
standInWorker("paused", { paused: true });
const q = await priceCheck(IMAGE);
expect(q.status, JSON.stringify(q.body)).toBe(200);
expect(q.body.place).toBe("pool");
- expect(q.body.quote).toMatchObject({ allowed: false, code: "busy", text: HOSTED_WORDS.startingSoon });
+ expect(q.body.quote).toMatchObject({ allowed: true, text: "Free" });
+ expect((q.body as { line?: unknown }).line).toMatchObject({ unknown: true, long: true });
// A guest is told the same.
const g = await priceCheck(IMAGE, "");
- expect(g.body.quote).toMatchObject({ allowed: false, code: "busy", text: HOSTED_WORDS.startingSoon });
+ expect(g.body.quote).toMatchObject({ allowed: true });
+ expect((g.body as { line?: unknown }).line).toMatchObject({ unknown: true });
});
- it("Run pressed while every worker is away makes no run that would wait for nothing, and promises no start; once one is back, Run works", async () => {
+ it("Run pressed while every worker is away is taken: In line, starts when one is back, and its result arrives", async () => {
const away = [
standInWorker("paused here", { connected: true }),
standInWorker("never connected", { connected: false }),
@@ -1203,20 +1204,34 @@ describe("no worker online", () => {
pool.patchWorker(away[3].id, { hours: { tz: "UTC", days: {} } });
const rows = made();
const holds = svc.holds.size;
- const r = await run(IMAGE);
- expect(r.status, JSON.stringify(r.body)).toBe(503);
- // Plain words that promise no start (no run was made), and no billing card: the price check, asked again, says
- // "Starting soon" with Run off.
- expect(r.body).toEqual({ error: billing.BILLING_WAIT.run, code: "busy" });
- expect(r.headers.get("x-fuobe-billing")).toBeNull();
- expect((await priceCheck(IMAGE)).body.quote).toMatchObject({ allowed: false, code: "busy", text: HOSTED_WORDS.startingSoon });
- expect(made()).toBe(rows);
- expect(svc.holds.size).toBe(holds);
- // The silent one beats again: Run is back on, and the run goes in line.
+ const { id } = await pressRun();
+ expect(made()).toBe(rows + 1);
+ expect(svc.holds.size).toBe(holds + 1);
+ expect(getGeneration(id)).toMatchObject({ status: "queued", message: POOL_WORDS.inLine, queue: { place: 1, unknown: true } });
+ // The silent one beats again: the line has an estimate again, and the run is next.
db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(Date.now(), away[2].id);
expect((await priceCheck(IMAGE)).body.quote).toMatchObject({ allowed: true, text: "Free" });
+ expect((getGeneration(id) as { queue?: { unknown?: boolean } }).queue?.unknown).toBeUndefined();
+ });
+
+ it("A1: every worker paused for 40 minutes under a policy that never gives up: the run waits In line, then its result arrives", async () => {
+ clock();
+ svc.policy = { ...svc.policy, limits: { ...(svc.policy.limits as Record<string, unknown>), giveUpS: 0 } };
+ const w = standInWorker();
+ const d = driver(w);
+ d.pause("here-now");
+ await d.beat();
const { id } = await pressRun();
- expect(getGeneration(id)).toMatchObject({ status: "queued", message: POOL_WORDS.inLine, queue: { place: 1 } });
+ const watch = watchOf(id);
+ // No wait limit on its task, whatever the reserve answer said.
+ expect(taskOf(id)!.not_after).toBeNull();
+ expect(getGeneration(id)).toMatchObject({ status: "queued", message: POOL_WORDS.inLine, queue: { place: 1, unknown: true } });
+ await pass(40 * MIN, [d], watch);
+ expect(getGeneration(id)).toMatchObject({ status: "queued", queue: { place: 1 } });
+ d.pause(null);
+ lookAtEveryStep(d, watch);
+ await workAll(d);
+ await expectOnce(id, watch, { place: 1 });
});
it("a worker making room for local work first is on: the run goes in line", async () => {
diff --git a/tests/run-place.test.ts b/tests/run-place.test.ts
index bac17aed..1ce4a1b7 100644
--- a/tests/run-place.test.ts
+++ b/tests/run-place.test.ts
@@ -3,7 +3,6 @@ import { placeOf } from "@/lib/place-name";
import { quoteBody } from "@/lib/hosted";
import { checkedPool, composerOnPool, composerPlace, IN_BROWSER, mainModel, offersRunOnSite, openCheckPlace, placePrice, placeRows, refusedBeforeRun, retryRequest, runPlace, toolPoolPrice, withPoolRefusal, type RunPlaceInput } from "@/lib/run-place";
import { RUN_SHOWN_HEADER, shownHeader } from "@/lib/guest-access";
-import { lineWords } from "@/lib/pool-line";
/** Where a run happens and what it costs, for each audience and engine (the composers' place chip and send button). */
const fmt = (usd: number) => `$${usd.toFixed(2)}`;
@@ -266,7 +265,7 @@ describe("Retry and Run on <the place> on a run's tile", () => {
describe("the Run on list", () => {
const account = { kind: "account" as const, hosted: true, prefer: "pool" as const, placeName: "Studio North GPUs", gpu: { connected: false } };
const gpu = { connected: true, online: true, device: "cuda:0 NVIDIA GeForce RTX 4090 : cudaMallocAsync" };
- const quote = { text: "Free", wait: "Next in line · about 40 s" };
+ const quote = { text: "Free", wait: "ready in about 40 s" };
it("no control without a choice: none for a guest, hosted runs off, nothing of one's own, or an item only one's own runs", () => {
expect(placeRows({ ...account, kind: "guest", gpu }, {}, quote)).toBeNull();
expect(placeRows({ ...account, hosted: false, gpu }, {}, quote)).toBeNull();
@@ -279,7 +278,7 @@ describe("the Run on list", () => {
expect(placeRows({ ...account, gpu }, {}, quote)).toEqual({
on: "site",
rows: [
- { id: "site", label: "Studio North GPUs", sub: "Free · Next in line · about 40 s", selected: true },
+ { id: "site", label: "Studio North GPUs", sub: "Free · ready in about 40 s", selected: true },
{ id: "gpu", label: "Your GPU", sub: "Free · RTX 4090", online: true, selected: false },
],
});
@@ -371,9 +370,13 @@ describe("checkedPool", () => {
describe("a tool page's own price check, for a run on this studio's GPUs", () => {
const line = { place: 2, etaSeconds: 180 };
- it("says the service's price and the place in line instead of the page's own words, and carries the price shown", () => {
+ it("says the service's price and when the run would be ready instead of the page's own words, and carries the price shown", () => {
const p = toolPoolPrice({ costUsd: 0, demo: false, notes: [], place: "pool", quote: { allowed: true, amount: 0, priceVersion: "v1", text: "Free" }, line });
- expect(p?.text).toBe(`Free · ${lineWords(line)}`);
+ expect(p?.text).toBe("Free · ready in about 3 min");
+ // Every GPU away: Run stays on, and the chip says it starts when one is free.
+ expect(toolPoolPrice({ place: "pool", quote: { allowed: true, amount: 0, priceVersion: "v1", text: "Free" }, line: { place: 2, etaSeconds: null, unknown: true } })).toMatchObject({ text: "Free · starts when a GPU is free", refused: false });
+ // Light work: ready in seconds.
+ expect(toolPoolPrice({ place: "pool", quote: { allowed: true, amount: 0, priceVersion: "", text: "Free" }, line: { place: 1, etaSeconds: null, light: true } })?.text).toBe("Free · ready in seconds");
expect(p?.text).not.toMatch(/GPU/);
expect(p?.refused).toBe(false);
expect(p?.headers).toEqual({ [RUN_SHOWN_HEADER]: shownHeader({ amount: 0, priceVersion: "v1" }) });
diff --git a/tests/workers-pool.test.ts b/tests/workers-pool.test.ts
index d1c3312d..08905a70 100644
--- a/tests/workers-pool.test.ts
+++ b/tests/workers-pool.test.ts
@@ -356,6 +356,18 @@ describe("losing a worker (checks 3, 4, 5)", () => {
expect(state(id).state).toBe("failed");
expect(state(id).error).toBe("The GPUs were busy. Not charged.");
});
+
+ it("a person's task with no wait limit (the policy's 0) never fails for a wait: 40 minutes with every worker paused, it is still in line", () => {
+ const w = worker("paused");
+ pool.patchWorker(w.id, { paused: true });
+ const id = task({ account: "acct-no-limit" });
+ clock += 40 * MIN;
+ pool.sweepPool(clock);
+ expect(state(id).state).toBe("waiting");
+ clock += 24 * 60 * MIN;
+ pool.sweepPool(clock);
+ expect(state(id).state).toBe("waiting");
+ });
});
describe("order (checks 8, 9)", () => {