Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(model-trellis): retry a stalled image fetch instead of failing the whole reconstruction

nirholasa2e88c5475f6
diff --git a/workers/model-trellis/Dockerfile b/workers/model-trellis/Dockerfile
index 8500595fe..31a7a9211 100644
--- a/workers/model-trellis/Dockerfile
+++ b/workers/model-trellis/Dockerfile
@@ -70,9 +70,13 @@ RUN git clone https://github.com/autonomousvision/mip-splatting.git /tmp/ext/mip
&& rm -rf /tmp/ext
# ── 5. Server deps ────────────────────────────────────────────────────────────
+# pytest is here for the build-time gate at the bottom of this file, the same
+# pattern workers/garment-forge uses: the request policy is unit tested during
+# `docker build`, so a broken tier table or clamp can never reach a revision.
RUN pip install \
"fastapi==0.115.0" "uvicorn[standard]==0.32.0" "pydantic>=2.0.0" \
- "httpx>=0.27.0" "google-cloud-storage==2.18.0" "safetensors>=0.4.0"
+ "httpx>=0.27.0" "google-cloud-storage==2.18.0" "safetensors>=0.4.0" \
+ "pytest>=8.0.0"
# ── 6. TRELLIS source (imported via PYTHONPATH, pinned for reproducibility) ───
# --recurse-submodules is REQUIRED: TRELLIS vendors FlexiCubes (its mesh
@@ -89,7 +93,14 @@ RUN git clone --recurse-submodules https://github.com/microsoft/TRELLIS.git /app
WORKDIR /app
COPY worker_security.py /app/worker_security.py
+COPY request_policy.py /app/request_policy.py
COPY main.py /app/main.py
+COPY test_request_policy.py /app/test_request_policy.py
+
+# Build-time gate: the quality tiers, the clamps that keep a caller value from
+# crashing the nvdiffrast bake, and the image-fetch retry policy are all pure
+# logic, so they are proven here rather than in production. Needs no GPU.
+RUN python3 -m pytest /app/test_request_policy.py -q
EXPOSE 8080
diff --git a/workers/model-trellis/README.md b/workers/model-trellis/README.md
index 6932e8701..43b795443 100644
--- a/workers/model-trellis/README.md
+++ b/workers/model-trellis/README.md
@@ -18,7 +18,11 @@ served back as an `https://storage.googleapis.com/…` URL.
## Endpoints
`POST /infer` and `GET /tasks/{id}` require `Authorization: Bearer $API_KEY`.
-`GET /health` is unauthenticated so Cloud Run's startup probe can reach it.
+`GET /health` and `GET /` are unauthenticated: they carry no secrets, and the
+platform's warmth probe ([`api/_lib/forge-lane-health.js`](../../api/_lib/forge-lane-health.js),
+[`api/cron/gpu-keepwarm.js`](../../api/cron/gpu-keepwarm.js)) reads the root to
+decide whether this lane is up. Cloud Run's own startup probe is a TCP check on
+port 8080, not an HTTP one.
### `POST /infer` → `202`
@@ -42,7 +46,12 @@ Request:
turnaround views (front/side/back) of the **same** subject via
`run_multi_image`. `https` sources are pulled through the SSRF guard in
[`worker_security.py`](./worker_security.py) (https-only; private, loopback,
- link-local, and cloud-metadata IPs rejected on every redirect hop).
+ link-local, and cloud-metadata IPs rejected on every redirect hop). Each fetch
+ is retried up to 3 times with exponential backoff on a timeout, a connection
+ failure, or a retryable upstream status (408/425/429/5xx); a 404 or 403 fails
+ immediately because it will never succeed. When a source is genuinely
+ unusable the task's `error` names the reason and the host instead of an
+ opaque error ref, so the caller can fix the URL.
- `body_type` — optional, default `"neutral"` (accepted, not used by TRELLIS).
- `job_id` — optional correlation string.
- `tier` — optional named quality preset: `draft` | `standard` | `high` | `max`
@@ -109,8 +118,13 @@ or `failed`.
}
```
-On failure the record carries a sanitized `error` string (the full traceback
-stays in the container log). Unknown ids return `404`.
+On failure the record carries an `error` string. A bad image source reports the
+actual reason (`image source cdn.example.com unreachable after 3 attempts
+(ReadTimeout); check the URL is publicly readable`) because the fault is in the
+request; anything internal is reduced to a correlation-id ref with the full
+traceback kept in the container log. A `queued` or `running` record that makes
+no progress for 30 minutes is expired to `failed` so a client cannot poll
+forever behind a dead runner. Unknown ids return `404`.
### `GET /health`
@@ -133,6 +147,20 @@ The ~3 GB pipeline loads in the background after the port opens, so a cold
instance reports `ready: false` briefly; `/infer` tasks submitted during that
window wait for `ready` (up to 600 s) rather than failing.
+### `GET /`
+
+Unauthenticated service descriptor, answered so the platform's warmth probe
+stops recording a 404 every minute in this service's log:
+
+```json
+{
+ "service": "model-trellis",
+ "model": "trellis-image-large",
+ "ready": true,
+ "endpoints": ["POST /infer", "GET /tasks/{task_id}", "GET /health"]
+}
+```
+
## Environment
| Var | Required | Default | Purpose |
@@ -146,10 +174,24 @@ window wait for `ready` (up to 600 s) rather than failing.
| `REMBG_SERVICE_URL` | no | — | Sibling [`rembg-service`](../rembg/) base URL for the `matte` pre-step. Unset disables matting (TRELLIS still removes the background internally). |
| `REMBG_MODEL` | no | `isnet-general-use` | Default rembg model for the pre-matte |
| `REMBG_TIMEOUT_S` | no | `90` | Max seconds to wait on the rembg-service round-trip before falling back to the un-matted image |
+| `WEIGHTS_GCS_URI` | no | - | `gs://` weight tree staged to local disk at startup with the storage client. Set in production; see the note below |
+| `WEIGHTS_LOCAL_DIR` | no | `/tmp/trellis-weights` | Where that staging lands, and what the pipeline then loads from |
+| `IMAGE_FETCH_TIMEOUT_S` | no | `30` | Per-attempt timeout for fetching a caller-supplied `https://` image (3 attempts) |
Weights are **not** baked into the image — the `three-ws-model-weights` bucket
-is mounted at `/weights`, so refreshing weights needs no rebuild. Pre-populate
-once with:
+is mounted at `/weights`, so refreshing weights needs no rebuild.
+
+At startup the loader **stages** that tree to local disk (`WEIGHTS_GCS_URI` →
+`WEIGHTS_LOCAL_DIR`) with the storage client and loads from there. The GCS FUSE
+mount serves the model's random-access reads over the network, and a cold load
+routinely stalled on it (`stalled read-req cancelled`, `context deadline
+exceeded`), turning a ~50 s load into 15+ minutes or a hard timeout; a plain
+sequential GET per object does not. If `WEIGHTS_GCS_URI` is unset, or staging
+fails for any reason, the loader falls back to reading `WEIGHTS_DIR` off the
+mount, so this can only add reliability. Already-staged objects whose size
+matches are reused, so a same-instance reload does not re-pull 3 GB.
+
+Pre-populate the bucket once with:
```bash
pip install huggingface_hub
@@ -157,6 +199,25 @@ huggingface-cli download microsoft/TRELLIS-image-large --local-dir /tmp/trellis-
gsutil -m cp -r /tmp/trellis-large gs://three-ws-model-weights/trellis-large/
```
+## Tests
+
+The request policy (quality tiers, the clamps that stop a caller value from
+crashing the texture bake, the image-fetch retry) lives in
+[`request_policy.py`](./request_policy.py), deliberately free of torch and CUDA
+so it can be proven anywhere:
+
+```bash
+cd workers/model-trellis
+python3 -m pip install pytest httpx
+python3 -m pytest test_request_policy.py -q # 18 tests
+```
+
+The same suite runs **inside `docker build`** (see the `RUN python3 -m pytest`
+step in the Dockerfile), so a broken tier table or clamp fails the build instead
+of a user's generation. The GPU-bound half of the service is covered by the
+platform-side integration tests in
+[`tests/api/forge-trellis-selfhost.test.js`](../../tests/api/forge-trellis-selfhost.test.js).
+
## Run locally
Requires a CUDA GPU and the TRELLIS weights on disk. Dependencies are installed
@@ -195,14 +256,22 @@ Submit from the **repo root** — the build step declares `dir: workers/model-tr
so the upload source is the whole repo:
```bash
-gcloud builds submit --config workers/model-trellis/cloudbuild.yaml .
+gcloud builds submit --config workers/model-trellis/cloudbuild.yaml . \
+ --region us-central1 --project aerial-vehicle-466722-p5 \
+ --substitutions=SHORT_SHA=manual$(date +%s)
```
+`SHORT_SHA` is only populated automatically for trigger-driven builds; a manual
+submit must pass it, because the config tags and deploys
+`.../server:$SHORT_SHA`. The config also pins the `three-ws-build@` service
+account (the project's default compute SA was deleted).
+
Or provision it alongside the rest of the fleet (idempotent; prints the URLs to
-set on the `three-ws-api` service env):
+set on the `three-ws-api` service env). Valid service ids are exactly
+`hunyuan3d trellis triposr triposg rig`:
```bash
-PROJECT_ID=<gcp-project> SERVICES="hunyuan3d trellis triposg unirig" \
+PROJECT_ID=<gcp-project> SERVICES="hunyuan3d trellis triposg rig" \
workers/deploy/deploy-all.sh
```
@@ -210,9 +279,10 @@ Builds the image (CUDA extension compiles push the build past an hour — the
config sets `timeout: 3600s`) and deploys Cloud Run service **`model-trellis`**
in `us-central1`: **1× `nvidia-l4` GPU**, 8 vCPU, 32 GiB, 900 s request timeout,
`min-instances=1` (one instance stays warm because a cold start pays a
-multi-minute weight load), `max-instances=2`. The weights bucket
-(`three-ws-model-weights`) is mounted at `/weights` and `API_KEY` comes from the
-`avatar-reconstruction-key` secret.
+multi-minute weight load), `max-instances=3`. Each instance serializes its own
+GPU at `MAX_CONCURRENT=1`, so the instance count *is* the concurrent-generation
+count. The weights bucket (`three-ws-model-weights`) is mounted at `/weights`
+and `API_KEY` comes from the `avatar-reconstruction-key` secret.
## Example — submit, poll, fetch
@@ -224,7 +294,7 @@ KEY=your-api-key
TASK=$(curl -s -X POST "$BASE/infer" \
-H "Authorization: Bearer $KEY" \
-H 'Content-Type: application/json' \
- -d '{"images":["https://storage.googleapis.com/three-ws-public/samples/chair.png"]}' \
+ -d '{"images":["https://three.ws/avatars/thumbs/default.png"]}' \
| python3 -c 'import sys,json; print(json.load(sys.stdin)["task_id"])')
# 2. Poll until done
diff --git a/workers/model-trellis/main.py b/workers/model-trellis/main.py
index fd12e27a5..5c0a9a23e 100644
--- a/workers/model-trellis/main.py
+++ b/workers/model-trellis/main.py
@@ -23,16 +23,25 @@ API contract (consumed by the Pipeline Controller):
GET /health → { ok, model, gpu_available, tiers, rembg_matte }
+ GET / → { service, model, ready, endpoints }. Unauthenticated
+ service descriptor for the platform's warmth probe.
+
Model weights pre-population:
pip install huggingface_hub
huggingface-cli download microsoft/TRELLIS-image-large --local-dir /tmp/trellis-large
gsutil -m cp -r /tmp/trellis-large gs://three-ws-model-weights/trellis-large/
-Environment variables:
- API_KEY — shared bearer secret
- GCS_BUCKET — Cloud Storage bucket for output meshes
- WEIGHTS_DIR — local path to model weights (default: /weights/trellis-large)
- MAX_CONCURRENT — max parallel inferences (default: 1)
+Environment variables (README.md carries the full table):
+ API_KEY shared bearer secret
+ GCS_BUCKET Cloud Storage bucket for output meshes
+ WEIGHTS_DIR local path to weights (default: /weights/trellis-large)
+ WEIGHTS_GCS_URI optional gs:// tree staged to local disk at startup
+ WEIGHTS_LOCAL_DIR where that staging lands (default: /tmp/trellis-weights)
+ MAX_CONCURRENT max parallel inferences (default: 1)
+ REMBG_SERVICE_URL sibling rembg worker for the matte pre-step
+ REMBG_MODEL default rembg model (default: isnet-general-use)
+ REMBG_TIMEOUT_S matte round-trip budget (default: 90)
+ IMAGE_FETCH_TIMEOUT_S per-attempt image fetch timeout (default: 30)
"""
from __future__ import annotations
@@ -56,6 +65,7 @@ os.environ.setdefault("ATTN_BACKEND", "xformers")
os.environ.setdefault("SPCONV_ALGO", "native")
from contextlib import asynccontextmanager
from typing import Optional
+from urllib.parse import urlsplit
import torch
from fastapi import FastAPI, HTTPException, Header, BackgroundTasks
@@ -64,6 +74,15 @@ from google.cloud import storage
from PIL import Image
from pydantic import BaseModel, Field
+from request_policy import (
+ FETCH_ATTEMPTS,
+ QUALITY_DEFAULTS,
+ TIER_PRESETS,
+ call_with_retry,
+ clamped_quality,
+ matte_enabled,
+ normalize_tier,
+)
from worker_security import (
UnsafeUrlError,
fetch_remote_bytes,
@@ -217,6 +236,64 @@ def _require_api_key(authorization: str) -> None:
raise HTTPException(status_code=401, detail=str(exc)) from exc
+class ImageSourceError(ValueError):
+ """A caller-supplied image could not be read.
+
+ Distinct from an internal failure: the cause is the request's own `images`
+ entry (unreachable host, rejected target, undecodable bytes), so the message
+ is safe and useful to hand back verbatim instead of an opaque error ref.
+ """
+
+
+IMAGE_FETCH_TIMEOUT_S = float(os.environ.get("IMAGE_FETCH_TIMEOUT_S", "30"))
+
+
+def _source_label(src: str) -> str:
+ """Short, non-leaking identifier for an image source, for error messages."""
+ if src.startswith("data:image"):
+ return "inline data uri"
+ host = urlsplit(src).hostname
+ return host or src[:60]
+
+
+def _fetch_image_bytes(src: str) -> bytes:
+ """Fetch one https image source, retrying transient network failures.
+
+ A single read timeout against a public image host used to fail the entire
+ generation (observed live 2026-08-10). The fetch itself stays SSRF-hardened:
+ https-only, private/loopback/link-local/metadata IPs rejected after DNS
+ resolution, redirects re-validated per hop, response size bounded.
+ """
+ label = _source_label(src)
+
+ def attempt() -> bytes:
+ return fetch_remote_bytes(src, timeout=IMAGE_FETCH_TIMEOUT_S)
+
+ def note_retry(number: int, delay: float, exc: BaseException) -> None:
+ log.warning(
+ "image fetch attempt %d/%d for %s failed (%s); retrying in %.1fs",
+ number, FETCH_ATTEMPTS, label, type(exc).__name__, delay,
+ )
+
+ try:
+ return call_with_retry(attempt, sleep=time.sleep, on_retry=note_retry)
+ except UnsafeUrlError as exc:
+ raise ImageSourceError(f"refused to fetch image source ({label}): {exc}") from exc
+ except httpx.HTTPStatusError as exc:
+ raise ImageSourceError(
+ f"image source {label} returned HTTP {exc.response.status_code}"
+ ) from exc
+ except httpx.HTTPError as exc:
+ raise ImageSourceError(
+ f"image source {label} unreachable after {FETCH_ATTEMPTS} attempts "
+ f"({type(exc).__name__}); check the URL is publicly readable"
+ ) from exc
+ except ValueError as exc:
+ # The guard's own size ceiling. Caught after UnsafeUrlError (a ValueError
+ # subclass) so the more specific message wins.
+ raise ImageSourceError(f"image source {label} rejected: {exc}") from exc
+
+
def _decode_image(src: str, keep_alpha: bool = False) -> Image.Image:
# keep_alpha=True preserves an RGBA cutout's transparency so TRELLIS uses the
# supplied alpha as the subject mask (its preprocess_image path respects an
@@ -225,16 +302,23 @@ def _decode_image(src: str, keep_alpha: bool = False) -> Image.Image:
mode = "RGBA" if keep_alpha else "RGB"
if src.startswith("data:image"):
b64 = src.split(",", 1)[1]
- return Image.open(io.BytesIO(base64.b64decode(b64))).convert(mode)
- if src.startswith("https://"):
- # SSRF-hardened: https-only, private/loopback/link-local/metadata IPs
- # rejected after DNS resolution, redirects re-validated per hop, bounded.
try:
- data = fetch_remote_bytes(src, timeout=30)
- except UnsafeUrlError as exc:
- raise ValueError(f"refused to fetch image source: {exc}") from exc
+ raw = base64.b64decode(b64)
+ except Exception as exc: # noqa: BLE001 - caller's own payload, report it as such
+ raise ImageSourceError(f"inline data uri is not valid base64: {exc}") from exc
+ return _open_image(raw, mode, "inline data uri")
+ if src.startswith("https://"):
+ return _open_image(_fetch_image_bytes(src), mode, _source_label(src))
+ raise ImageSourceError(f"unsupported image source: {src[:60]}")
+
+
+def _open_image(data: bytes, mode: str, label: str) -> Image.Image:
+ try:
return Image.open(io.BytesIO(data)).convert(mode)
- raise ValueError(f"unsupported image source: {src[:60]}")
+ except Exception as exc: # noqa: BLE001 - undecodable caller input, not an internal fault
+ raise ImageSourceError(
+ f"image source {label} is not a decodable image ({type(exc).__name__})"
+ ) from exc
async def _matte_via_rembg(src: str, model: str) -> tuple[str, bool]:
@@ -350,93 +434,9 @@ async def _resolve_task(task_id: str) -> dict:
return task
-# Per-request quality knobs, clamped to safe envelopes for a 24 GB L4.
-# Defaults are the platform's production quality bar, not the TRELLIS demo's
-# (steps=12, simplify=0.95, texture_size=1024): GPU time is cheap against the
-# platform's GCP credit budget ($100k+ provisioned, owner has explicitly signed
-# off on spending it here), so both diffusion stages run well past the demo
-# step count and the texture bake runs at the model's max resolution by
-# default. Callers may still override per request (e.g. a lower-cost preview
-# lane). Measured warm cost at the PRIOR defaults (steps=25/25, texture=2048,
-# simplify=0.90) was ~50s/asset (docs/ops/gcp-credits.md) against a 300s client
-# poll budget (src/home-forge.js MAX_POLL_MS) — ample headroom to push further:
-# - ss_steps/slat_steps 25→40: sharper structure and surface detail. Cost
-# scales roughly linearly with steps, so ~1.6x the diffusion time.
-# - texture_size 2048→4096 (the clamp ceiling): texture baking is a
-# resize/encode pass, not a diffusion stage, so this is a small time cost
-# for a large perceptual win — resolution is one of the single biggest
-# levers on whether a result reads as "real" vs "generated."
-# - simplify 0.90→0.75: keeps meaningfully more geometry (25% of triangles
-# removed instead of 90%) — low-poly faceting is one of the most obvious
-# tells of AI-generated 3D, and this is otherwise-idle GPU decimation cost.
-# Together these land well inside the poll budget (est. ~90-120s warm) while
-# meaningfully closing the gap toward a photograph-real result.
-# `simplify` is the FRACTION OF TRIANGLES REMOVED by to_glb's decimation —
-# lower keeps more geometry. Raising steps sharpens structure and appearance
-# at roughly linear GPU-time cost; the L4 has headroom (MAX_CONCURRENT=1).
-_QUALITY_DEFAULTS = {
- "ss_steps": 40,
- "slat_steps": 40,
- "ss_cfg": 7.5,
- "slat_cfg": 3.0,
- "simplify": 0.75,
- "texture_size": 4096,
-}
-
-# Named quality tiers. A caller sends `tier` to pick one preset; an explicit
-# `quality` dict still overrides individual fields on top of it. When no tier is
-# sent the base stays _QUALITY_DEFAULTS, so the existing lane's behaviour is
-# byte-for-byte unchanged — tiers are purely additive.
-# draft — latency lane: demo-grade steps, aggressive decimation, 1K texture.
-# standard — the platform's prior default (steps 25, 2K texture, simplify 0.90).
-# high — the current default (steps 40, 4K texture, simplify 0.75).
-# max — maximum fidelity: steps at the sampler ceiling, near-zero geometry
-# decimation (keep ~all triangles), firmer guidance, 4K texture.
-# `simplify` is the FRACTION OF TRIANGLES REMOVED, so a lower value keeps MORE
-# geometry. texture_size caps at 4096 (the clamp ceiling and TRELLIS's practical
-# bake limit on the L4). max is meant to be paired with rembg pre-matting.
-_TIER_PRESETS = {
- "draft": {"ss_steps": 12, "slat_steps": 12, "ss_cfg": 7.5, "slat_cfg": 3.0, "simplify": 0.95, "texture_size": 1024},
- "standard": {"ss_steps": 25, "slat_steps": 25, "ss_cfg": 7.5, "slat_cfg": 3.0, "simplify": 0.90, "texture_size": 2048},
- "high": {"ss_steps": 40, "slat_steps": 40, "ss_cfg": 7.5, "slat_cfg": 3.0, "simplify": 0.75, "texture_size": 4096},
- "max": {"ss_steps": 50, "slat_steps": 50, "ss_cfg": 8.5, "slat_cfg": 4.5, "simplify": 0.50, "texture_size": 4096},
-}
-
-
-def _clamped_quality(q: dict | None, tier: str | None = None) -> dict:
- # Base = the named tier preset when a valid one is given, else the historical
- # defaults. An explicit `quality` dict then overrides field-by-field.
- base = dict(_QUALITY_DEFAULTS)
- if tier:
- preset = _TIER_PRESETS.get(str(tier).strip().lower())
- if preset:
- base = dict(preset)
- src = {**base, **(q or {})}
-
- def num(key, lo, hi, cast=float):
- raw = src.get(key)
- try:
- val = cast(raw)
- except (TypeError, ValueError):
- return base[key]
- return max(lo, min(hi, val))
-
- # nvdiffrast's texture bake builds a mip stack and hard-fails on any
- # non-power-of-two extent (proven live 2026-07-16: a 3072 request killed
- # every generation at the bake step). Snap the requested size down to the
- # nearest power of two inside the clamp envelope so no caller value can
- # crash the bake.
- tex = num("texture_size", 512, 4096, int)
- tex = 1 << (int(tex).bit_length() - 1)
-
- return {
- "ss_steps": num("ss_steps", 8, 50, int),
- "slat_steps": num("slat_steps", 8, 50, int),
- "ss_cfg": num("ss_cfg", 1.0, 15.0),
- "slat_cfg": num("slat_cfg", 1.0, 10.0),
- "simplify": num("simplify", 0.5, 0.98),
- "texture_size": tex,
- }
+# Quality tiers, clamps, and the matte default live in request_policy.py so the
+# decision logic that shapes every generation can be unit tested without torch,
+# CUDA, or the TRELLIS source tree (see test_request_policy.py).
async def _run_inference(
@@ -464,12 +464,12 @@ async def _run_inference(
await _update_task(task_id, status="failed", error=f"pipeline unavailable: {_load_error}")
return
- q = _clamped_quality(quality, tier)
+ q = clamped_quality(quality, tier)
# Matting defaults on for the MAX tier (paired for maximum fidelity) and off
# everywhere else, preserving the free/default lane. An explicit `matte`
# value always wins. It only actually runs when REMBG_SERVICE_URL is set.
- tier_key = str(tier).strip().lower() if tier else None
- do_matte = matte if matte is not None else (tier_key == "max")
+ tier_key = normalize_tier(tier)
+ do_matte = matte_enabled(matte, tier_key)
async with _sem:
await _update_task(task_id, status="running")
@@ -551,6 +551,17 @@ async def _run_inference(
task_id, elapsed, tier_key or "default", matted_count, q, len(glb_bytes), gcs_url,
)
+ except ImageSourceError as exc:
+ # The request's own `images` entry is at fault, so hand the reason
+ # back verbatim: an opaque error ref would tell the caller nothing
+ # and leaves the router retrying a URL that can never work.
+ log.warning("[%s] image source rejected: %s", task_id, exc)
+ await _update_task(
+ task_id,
+ status="failed",
+ error=str(exc),
+ elapsed_ms=int((time.time() - t0) * 1000),
+ )
except Exception as exc:
await _update_task(
task_id,
@@ -564,8 +575,8 @@ class InferRequest(BaseModel):
images: list[str] = Field(..., min_length=1, max_length=6)
body_type: str = "neutral"
job_id: str | None = None
- # Optional per-request override of _QUALITY_DEFAULTS (ss_steps, slat_steps,
- # ss_cfg, slat_cfg, simplify, texture_size) — see _clamped_quality. Omitted
+ # Optional per-request override of the resolved tier (ss_steps, slat_steps,
+ # ss_cfg, slat_cfg, simplify, texture_size), see request_policy. Omitted
# or partial fields fall back to the platform quality-bar defaults.
quality: dict | None = None
# Named quality tier: draft | standard | high | max. Seeds the base quality
@@ -615,6 +626,26 @@ async def get_task(task_id: str, authorization: str = Header(...)) -> dict:
return await _resolve_task(task_id)
+async def root() -> dict:
+ """Service descriptor for the platform's warmth probe.
+
+ api/_lib/forge-lane-health.js and api/cron/gpu-keepwarm.js keep this worker
+ resident with an authenticated GET against the root, and treat any status
+ below 500 as "the container is up". Without a route here every one of those
+ probes logged a 404 at WARNING severity, roughly once a minute forever,
+ which buried the real errors in this service's log. Answering 200 with the
+ readiness the probe actually wants costs nothing and keeps the log honest.
+ Unauthenticated, exposing exactly what /health already does.
+ """
+ return {
+ "service": "model-trellis",
+ "model": "trellis-image-large",
+ "ready": bool(_ready and _ready.is_set()),
+ "endpoints": ["POST /infer", "GET /tasks/{task_id}", "GET /health"],
+ }
+
+
@app.get("/health")
async def health() -> dict:
return {
@@ -625,7 +656,7 @@ async def health() -> dict:
"pipeline_loaded": _pipeline is not None,
"ready": bool(_ready and _ready.is_set()),
"load_error": _load_error,
- "tiers": list(_TIER_PRESETS),
- "default_quality": _QUALITY_DEFAULTS,
+ "tiers": list(TIER_PRESETS),
+ "default_quality": QUALITY_DEFAULTS,
"rembg_matte": bool(REMBG_SERVICE_URL),
}
diff --git a/workers/model-trellis/request_policy.py b/workers/model-trellis/request_policy.py
new file mode 100644
index 000000000..5e38d4ccf
--- /dev/null
+++ b/workers/model-trellis/request_policy.py
@@ -0,0 +1,205 @@
+"""Request policy for the TRELLIS worker: quality tiers and transient-fetch retry.
+
+This module is deliberately free of torch, CUDA, and the TRELLIS source tree so
+the decision logic that shapes every generation can be imported and unit tested
+on any machine (see test_request_policy.py). main.py imports every public name
+here; nothing in this file touches the GPU.
+
+Two policies live here:
+
+ 1. Quality resolution. A caller sends an optional named `tier` and an optional
+ per-field `quality` dict; this module turns that into the exact sampler and
+ bake parameters, clamped to what a 24 GB L4 can serve.
+ 2. Transient-fetch retry. Caller-supplied image URLs are fetched over the
+ public internet, where a single read timeout would otherwise fail a whole
+ generation. `call_with_retry` re-runs the fetch for errors that are worth
+ retrying and gives up immediately on the ones that are not.
+"""
+
+from __future__ import annotations
+
+from typing import Callable, Optional
+
+import httpx
+
+# Per-request quality knobs, clamped to safe envelopes for a 24 GB L4.
+# Defaults are the platform's production quality bar, not the TRELLIS demo's
+# (steps=12, simplify=0.95, texture_size=1024): GPU time is cheap against the
+# platform's GCP credit budget, so both diffusion stages run well past the demo
+# step count and the texture bake runs at the model's max resolution by default.
+# Callers may still override per request (for example a lower-cost preview lane).
+# `simplify` is the FRACTION OF TRIANGLES REMOVED by to_glb's decimation, so a
+# lower value keeps more geometry. Raising steps sharpens structure and
+# appearance at roughly linear GPU-time cost; the L4 has headroom because
+# MAX_CONCURRENT is 1.
+#
+# Why these numbers, measured: warm cost at the PRIOR defaults (steps 25/25,
+# texture 2048, simplify 0.90) was about 50s per asset (docs/ops/gcp-credits.md)
+# against a 300s client poll budget (src/home-forge.js MAX_POLL_MS), which left
+# room to push further:
+# - ss_steps/slat_steps 25 to 40: sharper structure and surface detail, at
+# roughly 1.6x the diffusion time since cost scales about linearly.
+# - texture_size 2048 to 4096 (the clamp ceiling): the bake is a resize and
+# encode pass, not a diffusion stage, so this is a small time cost for a
+# large perceptual win. Resolution is one of the biggest levers on whether a
+# result reads as real rather than generated.
+# - simplify 0.90 to 0.75: keeps meaningfully more geometry (25% of triangles
+# removed instead of 90%). Low-poly faceting is one of the most obvious tells
+# of AI-generated 3D, and this is otherwise-idle GPU decimation cost.
+# Together these land well inside the poll budget (about 90 to 120s warm).
+QUALITY_DEFAULTS = {
+ "ss_steps": 40,
+ "slat_steps": 40,
+ "ss_cfg": 7.5,
+ "slat_cfg": 3.0,
+ "simplify": 0.75,
+ "texture_size": 4096,
+}
+
+# Named quality tiers. A caller sends `tier` to pick one preset; an explicit
+# `quality` dict still overrides individual fields on top of it. When no tier is
+# sent the base stays QUALITY_DEFAULTS, so the existing lane's behaviour is
+# byte-for-byte unchanged: tiers are purely additive.
+# draft - latency lane: demo-grade steps, aggressive decimation, 1K texture.
+# standard - the platform's prior default (steps 25, 2K texture, simplify 0.90).
+# high - the current default (steps 40, 4K texture, simplify 0.75).
+# max - maximum fidelity: steps at the sampler ceiling, near-zero geometry
+# decimation (keep about all triangles), firmer guidance, 4K texture.
+# texture_size caps at 4096 (the clamp ceiling and TRELLIS's practical bake limit
+# on the L4). `max` is meant to be paired with rembg pre-matting.
+TIER_PRESETS = {
+ "draft": {"ss_steps": 12, "slat_steps": 12, "ss_cfg": 7.5, "slat_cfg": 3.0, "simplify": 0.95, "texture_size": 1024},
+ "standard": {"ss_steps": 25, "slat_steps": 25, "ss_cfg": 7.5, "slat_cfg": 3.0, "simplify": 0.90, "texture_size": 2048},
+ "high": {"ss_steps": 40, "slat_steps": 40, "ss_cfg": 7.5, "slat_cfg": 3.0, "simplify": 0.75, "texture_size": 4096},
+ "max": {"ss_steps": 50, "slat_steps": 50, "ss_cfg": 8.5, "slat_cfg": 4.5, "simplify": 0.50, "texture_size": 4096},
+}
+
+
+def normalize_tier(tier: Optional[str]) -> Optional[str]:
+ """Lowercase and trim a caller's tier string, or None when none was sent.
+
+ An unknown-but-non-empty tier normalizes rather than raising: it is reported
+ back on the task record so a typo is visible, and quality falls back to the
+ defaults.
+ """
+ if tier is None:
+ return None
+ key = str(tier).strip().lower()
+ return key or None
+
+
+def matte_enabled(matte: Optional[bool], tier_key: Optional[str]) -> bool:
+ """Resolve whether to pre-matte the subject via the sibling rembg service.
+
+ Defaults on for the `max` tier (paired for maximum fidelity) and off
+ everywhere else, preserving the free/default lane. An explicit `matte` value
+ from the caller always wins.
+ """
+ if matte is not None:
+ return bool(matte)
+ return tier_key == "max"
+
+
+def clamped_quality(q: Optional[dict], tier: Optional[str] = None) -> dict:
+ """Resolve tier preset plus per-field overrides into clamped sampler params.
+
+ Base is the named tier preset when a valid one is given, else the historical
+ defaults. An explicit `quality` dict then overrides field by field, and every
+ field is clamped to the L4 envelope. Unparseable values fall back to the base
+ rather than failing the request.
+ """
+ base = dict(QUALITY_DEFAULTS)
+ if tier:
+ preset = TIER_PRESETS.get(normalize_tier(tier) or "")
+ if preset:
+ base = dict(preset)
+ src = {**base, **(q or {})}
+
+ def num(key, lo, hi, cast=float):
+ raw = src.get(key)
+ try:
+ val = cast(raw)
+ except (TypeError, ValueError):
+ return base[key]
+ return max(lo, min(hi, val))
+
+ # nvdiffrast's texture bake builds a mip stack and hard-fails on any
+ # non-power-of-two extent (proven live 2026-07-16: a 3072 request killed
+ # every generation at the bake step). Snap the requested size down to the
+ # nearest power of two inside the clamp envelope so no caller value can
+ # crash the bake.
+ tex = num("texture_size", 512, 4096, int)
+ tex = 1 << (int(tex).bit_length() - 1)
+
+ return {
+ "ss_steps": num("ss_steps", 8, 50, int),
+ "slat_steps": num("slat_steps", 8, 50, int),
+ "ss_cfg": num("ss_cfg", 1.0, 15.0),
+ "slat_cfg": num("slat_cfg", 1.0, 10.0),
+ "simplify": num("simplify", 0.5, 0.98),
+ "texture_size": tex,
+ }
+
+
+# Total attempts (not extra retries) for one caller-supplied image URL, and the
+# first backoff gap. Three attempts at 1s then 2s costs at most a few seconds of
+# an already-asynchronous job, and covers the single-blip read timeouts that
+# were failing whole generations from the public internet.
+FETCH_ATTEMPTS = 3
+FETCH_RETRY_BASE_SECONDS = 1.0
+
+# Upstream status codes worth a second try. Everything else (404, 403, 400) is a
+# statement about the URL itself and will fail identically on every attempt.
+_RETRYABLE_STATUS = frozenset({408, 425, 429, 500, 502, 503, 504})
+
+
+def retry_delays(
+ attempts: int = FETCH_ATTEMPTS, base: float = FETCH_RETRY_BASE_SECONDS
+) -> list[float]:
+ """Exponential backoff gaps between attempts (one fewer than `attempts`)."""
+ return [base * (2 ** i) for i in range(max(0, attempts - 1))]
+
+
+def is_transient_fetch_error(exc: BaseException) -> bool:
+ """True when re-fetching the same URL could plausibly succeed.
+
+ Timeouts and connection-level failures are the blips this exists for. An
+ HTTP error is transient only for the status codes above; a 404 is not going
+ to become a 200 on the next attempt.
+ """
+ if isinstance(exc, httpx.HTTPStatusError):
+ return exc.response.status_code in _RETRYABLE_STATUS
+ return isinstance(
+ exc, (httpx.TimeoutException, httpx.NetworkError, httpx.RemoteProtocolError)
+ )
+
+
+def call_with_retry(
+ fn: Callable[[], object],
+ *,
+ attempts: int = FETCH_ATTEMPTS,
+ should_retry: Callable[[BaseException], bool] = is_transient_fetch_error,
+ sleep: Callable[[float], None],
+ on_retry: Optional[Callable[[int, float, BaseException], None]] = None,
+):
+ """Call `fn`, retrying with exponential backoff while `should_retry` holds.
+
+ Re-raises the last exception once the attempts are spent or the error is not
+ retryable. `sleep` is injected so the policy stays testable without wall
+ clock time; `on_retry` receives (attempt_number, delay, exception) for
+ logging.
+ """
+ delays = retry_delays(attempts)
+ last: BaseException
+ for index in range(max(1, attempts)):
+ try:
+ return fn()
+ except BaseException as exc: # noqa: BLE001 - re-raised below after the budget
+ last = exc
+ if index >= len(delays) or not should_retry(exc):
+ raise
+ delay = delays[index]
+ if on_retry:
+ on_retry(index + 1, delay, exc)
+ sleep(delay)
+ raise last
diff --git a/workers/model-trellis/test_request_policy.py b/workers/model-trellis/test_request_policy.py
new file mode 100644
index 000000000..d579f23eb
--- /dev/null
+++ b/workers/model-trellis/test_request_policy.py
@@ -0,0 +1,194 @@
+"""Unit tests for the request policy: quality tiers and transient-fetch retry.
+
+Pure stdlib plus httpx, no torch and no CUDA, so this runs anywhere:
+
+ cd workers/model-trellis && python3 -m pytest test_request_policy.py -q
+
+Everything here is on the hot path of every generation. The tier table decides
+what the samplers actually do, the clamps are the only thing standing between a
+caller value and a crashed bake, and the retry policy is what keeps one blip on
+a public image host from failing a whole reconstruction.
+"""
+
+import httpx
+import pytest
+
+from request_policy import (
+ FETCH_ATTEMPTS,
+ QUALITY_DEFAULTS,
+ TIER_PRESETS,
+ call_with_retry,
+ clamped_quality,
+ is_transient_fetch_error,
+ matte_enabled,
+ normalize_tier,
+ retry_delays,
+)
+
+# ---------------------------------------------------------------- quality tiers
+
+
+def test_no_tier_keeps_historical_defaults():
+ assert clamped_quality(None) == QUALITY_DEFAULTS
+
+
+def test_every_tier_resolves_to_its_preset():
+ for name, preset in TIER_PRESETS.items():
+ assert clamped_quality(None, name) == preset, name
+
+
+def test_tier_is_case_and_whitespace_tolerant():
+ assert clamped_quality(None, " MAX ") == TIER_PRESETS["max"]
+
+
+def test_unknown_tier_falls_back_to_defaults():
+ assert clamped_quality(None, "ultra") == QUALITY_DEFAULTS
+
+
+def test_quality_dict_overrides_the_tier_field_by_field():
+ resolved = clamped_quality({"texture_size": 1024}, "max")
+ assert resolved["texture_size"] == 1024
+ # Every other field still comes from the tier.
+ assert resolved["ss_steps"] == TIER_PRESETS["max"]["ss_steps"]
+ assert resolved["simplify"] == TIER_PRESETS["max"]["simplify"]
+
+
+def test_steps_and_cfg_clamp_to_the_l4_envelope():
+ resolved = clamped_quality(
+ {"ss_steps": 9999, "slat_steps": 0, "ss_cfg": 99.0, "slat_cfg": 0.0, "simplify": 1.0}
+ )
+ assert resolved["ss_steps"] == 50
+ assert resolved["slat_steps"] == 8
+ assert resolved["ss_cfg"] == 15.0
+ assert resolved["slat_cfg"] == 1.0
+ assert resolved["simplify"] == 0.98
+
+
+def test_texture_size_snaps_down_to_a_power_of_two():
+ # Regression: a 3072 request killed every generation at the nvdiffrast bake
+ # (live 2026-07-16). It must land on 2048, never pass through.
+ assert clamped_quality({"texture_size": 3072})["texture_size"] == 2048
+ assert clamped_quality({"texture_size": 4096})["texture_size"] == 4096
+ assert clamped_quality({"texture_size": 100})["texture_size"] == 512
+ assert clamped_quality({"texture_size": 99999})["texture_size"] == 4096
+
+
+def test_unparseable_values_fall_back_to_the_base_rather_than_failing():
+ resolved = clamped_quality({"ss_steps": "many", "slat_cfg": None}, "draft")
+ assert resolved["ss_steps"] == TIER_PRESETS["draft"]["ss_steps"]
+ assert resolved["slat_cfg"] == TIER_PRESETS["draft"]["slat_cfg"]
+
+
+def test_resolved_quality_always_carries_every_sampler_field():
+ for tier in [None, *TIER_PRESETS]:
+ assert set(clamped_quality(None, tier)) == set(QUALITY_DEFAULTS)
+
+
+def test_normalize_tier():
+ assert normalize_tier(None) is None
+ assert normalize_tier(" ") is None
+ assert normalize_tier(" High ") == "high"
+
+
+def test_matte_defaults_on_only_for_max():
+ assert matte_enabled(None, "max") is True
+ assert matte_enabled(None, "high") is False
+ assert matte_enabled(None, None) is False
+ # An explicit caller value always wins over the tier default.
+ assert matte_enabled(False, "max") is False
+ assert matte_enabled(True, "draft") is True
+
+
+# ------------------------------------------------------------------ fetch retry
+
+
+def _timeout():
+ return httpx.ReadTimeout("read timed out")
+
+
+def _status(code):
+ request = httpx.Request("GET", "https://example.invalid/a.png")
+ response = httpx.Response(code, request=request)
+ return httpx.HTTPStatusError(f"http {code}", request=request, response=response)
+
+
+def test_transient_classification():
+ assert is_transient_fetch_error(_timeout()) is True
+ assert is_transient_fetch_error(httpx.ConnectError("refused")) is True
+ assert is_transient_fetch_error(_status(503)) is True
+ assert is_transient_fetch_error(_status(429)) is True
+ # A URL that is wrong stays wrong: retrying it only wastes the job's budget.
+ assert is_transient_fetch_error(_status(404)) is False
+ assert is_transient_fetch_error(_status(403)) is False
+ assert is_transient_fetch_error(ValueError("not an image")) is False
+
+
+def test_retry_delays_back_off_exponentially():
+ assert retry_delays(3, 1.0) == [1.0, 2.0]
+ assert retry_delays(1, 1.0) == []
+
+
+def test_returns_immediately_when_the_first_attempt_works():
+ calls = []
+ slept = []
+ result = call_with_retry(
+ lambda: (calls.append(1), "ok")[1], sleep=slept.append
+ )
+ assert result == "ok"
+ assert len(calls) == 1
+ assert slept == []
+
+
+def test_recovers_from_a_transient_blip():
+ attempts = []
+
+ def flaky():
+ attempts.append(1)
+ if len(attempts) < 3:
+ raise _timeout()
+ return b"glb"
+
+ slept = []
+ assert call_with_retry(flaky, sleep=slept.append) == b"glb"
+ assert len(attempts) == 3
+ assert slept == [1.0, 2.0]
+
+
+def test_gives_up_after_the_attempt_budget():
+ attempts = []
+
+ def always_times_out():
+ attempts.append(1)
+ raise _timeout()
+
+ slept = []
+ with pytest.raises(httpx.ReadTimeout):
+ call_with_retry(always_times_out, sleep=slept.append)
+ assert len(attempts) == FETCH_ATTEMPTS
+ assert len(slept) == FETCH_ATTEMPTS - 1
+
+
+def test_does_not_retry_a_permanent_failure():
+ attempts = []
+
+ def not_found():
+ attempts.append(1)
+ raise _status(404)
+
+ slept = []
+ with pytest.raises(httpx.HTTPStatusError):
+ call_with_retry(not_found, sleep=slept.append)
+ assert len(attempts) == 1
+ assert slept == []
+
+
+def test_on_retry_receives_the_attempt_delay_and_cause():
+ seen = []
+
+ def flaky():
+ if len(seen) < 1:
+ raise _timeout()
+ return "ok"
+
+ call_with_retry(flaky, sleep=lambda _: None, on_retry=lambda n, d, e: seen.append((n, d, type(e))))
+ assert seen == [(1, 1.0, httpx.ReadTimeout)]