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.

feat(trellis2): add the TRELLIS.2 GPU worker that returns PBR GLBs with alpha, meshopt packed, at 512, 1024 or 1536

nirholasc977a7193076
diff --git a/workers/model-trellis2/Dockerfile b/workers/model-trellis2/Dockerfile
new file mode 100644
index 000000000..bad45baae
--- /dev/null
+++ b/workers/model-trellis2/Dockerfile
@@ -0,0 +1,120 @@
+# TRELLIS.2 (Microsoft, MIT): single image to a PBR-textured 3D asset on an L4 (24 GB).
+#
+# Translates the upstream conda `setup.sh` into a reproducible pip build.
+# * CUDA 12.4 *devel* base: nvcc compiles CuMesh, FlexGEMM, O-Voxel and
+# nvdiffrast from source, and 12.4 is the toolkit upstream recommends.
+# * torch 2.6.0 + cu124, the matrix upstream's setup.sh installs.
+# * Attention backend = xformers, NOT flash-attn. flash-attn compiles from source
+# for 30+ minutes and routinely OOMs the builder; xformers is an upstream
+# supported backend and runs on the L4 (sm_89). Set via ATTN_BACKEND.
+# * TORCH_CUDA_ARCH_LIST defaults to 8.9 (L4). Pass a wider list for other GPUs.
+# * nvdiffrec is NOT installed: it only backs the preview renderer, never the GLB
+# bake, and carries NVIDIA terms we have no need to take on.
+# * gltfpack (zeux/meshoptimizer, MIT) is pinned by release tag and checksum,
+# the same pin workers/stylize ships, and compresses the output GLB.
+FROM python:3.11-slim AS gltfpack
+ARG GLTFPACK_VERSION=v1.2
+ARG GLTFPACK_SHA256=ebc236f5f6c08c7e5c5750476a187d24805d44d8c680449c4b7369c333f817b1
+RUN apt-get update && apt-get install -y --no-install-recommends curl unzip ca-certificates \
+ && curl -fsSL -o /tmp/gltfpack.zip \
+ https://github.com/zeux/meshoptimizer/releases/download/${GLTFPACK_VERSION}/gltfpack-ubuntu.zip \
+ && echo "${GLTFPACK_SHA256} /tmp/gltfpack.zip" | sha256sum -c - \
+ && unzip -j /tmp/gltfpack.zip gltfpack -d /usr/local/bin \
+ && chmod +x /usr/local/bin/gltfpack \
+ && /usr/local/bin/gltfpack -v
+
+FROM nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04
+
+ARG TORCH_CUDA_ARCH_LIST="8.9"
+
+ENV PYTHONDONTWRITEBYTECODE=1 \
+ PYTHONUNBUFFERED=1 \
+ PIP_NO_CACHE_DIR=1 \
+ DEBIAN_FRONTEND=noninteractive \
+ TORCH_CUDA_ARCH_LIST="${TORCH_CUDA_ARCH_LIST}" \
+ CUDA_HOME=/usr/local/cuda \
+ ATTN_BACKEND=xformers \
+ PYTHONPATH=/app/TRELLIS.2:/app/TRELLIS.2/o-voxel \
+ PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
+ # The weights are staged to the bucket, never fetched from the Hub at serve time.
+ HF_HUB_OFFLINE=1 \
+ TRANSFORMERS_OFFLINE=1 \
+ # Cap glibc at two malloc arenas. Every job runs on executor threads, and by
+ # default each thread grows its own arena that keeps freed heap forever (see
+ # instance_health.py).
+ MALLOC_ARENA_MAX=2
+
+# libusb-1.0-0 and libegl1: open3d dlopens both at import time. libjpeg-dev is the
+# header set setup.sh installs for pillow.
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ python3.10 python3.10-dev python3-pip \
+ git curl wget build-essential ninja-build \
+ libgl1 libglib2.0-0 libgomp1 libjpeg-dev \
+ libusb-1.0-0 libegl1 \
+ && rm -rf /var/lib/apt/lists/* \
+ && ln -sf /usr/bin/python3.10 /usr/bin/python3 \
+ && ln -sf /usr/bin/python3.10 /usr/bin/python \
+ && pip install --upgrade pip setuptools wheel
+
+COPY --from=gltfpack /usr/local/bin/gltfpack /usr/local/bin/gltfpack
+
+# 1. Torch first (own layer; every extension below links against it).
+RUN pip install torch==2.6.0 torchvision==0.21.0 --index-url https://download.pytorch.org/whl/cu124
+
+# 2. setup.sh --basic, minus gradio/tensorboard (the demo UI) and with the serving
+# dependencies pinned. transformers must carry DINOv3 (4.56+) and stay compatible
+# with torch 2.6. open3d is pinned for the same reason as the v1 worker: an
+# unpinned resolve once pulled a wheel with new system-library needs.
+RUN pip install \
+ imageio imageio-ffmpeg tqdm easydict opencv-python-headless ninja trimesh \
+ "transformers==4.57.1" pandas lpips zstandard kornia timm einops \
+ pillow plyfile scipy "open3d==0.19.0" \
+ && pip install git+https://github.com/EasternJournalist/utils3d.git@9a4eb15e4021b67b12c460c7057d642626897ec8
+
+# 3. xformers matched to torch 2.6.0.
+RUN pip install xformers==0.0.29.post2 --index-url https://download.pytorch.org/whl/cu124
+
+# 4. Compiled CUDA extensions (setup.sh --nvdiffrast --cumesh --flexgemm --o-voxel).
+# --no-build-isolation is REQUIRED: each setup.py imports torch at build time and
+# PEP517 isolation hides the torch from step 1.
+# TRELLIS.2 is pinned to a commit: a moving `main` has broken a worker rebuild
+# before. The clone is recursive for o-voxel's eigen submodule.
+RUN git clone --recursive https://github.com/microsoft/TRELLIS.2.git /app/TRELLIS.2 \
+ && git -C /app/TRELLIS.2 checkout 75fbf0183001ed9876c8dbb35de6b68552ee08bd \
+ && git -C /app/TRELLIS.2 submodule update --init --recursive
+RUN git clone -b v0.4.0 --depth 1 https://github.com/NVlabs/nvdiffrast.git /tmp/ext/nvdiffrast \
+ && pip install --no-build-isolation /tmp/ext/nvdiffrast
+RUN git clone --recursive https://github.com/JeffreyXiang/CuMesh.git /tmp/ext/CuMesh \
+ && pip install --no-build-isolation /tmp/ext/CuMesh
+RUN git clone --recursive https://github.com/JeffreyXiang/FlexGEMM.git /tmp/ext/FlexGEMM \
+ && pip install --no-build-isolation /tmp/ext/FlexGEMM
+RUN pip install --no-build-isolation /app/TRELLIS.2/o-voxel \
+ && rm -rf /tmp/ext
+
+# 5. Server deps. pytest is here for the build-time gate at the bottom of this
+# file: the request policy, config rewrite and GLB packing are unit tested during
+# `docker build`, so a broken one 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" \
+ "pytest>=8.0.0"
+
+WORKDIR /app
+COPY worker_security.py request_policy.py storage_backend.py instance_health.py \
+ pipeline_config.py glb_pack.py main.py /app/
+COPY test_request_policy.py test_storage_backend.py test_instance_health.py \
+ test_pipeline_config.py test_glb_pack.py test_app_contract.py /app/
+
+# Build-time gate, neither half of which needs a GPU: the pure-logic tests, then
+# the served contract against the exact dependency set that will run.
+RUN python3 -m pytest /app/test_request_policy.py /app/test_storage_backend.py \
+ /app/test_instance_health.py /app/test_pipeline_config.py /app/test_glb_pack.py -q \
+ && python3 /app/test_app_contract.py
+
+EXPOSE 8080
+
+CMD ["uvicorn", "main:app", \
+ "--host", "0.0.0.0", \
+ "--port", "8080", \
+ "--workers", "1", \
+ "--timeout-keep-alive", "300"]
diff --git a/workers/model-trellis2/README.md b/workers/model-trellis2/README.md
new file mode 100644
index 000000000..9df62d806
--- /dev/null
+++ b/workers/model-trellis2/README.md
@@ -0,0 +1,198 @@
+# model-trellis2: single image to PBR 3D asset (TRELLIS.2)
+
+FastAPI inference service that turns **one image into a PBR-textured GLB** with
+[Microsoft TRELLIS.2](https://github.com/microsoft/TRELLIS.2) (4B flow
+transformer over O-Voxel structured latents, MIT license). It is the default
+image-to-3D lane of the Forge (`/forge`, `/api/forge`) and the only default lane
+that serves the European Union, the United Kingdom and South Korea, where the
+Tencent Hunyuan3D license does not apply (see
+[`../model-hunyuan3d/README.md`](../model-hunyuan3d/README.md) and
+`api/_lib/forge-territory.js`).
+
+What a caller gets back:
+
+- A glTF binary with base colour, metallic-roughness and normal maps.
+- **Alpha preserved.** `o_voxel` bakes opacity into the base colour alpha channel
+ but declares the material opaque. `glb_pack.py` flips the material to `BLEND`
+ when enough of the texture is genuinely translucent and leaves it `OPAQUE`
+ otherwise, so glass and foliage render correctly without haloing solid assets.
+- **Meshopt compression** through the pinned `gltfpack` binary (v1.2, checksum
+ verified in the Dockerfile). Quantisation is on, texture compression is off, so
+ the baked PBR maps and alpha stay byte-exact.
+- Three resolutions: `512` (latency lane), `1024` (default), `1536` (maximum
+ detail, cascaded).
+
+Work is asynchronous: `POST /infer` returns `202` with a `task_id`, and the caller
+polls `GET /tasks/{id}` until `status` is `completed`. With `GCS_BUCKET` set the
+GLB lands at `gs://$GCS_BUCKET/raw-meshes/trellis2/{task_id}.glb` and is returned
+as a `storage.googleapis.com` URL. Without it the container writes tasks and
+results under `OUTPUT_DIR` and serves the mesh from `GET /results/{id}.glb`.
+
+## Endpoints
+
+`POST /infer`, `GET /tasks/{id}` and `GET /results/{id}.glb` require
+`Authorization: Bearer $API_KEY`. `GET /health` and `GET /` are unauthenticated:
+they carry no secrets, and the platform reads them to decide whether the lane can
+take work.
+
+### `POST /infer`
+
+```json
+{
+ "images": ["https://example.com/front.png"],
+ "resolution": 1024,
+ "tier": "standard",
+ "seed": 42,
+ "texture_size": 4096,
+ "decimation_target": 1000000,
+ "job_id": "optional-caller-id"
+}
+```
+
+| Field | Meaning |
+|---|---|
+| `images` | One or more `https://` URLs or `data:` URIs. TRELLIS.2 conditions on one image, so the first is used and the task reports `views_used: 1`. URLs are SSRF-checked (no private or link-local hosts). |
+| `resolution` | `512`, `1024` or `1536`. Anything else is a `422`. Wins over `tier`. |
+| `tier` | `draft` (512), `standard` and `high` (1024), `max` (1536). Used only when `resolution` is absent, so forge tiers and explicit resolutions land on the same presets. |
+| `seed` | Reproducible sampling. |
+| `texture_size`, `decimation_target` | Bake overrides, clamped to 512 to 4096 (power of two) and 50k to 2M faces. |
+
+### `GET /tasks/{id}`
+
+```json
+{
+ "task_id": "…",
+ "status": "completed",
+ "result_gcs_url": "https://storage.googleapis.com/…/raw-meshes/trellis2/….glb",
+ "resolution": 1024,
+ "resolution_served": 1024,
+ "alpha_mode": "OPAQUE",
+ "packed": true,
+ "views_used": 1
+}
+```
+
+A request the GPU cannot hold is retried one size down (1536 to 1024 to 512) and
+`resolution_served` reports the step so the platform never pretends a stepped-down
+result was the requested one. `status` is one of `queued`, `processing`,
+`completed`, `failed`.
+
+## Run it and call it
+
+```bash
+# Build and run on a machine with an NVIDIA GPU (24 GB or more).
+docker build -t model-trellis2 workers/model-trellis2
+docker run --gpus all -p 8080:8080 \
+ -e API_KEY=dev-secret -e OUTPUT_DIR=/data \
+ -e WEIGHTS_GCS_URI=gs://three-ws-model-weights/trellis2-4b \
+ -v "$PWD/data:/data" model-trellis2
+
+# Submit and poll.
+TASK=$(curl -s -X POST localhost:8080/infer \
+ -H "Authorization: Bearer dev-secret" -H "content-type: application/json" \
+ -d '{"images":["https://example.com/front.png"],"resolution":1024}' | jq -r .task_id)
+curl -s localhost:8080/tasks/$TASK -H "Authorization: Bearer dev-secret"
+```
+
+Through the platform the same lane is reached with
+`POST /api/forge` using `{"path":"image","backend":"trellis2","resolution":1024}`,
+or implicitly: it is the default for every image-to-3D tier. The catalog
+(`GET /api/forge?catalog`) lists the accepted `resolutions` on the `trellis2`
+backend.
+
+## Environment
+
+| Variable | Default | Purpose |
+|---|---|---|
+| `API_KEY` | none | Shared bearer secret (Secret Manager `avatar-reconstruction-key` on Cloud Run). |
+| `GCS_BUCKET` | unset | Output bucket. Unset uses `OUTPUT_DIR`. |
+| `OUTPUT_DIR` | `/tmp/outputs` | Task and result volume for standalone use. |
+| `WEIGHTS_DIR` | `/weights/trellis2-4b` | Local weight tree (gcsfuse mount on Cloud Run). |
+| `WEIGHTS_GCS_URI` | unset | `gs://` tree. Each sub-model streams to local disk, loads, then is deleted, so peak disk is one checkpoint. The full set (about 15 GiB) does not fit Cloud Run's in-memory filesystem otherwise. |
+| `WEIGHTS_LOCAL_DIR` | `/tmp/trellis2-weights` | Scratch for that streaming. |
+| `MAX_RESOLUTION` | `1536` | Ceiling on the served resolution. |
+| `MAX_CONCURRENT` | `1` | Parallel inferences per instance. One GPU, so instance count is the concurrent-generation count. |
+| `IMAGE_FETCH_TIMEOUT_S` | `30` | Per-attempt image fetch timeout. |
+| `MODEL_LOAD_ATTEMPTS` | `4` | Model-load attempts before the error latches and `/health` returns 503. |
+| `MODEL_LOAD_RETRY_BASE_S`, `MODEL_LOAD_RETRY_CAP_S` | see `main.py` | Load-retry backoff bounds. |
+
+The platform side reads `MODEL_TRELLIS2_URL` (this service's URL) and
+`GCP_RECONSTRUCTION_KEY` (the bearer secret) from the `three-ws-api` environment.
+Until `MODEL_TRELLIS2_URL` is set the lane reports unconfigured and the router
+skips it, so image-to-3D keeps working through the chain behind it.
+
+## Files
+
+| File | Role |
+|---|---|
+| `main.py` | FastAPI app, streaming weight loader, task store, GPU executor. |
+| `request_policy.py` | Resolution presets, tier mapping, bake clamps, fetch-retry policy. Pure logic. |
+| `pipeline_config.py` | Rewrites the upstream `pipeline.json` to the licence-clean model set below. |
+| `glb_pack.py` | Alpha-mode decision and meshopt packing through `gltfpack`. |
+| `stage_weights.sh` | One-time mirror of every upstream weight into `gs://three-ws-model-weights/trellis2-4b`. |
+| `worker_security.py`, `instance_health.py`, `storage_backend.py` | Vendored shared modules, kept byte-identical by `npm run check:vendored`. |
+| `Dockerfile`, `cloudbuild.yaml` | CUDA 12.4 image with the compiled extensions, and the Cloud Build deploy. |
+| `test_*.py` | Unit and contract tests. They also run as the build-time gate inside the Dockerfile. |
+
+## Deploy
+
+GPU worker deploys are owner-gated. The image build compiles four CUDA extensions
+and takes most of an hour on the 32-vCPU builder; the config pins the
+`three-ws-build@` service account.
+
+```bash
+# 1. One time: mirror the weights (idempotent, skips what is already there).
+workers/model-trellis2/stage_weights.sh
+
+# 2. Build, push and deploy.
+gcloud builds submit --config workers/model-trellis2/cloudbuild.yaml \
+ --region us-central1 --project aerial-vehicle-466722-p5 \
+ --substitutions=SHORT_SHA=manual$(date +%s) .
+
+# 3. Point the API at it.
+gcloud run services update three-ws-api --region us-central1 \
+ --update-env-vars MODEL_TRELLIS2_URL=$(gcloud run services describe model-trellis2 \
+ --region us-central1 --format='value(status.url)')
+```
+
+The service runs on one NVIDIA L4 (24 GB) with minimum instances `0`. The
+us-central1 L4 grant is shared by every GPU lane, so a warm floor here is a quota
+decision: the first request after idle pays the weight stream and model load
+(`BACKENDS.trellis2.coldStartSeconds`), and the keep-warm cron does not warm this
+lane by default. Raise the floor with
+`gcloud run services update model-trellis2 --min-instances=1` when quota allows.
+
+## Licence notes
+
+TRELLIS.2 is MIT. Three upstream components were swapped so the whole image is
+commercially usable and nothing sits behind a gate we cannot satisfy:
+
+- **Background removal: BiRefNet (MIT) instead of RMBG-2.0.** RMBG-2.0 is
+ CC BY-NC 4.0, which forbids commercial use.
+- **Image conditioner: DINOv3 ViT-L/16 from an ungated mirror**
+ (`camenduru/dinov3-vitl16-pretrain-lvd1689m`, which carries the DINOv3 licence
+ text, staged at `trellis2-4b/dinov3/LICENSE.md`). The official `facebook/` repo
+ is gated and the platform's Hugging Face token is refused on it. To use the
+ official repo instead, accept the terms on its model page with the token's
+ account, restage `dinov3/` from it, and nothing else changes.
+- **Sparse-structure decoder** is taken from `microsoft/TRELLIS-image-large`
+ (`ss_dec`), as the upstream pipeline references it by that name.
+
+`pipeline_config.py` applies the first two swaps by rewriting the pipeline config
+at load time; the upstream file stays untouched in the weights bucket. **Open licence risk, owner decision: `nvdiffrast`.** The texture-bake rasteriser
+that upstream `o-voxel` requires, NVIDIA's `nvdiffrast`, is under the NVIDIA Source
+Code License (1-Way Commercial). Section 3.3 limits use of the Work to
+non-commercial research or evaluation, with commercial use reserved to NVIDIA. The
+v1 lane (`../model-trellis`) already ships the same dependency, so this worker does
+not widen the exposure, but it does not remove it either. The paths to close it are
+a commercial grant from NVIDIA for `nvdiffrast`, or replacing the bake rasteriser
+with an MIT or Apache implementation. No source or weights are redistributed, only
+generated GLBs.
+
+Known limit: `1536` on a 24 GB L4 is the tightest setting and is unverified until
+the first deployed generation. The worker steps down on out-of-memory and reports
+`resolution_served`, so a caller always sees what it actually received.
+
+Related: [`../model-trellis`](../model-trellis) (TRELLIS v1, the failover behind
+this lane), [`../../docs/forge-pipeline.md`](../../docs/forge-pipeline.md),
+[`../../docs/ops/gcp-model-workers.md`](../../docs/ops/gcp-model-workers.md).
diff --git a/workers/model-trellis2/cloudbuild.yaml b/workers/model-trellis2/cloudbuild.yaml
new file mode 100644
index 000000000..f9d41e4cc
--- /dev/null
+++ b/workers/model-trellis2/cloudbuild.yaml
@@ -0,0 +1,89 @@
+substitutions:
+ _REGION: us-central1
+ _RUN_SA: avatar-reconstruction-sa@aerial-vehicle-466722-p5.iam.gserviceaccount.com
+ _SERVICE: model-trellis2
+ _REPO: model-trellis2
+ _GCS_BUCKET: three-ws-avatar-reconstructions
+ _WEIGHTS_BUCKET: three-ws-model-weights
+ _WEIGHTS_BUCKET_PREFIX: trellis2-4b
+ # Scale-to-zero by default. The us-central1 L4 grant is shared by every GPU
+ # lane and warm pins elsewhere already hold it (docs/ops/gcp-credits-plan.md),
+ # so a warm floor here is a quota decision, not a default. The deploy still
+ # works at 0: the first request pays the weight stream and model load, which
+ # the API reports as a cold start (BACKENDS.trellis2.coldStartSeconds). Raise
+ # it with `gcloud run services update model-trellis2 --min-instances=1` once
+ # the grant allows, or add trellis2 to FORGE_KEEPWARM_LANES.
+ _MIN_INSTANCES: "0"
+ _MAX_INSTANCES: "2"
+
+steps:
+ - id: build
+ name: gcr.io/cloud-builders/docker
+ dir: workers/model-trellis2
+ args:
+ - build
+ - --tag
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - --tag
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+ - --cache-from
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+ - .
+
+ - id: push
+ name: gcr.io/cloud-builders/docker
+ args:
+ - push
+ - --all-tags
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server
+
+ - id: deploy
+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
+ entrypoint: gcloud
+ args:
+ - run
+ - deploy
+ - ${_SERVICE}
+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - --region=${_REGION}
+ - --service-account=${_RUN_SA}
+ - --platform=managed
+ - --port=8080
+ - --gpu=1
+ - --gpu-type=nvidia-l4
+ - --no-gpu-zonal-redundancy
+ - --no-cpu-throttling
+ - --cpu=8
+ - --memory=32Gi
+ - --min-instances=${_MIN_INSTANCES}
+ - --max-instances=${_MAX_INSTANCES}
+ - --timeout=900
+ - --allow-unauthenticated
+ # The checkpoints (about 15 GiB) do not fit the in-memory filesystem next to
+ # the model, so main.py streams them from WEIGHTS_GCS_URI one at a time
+ # (download, load, delete). The gcsfuse volume below is the fallback read
+ # path and carries no cold-start cost until a file is opened.
+ - --add-volume=name=weights,type=cloud-storage,bucket=${_WEIGHTS_BUCKET}
+ - --add-volume-mount=volume=weights,mount-path=/weights
+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},WEIGHTS_DIR=/weights/${_WEIGHTS_BUCKET_PREFIX},MAX_CONCURRENT=1,WEIGHTS_GCS_URI=gs://${_WEIGHTS_BUCKET}/${_WEIGHTS_BUCKET_PREFIX},WEIGHTS_LOCAL_DIR=/tmp/trellis2-weights
+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest
+ # Recycle an instance whose model load is permanently dead. main.py answers
+ # /health with 503 only once the whole load-retry budget is spent, so an
+ # ordinary cold load (200 while loading) is never killed mid-load.
+ - --liveness-probe=httpGet.path=/health,initialDelaySeconds=60,periodSeconds=60,timeoutSeconds=10,failureThreshold=3
+
+images:
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+
+options:
+ machineType: E2_HIGHCPU_32
+ logging: CLOUD_LOGGING_ONLY
+
+# CUDA extension compiles (nvdiffrast, CuMesh, FlexGEMM, o-voxel) push the image
+# build well past Cloud Build's 10-minute default. Give it an hour.
+timeout: 3600s
+
+# The project's default compute SA was deleted: builds must pin the dedicated
+# build account or submits fail with "Unknown service account".
+serviceAccount: projects/aerial-vehicle-466722-p5/serviceAccounts/[email protected]
diff --git a/workers/model-trellis2/glb_pack.py b/workers/model-trellis2/glb_pack.py
new file mode 100644
index 000000000..7de09f033
--- /dev/null
+++ b/workers/model-trellis2/glb_pack.py
@@ -0,0 +1,88 @@
+"""Post-processing for a TRELLIS.2 GLB: keep transparency, then meshopt-compress.
+
+numpy and the stdlib only (the trimesh scene is duck-typed), so the decisions
+unit test without a GPU (test_glb_pack.py).
+
+Two jobs:
+
+ 1. Alpha. o_voxel's to_glb bakes opacity into the base colour texture's alpha
+ channel but always declares the material OPAQUE, so a viewer ignores it and
+ a leaf or a glass pane renders as a solid card. `blend_if_translucent`
+ flips the material to BLEND when the baked alpha is genuinely translucent.
+ 2. Compression. `gltfpack -cc` rewrites the GLB with EXT_meshopt_compression
+ and quantized attributes, the same encoding three.ws avatars ship with, so
+ the viewer's existing MeshoptDecoder reads it. Textures pass through
+ untouched (no -tc), which keeps the baked PBR maps and alpha byte-exact.
+ A failed pack never fails the job: the uncompressed GLB is still a valid
+ asset, so it is returned and the reason is logged.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import subprocess
+import tempfile
+from pathlib import Path
+from typing import Optional
+
+import numpy as np
+
+log = logging.getLogger("glb-pack")
+
+GLTFPACK_BIN = os.environ.get("GLTFPACK_BIN", "gltfpack")
+GLTFPACK_TIMEOUT_S = int(os.environ.get("GLTFPACK_TIMEOUT_S", "300"))
+
+# A texel counts as translucent below this alpha, and the asset only flips to
+# BLEND when enough of the texture is: stray inpainting pixels at UV seams must
+# not turn a solid object into a sorted-transparency one.
+TRANSLUCENT_BELOW = 245
+TRANSLUCENT_MIN_FRACTION = 0.01
+
+
+def alpha_mode_for(alpha: np.ndarray) -> str:
+ """OPAQUE or BLEND for a baked alpha plane (uint8, any shape)."""
+ plane = np.asarray(alpha)
+ if plane.size == 0:
+ return "OPAQUE"
+ translucent = float(np.count_nonzero(plane < TRANSLUCENT_BELOW)) / plane.size
+ return "BLEND" if translucent >= TRANSLUCENT_MIN_FRACTION else "OPAQUE"
+
+
+def blend_if_translucent(mesh) -> str:
+ """Set the mesh material's alphaMode from its baked texture and return it."""
+ material = getattr(getattr(mesh, "visual", None), "material", None)
+ texture = getattr(material, "baseColorTexture", None)
+ if material is None or texture is None or getattr(texture, "mode", "") != "RGBA":
+ return "OPAQUE"
+ mode = alpha_mode_for(np.asarray(texture)[..., 3])
+ material.alphaMode = mode
+ return mode
+
+
+def compress(glb: bytes, gltfpack_bin: Optional[str] = None) -> tuple[bytes, bool]:
+ """Meshopt-compress a GLB. Returns (bytes, compressed)."""
+ binary = gltfpack_bin or GLTFPACK_BIN
+ with tempfile.TemporaryDirectory() as tmp:
+ src = Path(tmp) / "in.glb"
+ dst = Path(tmp) / "out.glb"
+ src.write_bytes(glb)
+ try:
+ subprocess.run(
+ [binary, "-i", str(src), "-o", str(dst), "-cc"],
+ check=True,
+ capture_output=True,
+ timeout=GLTFPACK_TIMEOUT_S,
+ )
+ packed = dst.read_bytes()
+ except FileNotFoundError:
+ log.warning("gltfpack not found at %s; serving the uncompressed GLB", binary)
+ return glb, False
+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
+ detail = getattr(exc, "stderr", b"") or b""
+ log.warning("gltfpack failed (%s %s); serving the uncompressed GLB", type(exc).__name__, detail[-300:])
+ return glb, False
+ if packed[:4] != b"glTF":
+ log.warning("gltfpack produced a non-GLB output; serving the uncompressed GLB")
+ return glb, False
+ return packed, True
diff --git a/workers/model-trellis2/instance_health.py b/workers/model-trellis2/instance_health.py
new file mode 100644
index 000000000..124dbc40a
--- /dev/null
+++ b/workers/model-trellis2/instance_health.py
@@ -0,0 +1,219 @@
+"""Instance self-care for the TRELLIS worker: host memory and task liveness.
+
+Pure stdlib, no torch and no CUDA, so every decision here is unit tested on any
+machine (see test_instance_health.py) and main.py only wires it in.
+
+Why this module exists (production, 2026-10-03 to 2026-10-08):
+
+ * The single warm L4 instance was OOM-killed twelve times in five days
+ ("Container terminated on signal 9"). Cloud Run's memory utilization for
+ the revision climbed in steps after each heavy job (0.46 -> 0.56 -> 0.71 ->
+ 0.81 -> 0.88 -> 0.91) and never came back down, then a mesh postprocess
+ (decimate, invisible-face removal, UV unwrap, texture bake) pushed it past
+ the 32 GiB ceiling, which is the most memory Cloud Run gives an L4 instance.
+ That is glibc keeping freed heap in per-thread arenas: the pipeline runs in
+ executor threads, each of which grows its own arena, and nothing hands the
+ freed pages back to the kernel.
+ * Every kill took the in-flight job with it, and the queued job behind it.
+ Their durable GCS records stayed "running" until a 30 minute orphan window
+ expired, long after the caller's poll budget, so the forge's lane failover
+ never saw a failure to act on and the user just watched a spinner.
+
+The fixes are split by what they guard against:
+
+ trim_heap() returns freed heap to the kernel after every job.
+ read_memory() reports what the instance actually holds, so each job
+ logs its footprint and the recycle guard has a number.
+ should_recycle() decides when an instance has ratcheted far enough that
+ it should restart BETWEEN jobs rather than die inside one.
+ task_is_orphaned() lets a heartbeat-refreshed record expire in minutes, not
+ half an hour, once its runner is gone.
+"""
+
+from __future__ import annotations
+
+import ctypes
+import ctypes.util
+import os
+from dataclasses import dataclass
+from typing import Optional
+
+# How often a live task refreshes its durable record, and how long a queued or
+# running record may go without a refresh before it is declared orphaned. Six
+# missed beats is far beyond any scheduling hiccup on a healthy instance, and
+# still well inside the forge client's ~300 s poll budget, so the failure lands
+# while a client is still listening and the lane failover can redispatch.
+HEARTBEAT_SECS = 30.0
+ORPHAN_AFTER_SECS = 180.0
+
+# Recycle once the instance holds this share of its memory limit after a job...
+RECYCLE_FRACTION = float(os.environ.get("MEMORY_RECYCLE_FRACTION", "0.80"))
+# ...and only if it has grown at least this much past its post-load baseline. The
+# growth floor is what stops a mismeasured or simply large baseline from turning
+# into a restart after every single job.
+RECYCLE_MIN_GROWTH = float(os.environ.get("MEMORY_RECYCLE_MIN_GROWTH", "0.15"))
+
+_CGROUP_V2 = "/sys/fs/cgroup"
+_CGROUP_V1 = "/sys/fs/cgroup/memory"
+_MEMINFO = "/proc/meminfo"
+
+
+@dataclass(frozen=True)
+class MemorySample:
+ used_bytes: int
+ limit_bytes: int
+ source: str
+
+ @property
+ def fraction(self) -> float:
+ return self.used_bytes / self.limit_bytes if self.limit_bytes else 0.0
+
+ def describe(self) -> str:
+ gib = 1024 ** 3
+ return (
+ f"{self.used_bytes / gib:.1f}/{self.limit_bytes / gib:.1f} GiB "
+ f"({self.fraction:.0%}, {self.source})"
+ )
+
+
+def _read(path: str) -> Optional[str]:
+ try:
+ with open(path, encoding="ascii") as fh:
+ return fh.read()
+ except OSError:
+ return None
+
+
+def _stat_fields(text: str) -> dict[str, int]:
+ fields: dict[str, int] = {}
+ for line in text.splitlines():
+ parts = line.split()
+ if len(parts) >= 2 and parts[1].isdigit():
+ fields[parts[0].rstrip(":")] = int(parts[1])
+ return fields
+
+
+def _from_cgroup_v2(root: str) -> Optional[MemorySample]:
+ stat, limit = _read(os.path.join(root, "memory.stat")), _read(os.path.join(root, "memory.max"))
+ if stat is None or limit is None or not limit.strip().isdigit():
+ return None
+ fields = _stat_fields(stat)
+ if "anon" not in fields:
+ return None
+ # anon is the process heap; shmem is tmpfs, which is where Cloud Run's
+ # in-memory filesystem (and so the staged weights in /tmp) is charged.
+ # Page cache is left out on purpose: the kernel reclaims it before it OOMs.
+ return MemorySample(fields["anon"] + fields.get("shmem", 0), int(limit.strip()), "cgroup2")
+
+
+def _from_cgroup_v1(root: str) -> Optional[MemorySample]:
+ stat = _read(os.path.join(root, "memory.stat"))
+ limit = _read(os.path.join(root, "memory.limit_in_bytes"))
+ if stat is None or limit is None or not limit.strip().isdigit():
+ return None
+ fields = _stat_fields(stat)
+ if "total_rss" not in fields:
+ return None
+ limit_bytes = int(limit.strip())
+ # An unlimited v1 group reports a sentinel near 2**63; it says nothing about
+ # this instance's ceiling, so defer to /proc/meminfo instead.
+ if limit_bytes >= 1 << 60:
+ return None
+ return MemorySample(fields["total_rss"] + fields.get("total_shmem", 0), limit_bytes, "cgroup1")
+
+
+def _from_meminfo(path: str) -> Optional[MemorySample]:
+ text = _read(path)
+ if text is None:
+ return None
+ fields = _stat_fields(text)
+ total, available = fields.get("MemTotal"), fields.get("MemAvailable")
+ if not total or available is None:
+ return None
+ # /proc/meminfo is in KiB. MemAvailable already discounts reclaimable cache.
+ return MemorySample((total - available) * 1024, total * 1024, "meminfo")
+
+
+def read_memory(
+ cgroup_v2_root: str = _CGROUP_V2,
+ cgroup_v1_root: str = _CGROUP_V1,
+ meminfo_path: str = _MEMINFO,
+) -> Optional[MemorySample]:
+ """Best available view of the memory this instance holds against its limit.
+
+ Never raises. Returns None when no source is readable, and every caller
+ treats None as "unknown", which never triggers a recycle.
+ """
+ for reader, arg in (
+ (_from_cgroup_v2, cgroup_v2_root),
+ (_from_cgroup_v1, cgroup_v1_root),
+ (_from_meminfo, meminfo_path),
+ ):
+ try:
+ sample = reader(arg)
+ except (ValueError, ZeroDivisionError):
+ sample = None
+ if sample is not None and sample.limit_bytes > 0:
+ return sample
+ return None
+
+
+def should_recycle(
+ current: Optional[MemorySample],
+ baseline: Optional[MemorySample],
+ threshold: float = RECYCLE_FRACTION,
+ min_growth: float = RECYCLE_MIN_GROWTH,
+) -> bool:
+ """True when the instance should restart between jobs.
+
+ Both conditions must hold: the instance is near its ceiling, AND it got
+ there by growing since the model finished loading. Without a baseline (the
+ load has not completed, or memory is unreadable) the answer is always no.
+ """
+ if current is None or baseline is None:
+ return False
+ return current.fraction >= threshold and current.fraction - baseline.fraction >= min_growth
+
+
+_libc = None
+
+
+def trim_heap() -> bool:
+ """Hand freed heap pages back to the kernel (glibc malloc_trim).
+
+ Returns False on a libc without malloc_trim (musl, macOS), where there is
+ nothing to do. Never raises.
+ """
+ global _libc
+ try:
+ if _libc is None:
+ _libc = ctypes.CDLL(ctypes.util.find_library("c") or "libc.so.6")
+ trim = getattr(_libc, "malloc_trim", None)
+ if trim is None:
+ return False
+ trim.argtypes = [ctypes.c_size_t]
+ trim.restype = ctypes.c_int
+ trim(0)
+ return True
+ except OSError:
+ return False
+
+
+def task_is_orphaned(
+ status: Optional[str],
+ updated_at: object,
+ now: float,
+ orphan_after: float = ORPHAN_AFTER_SECS,
+) -> bool:
+ """True when a queued or running record has gone stale.
+
+ A live runner refreshes updated_at every HEARTBEAT_SECS, so a record that
+ has not moved for orphan_after seconds belongs to an instance that died.
+ A record with no usable timestamp cannot prove it is alive, so it counts as
+ orphaned too. Terminal and unknown statuses never are.
+ """
+ if status not in ("queued", "running"):
+ return False
+ if isinstance(updated_at, bool) or not isinstance(updated_at, (int, float)):
+ return True
+ return now - updated_at > orphan_after
diff --git a/workers/model-trellis2/main.py b/workers/model-trellis2/main.py
new file mode 100644
index 000000000..160d09d52
--- /dev/null
+++ b/workers/model-trellis2/main.py
@@ -0,0 +1,884 @@
+"""
+TRELLIS.2 inference service: single image to a PBR-textured 3D asset (Microsoft,
+MIT license; 4B flow transformer over O-Voxel structured latents).
+
+API contract (consumed by the Forge router, same shape as workers/model-trellis):
+ POST /infer { images: [data-uri|url, ...], resolution?: 512|1024|1536,
+ tier?: str, seed?: int, texture_size?: int,
+ decimation_target?: int, body_type?: str, job_id?: str }
+ -> 202 { task_id, status: "queued" }
+
+ TRELLIS.2 conditions on ONE image. When several are sent the first is used and
+ the task record reports views_used: 1.
+
+ resolution picks the O-Voxel grid (512 | 1024 | 1536). tier (draft | standard |
+ high | max) is accepted for lane parity and maps to a resolution when none is
+ sent. The default is 1024. A request the GPU cannot hold is retried one size
+ down, and the task record reports resolution_served so the step-down is visible.
+
+ GET /tasks/:id -> { task_id, status, result_gcs_url?, result_url?, resolution?,
+ resolution_served?, alpha_mode?, packed?, error? }
+
+ GET /results/:id.glb -> generated GLB when OUTPUT_DIR local storage is active
+
+ GET /health -> { ok, model, gpu_available, resolutions, load_error,
+ load_attempts }. 503 with ok:false once the model load has
+ spent its retry budget, so a dead instance is drained.
+
+ GET / -> { service, model, ready, endpoints }. Unauthenticated
+ descriptor for the platform's warmth probe.
+
+Weights: gs://three-ws-model-weights/trellis2-4b (workers/model-trellis2/stage_weights.sh).
+
+Environment variables (README.md carries the full table):
+ API_KEY shared bearer secret
+ GCS_BUCKET optional Cloud Storage bucket for output meshes
+ OUTPUT_DIR local task and result volume when GCS_BUCKET is unset
+ WEIGHTS_DIR local weight tree (default: /weights/trellis2-4b)
+ WEIGHTS_GCS_URI optional gs:// tree; each sub-model streams to local disk,
+ loads, and is deleted, so peak disk is one checkpoint
+ WEIGHTS_LOCAL_DIR scratch for that streaming (default: /tmp/trellis2-weights)
+ MAX_RESOLUTION ceiling on the served resolution (default: 1536)
+ MAX_CONCURRENT max parallel inferences (default: 1)
+ IMAGE_FETCH_TIMEOUT_S per-attempt image fetch timeout (default: 30)
+ MODEL_LOAD_ATTEMPTS model-load attempts before the error latches (default: 4)
+ MODEL_LOAD_RETRY_BASE_S / MODEL_LOAD_RETRY_CAP_S load-retry backoff bounds
+"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import gc
+import io
+import json
+import logging
+import os
+import shutil
+import signal
+import time
+import uuid
+
+import httpx
+
+# TRELLIS.2 reads its attention and sparse-conv backends from the environment at
+# import time. The Dockerfile sets these as ENV; default them here too so a bare
+# env still loads. xformers avoids the flash-attn source compile, and the
+# expandable-segments allocator lowers fragmentation across the cascade stages.
+os.environ.setdefault("ATTN_BACKEND", "xformers")
+os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
+from contextlib import asynccontextmanager
+from pathlib import Path
+from typing import Optional
+from urllib.parse import urlsplit
+
+import torch
+from fastapi import FastAPI, HTTPException, Header, BackgroundTasks, Response
+from fastapi.responses import FileResponse
+from google.api_core.exceptions import NotFound
+from google.cloud import storage
+from PIL import Image
+from pydantic import BaseModel, Field
+
+import glb_pack
+import pipeline_config
+from request_policy import (
+ DEFAULT_RESOLUTION,
+ FETCH_ATTEMPTS,
+ PIPELINE_TYPES,
+ RESOLUTIONS,
+ bake_params,
+ call_with_retry,
+ clamp_to_ceiling,
+ resolve_resolution,
+ step_down,
+)
+from worker_security import (
+ UnsafeUrlError,
+ fetch_remote_bytes,
+ require_api_key,
+ safe_error,
+)
+from storage_backend import LocalStorage
+from instance_health import (
+ HEARTBEAT_SECS,
+ MemorySample,
+ read_memory,
+ should_recycle,
+ task_is_orphaned,
+ trim_heap,
+)
+
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s %(levelname)s %(name)s %(message)s",
+)
+log = logging.getLogger("trellis2")
+
+API_KEY = os.environ["API_KEY"]
+GCS_BUCKET = os.environ.get("GCS_BUCKET", "").strip()
+OUTPUT_DIR = os.environ.get("OUTPUT_DIR", "/output")
+WEIGHTS_DIR = os.environ.get("WEIGHTS_DIR", "/weights/trellis2-4b")
+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "1"))
+MAX_RESOLUTION = int(os.environ.get("MAX_RESOLUTION", str(max(RESOLUTIONS))))
+# The 15 GiB checkpoint tree does not fit Cloud Run's in-memory filesystem next
+# to a 32 GiB job budget, and the Cloud Storage FUSE mount stalls on the random
+# reads safetensors makes ("stalled read-req cancelled"). So with WEIGHTS_GCS_URI
+# set, each sub-model streams to local disk with plain sequential GETs, loads,
+# and is deleted before the next one starts. Unset (an NGC container with the
+# tree on a mounted volume), the pipeline loads straight from WEIGHTS_DIR.
+WEIGHTS_GCS_URI = os.environ.get("WEIGHTS_GCS_URI", "").rstrip("/")
+WEIGHTS_LOCAL_DIR = os.environ.get("WEIGHTS_LOCAL_DIR", "/tmp/trellis2-weights")
+CONFIG_DIR = os.path.join(WEIGHTS_LOCAL_DIR, "config")
+AUX_DIR = os.path.join(WEIGHTS_LOCAL_DIR, "aux")
+MODEL_LOAD_ATTEMPTS = int(os.environ.get("MODEL_LOAD_ATTEMPTS", "4"))
+MODEL_LOAD_RETRY_BASE_S = float(os.environ.get("MODEL_LOAD_RETRY_BASE_S", "15"))
+MODEL_LOAD_RETRY_CAP_S = float(os.environ.get("MODEL_LOAD_RETRY_CAP_S", "120"))
+
+_pipeline = None
+_bucket: Optional[storage.Bucket] = None
+_local_storage: Optional[LocalStorage] = None
+_sem: Optional[asyncio.Semaphore] = None
+_ready: Optional[asyncio.Event] = None
+_load_error: Optional[str] = None
+_load_attempts = 0
+# In-memory cache only: Cloud Run runs this service across several containers
+# with no session affinity, so the durable source of truth is the
+# `tasks/{task_id}.json` blob in GCS (see _update_task / _resolve_task).
+_tasks: dict[str, dict] = {}
+# One lock per task serializes its durable writes (heartbeat vs status writes).
+_task_locks: dict[str, asyncio.Lock] = {}
+# Tasks this instance has accepted and not yet finished.
+_live_tasks: set[str] = set()
+_memory_baseline: Optional[MemorySample] = None
+_draining = False
+_restart_signalled = False
+
+
+def _gcs_split(uri: str) -> tuple[str, str]:
+ bucket_name, _, prefix = uri[len("gs://"):].partition("/")
+ return bucket_name, prefix.strip("/")
+
+
+def _download_blob(blob, dest: str) -> None:
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
+ if os.path.exists(dest) and blob.size is not None and os.path.getsize(dest) == blob.size:
+ return
+ blob.download_to_filename(dest)
+
+
+def _stage_aux_weights(client: storage.Client, bucket_name: str, prefix: str) -> None:
+ """Copy the DINOv3 conditioner and BiRefNet matte (about 1.7 GB) to local disk.
+
+ They stay resident for the instance's life (the pipeline reloads them to the
+ GPU per job under low_vram), unlike the 4B checkpoints, which stream through.
+ """
+ from concurrent.futures import ThreadPoolExecutor
+
+ wanted = [
+ b
+ for sub in (pipeline_config.DINOV3_DIR, pipeline_config.BIREFNET_DIR)
+ for b in client.list_blobs(bucket_name, prefix=f"{prefix}/{sub}/")
+ if not b.name.endswith("/")
+ ]
+ t0 = time.time()
+ with ThreadPoolExecutor(max_workers=8) as pool:
+ list(pool.map(lambda b: _download_blob(b, os.path.join(AUX_DIR, b.name[len(prefix) + 1:])), wanted))
+ log.info("aux weights staged to %s in %.1fs (%d objects)", AUX_DIR, time.time() - t0, len(wanted))
+
+
+def _install_streaming_loader(client: storage.Client, bucket_name: str, prefix: str) -> None:
+ """Make TRELLIS.2's per-model loader stream each checkpoint from GCS.
+
+ Pipeline.from_pretrained resolves every model as `<CONFIG_DIR>/<name>` and
+ hands that to trellis2.models.from_pretrained. The wrapper fetches
+ `<name>.json` and `<name>.safetensors` from the weights prefix, loads them,
+ and removes them, so disk and RAM never hold more than one checkpoint.
+ """
+ import trellis2.models as t2_models
+
+ original = t2_models.from_pretrained
+ bucket = client.bucket(bucket_name)
+
+ def streaming(path: str, **kwargs):
+ if not path.startswith(CONFIG_DIR + "/"):
+ return original(path, **kwargs)
+ name = path[len(CONFIG_DIR) + 1:]
+ scratch = os.path.join(WEIGHTS_LOCAL_DIR, "stream")
+ local = os.path.join(scratch, name)
+ os.makedirs(os.path.dirname(local), exist_ok=True)
+ try:
+ for ext in (".json", ".safetensors"):
+ blob = bucket.get_blob(f"{prefix}/{name}{ext}")
+ if blob is None:
+ raise FileNotFoundError(f"gs://{bucket_name}/{prefix}/{name}{ext} is not staged")
+ blob.download_to_filename(local + ext)
+ return original(local, **kwargs)
+ finally:
+ shutil.rmtree(scratch, ignore_errors=True)
+
+ t2_models.from_pretrained = streaming
+
+
+def _prepare_pipeline_path() -> str:
+ """Return the config directory TRELLIS.2 loads from, staging what it needs."""
+ if WEIGHTS_GCS_URI.startswith("gs://"):
+ client = storage.Client()
+ bucket_name, prefix = _gcs_split(WEIGHTS_GCS_URI)
+ names = [
+ b.name[len(prefix) + 1:]
+ for b in client.list_blobs(bucket_name, prefix=prefix + "/")
+ if not b.name.endswith("/")
+ ]
+ missing = pipeline_config.missing_weights(names)
+ if missing:
+ raise FileNotFoundError(
+ f"TRELLIS.2 weights incomplete at {WEIGHTS_GCS_URI}: {', '.join(missing)}"
+ )
+ _stage_aux_weights(client, bucket_name, prefix)
+ pipeline_json = client.bucket(bucket_name).blob(f"{prefix}/pipeline.json").download_as_text()
+ pipeline_config.write_local_config(pipeline_json, AUX_DIR, CONFIG_DIR)
+ _install_streaming_loader(client, bucket_name, prefix)
+ return CONFIG_DIR
+
+ root = Path(WEIGHTS_DIR)
+ present = [str(p.relative_to(root)) for p in root.rglob("*") if p.is_file() or p.is_symlink()]
+ missing = pipeline_config.missing_weights(present)
+ if missing:
+ raise FileNotFoundError(f"TRELLIS.2 weights incomplete at {root}: {', '.join(missing)}")
+ pipeline_config.write_local_config((root / "pipeline.json").read_text(), root, CONFIG_DIR)
+ pipeline_config.link_weight_tree(root, CONFIG_DIR)
+ return CONFIG_DIR
+
+
+def _load_pipeline():
+ global _pipeline, _memory_baseline
+ from trellis2.pipelines import Trellis2ImageTo3DPipeline
+
+ path = _prepare_pipeline_path()
+ log.info("Loading TRELLIS.2 pipeline from %s", path)
+ _pipeline = Trellis2ImageTo3DPipeline.from_pretrained(path)
+ _pipeline.cuda()
+ log.info("TRELLIS.2 pipeline loaded")
+ shutil.rmtree(os.path.join(WEIGHTS_LOCAL_DIR, "stream"), ignore_errors=True)
+ trim_heap()
+ _memory_baseline = read_memory()
+ if _memory_baseline is not None:
+ log.info("memory after load: %s", _memory_baseline.describe())
+
+
+async def _load_pipeline_bg():
+ """Load the pipeline off the request path and signal readiness when done.
+
+ Runs the blocking, GPU-bound load in a worker thread so the event loop (and
+ the HTTP port) stay live.
+
+ The load is RETRIED with exponential backoff, and _load_error stays unset
+ while attempts remain, so a job that arrives mid-retry waits on _ready
+ instead of failing against a half-written verdict. Latching the very first
+ exception is what turned a single transient 403 into a 12-hour outage on
+ 2026-09-02: the error was cached in memory, every later task failed against
+ it instantly, and minScale=1 kept that dead instance resident and in
+ rotation. Only once the whole budget is spent does the error latch, and from
+ there /health answers 503 and /infer refuses new work, so the instance is
+ reported down and the caller fails over instead of queueing behind a corpse.
+ """
+ global _load_error, _load_attempts
+ loop = asyncio.get_event_loop()
+ attempts = max(1, MODEL_LOAD_ATTEMPTS)
+ for attempt in range(1, attempts + 1):
+ _load_attempts = attempt
+ try:
+ await loop.run_in_executor(None, _load_pipeline)
+ _load_error = None
+ _ready.set()
+ log.info("TRELLIS.2 pipeline ready (attempt %d)", attempt)
+ return
+ except Exception as exc: # noqa: BLE001 - surfaced via /health + task status
+ if attempt >= attempts:
+ _load_error = safe_error(exc, context="model load")
+ log.error("TRELLIS.2 pipeline load FAILED after %d attempt(s): %s", attempt, exc)
+ return
+ delay = min(MODEL_LOAD_RETRY_BASE_S * (2 ** (attempt - 1)), MODEL_LOAD_RETRY_CAP_S)
+ log.warning(
+ "TRELLIS.2 pipeline load attempt %d/%d failed (%s); retrying in %.0fs",
+ attempt, attempts, exc, delay,
+ )
+ await asyncio.sleep(delay)
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ global _bucket, _local_storage, _sem, _ready
+ if GCS_BUCKET:
+ _bucket = storage.Client().bucket(GCS_BUCKET)
+ _local_storage = None
+ else:
+ _bucket = None
+ _local_storage = LocalStorage(OUTPUT_DIR)
+ _sem = asyncio.Semaphore(MAX_CONCURRENT)
+ _ready = asyncio.Event()
+ # Load the pipeline in the BACKGROUND and yield immediately. uvicorn runs the
+ # ASGI lifespan BEFORE it binds the socket, so a blocking load here would
+ # outlast Cloud Run's startup TCP-probe window on a cold instance and the
+ # revision would be marked failed. Requests that arrive before the load
+ # completes wait on _ready (see _run_job).
+ asyncio.create_task(_load_pipeline_bg())
+ log.info("Service starting, pipeline loading in background (max_concurrent=%d)", MAX_CONCURRENT)
+ yield
+
+
+app = FastAPI(title="model-trellis2", lifespan=lifespan)
+
+
+def _require_api_key(authorization: str) -> None:
+ try:
+ require_api_key(authorization, API_KEY)
+ except PermissionError as exc:
+ 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) -> Image.Image:
+ # RGBA is preserved: TRELLIS.2 uses a supplied alpha channel as the subject
+ # mask and only runs its own background removal for opaque input.
+ mode = "RGBA"
+ if src.startswith("data:image"):
+ b64 = src.split(",", 1)[1]
+ try:
+ 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)
+ 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
+
+
+def _task_blob(task_id: str):
+ if _bucket is None:
+ raise RuntimeError("GCS task storage is not active")
+ return _bucket.blob(f"tasks/{task_id}.json")
+
+
+def _using_gcs() -> bool:
+ return bool(GCS_BUCKET)
+
+
+def _get_local_storage() -> LocalStorage:
+ global _local_storage
+ if _local_storage is None:
+ _local_storage = LocalStorage(OUTPUT_DIR)
+ return _local_storage
+
+
+async def _update_task(task_id: str, **fields) -> dict:
+ """Merge `fields` into the task, then persist to GCS as the source of truth
+ (see the comment on `_tasks`). Called with no fields it is a heartbeat: it
+ only refreshes updated_at, which is what proves the runner is alive."""
+ lock = _task_locks.setdefault(task_id, asyncio.Lock())
+ async with lock:
+ task = _tasks.setdefault(task_id, {"task_id": task_id})
+ task.update(fields)
+ task["updated_at"] = time.time()
+ # Snapshot inside the lock: the upload runs later on an executor thread,
+ # and serializing the live dict there could capture a newer state than
+ # the one this write is ordered as.
+ snapshot = task.copy()
+ loop = asyncio.get_event_loop()
+ if _using_gcs():
+ payload = json.dumps(snapshot)
+ await loop.run_in_executor(
+ None,
+ lambda: _task_blob(task_id).upload_from_string(
+ payload, content_type="application/json"
+ ),
+ )
+ else:
+ await loop.run_in_executor(None, _get_local_storage().write_task, snapshot)
+ return task
+
+
+async def _heartbeat(task_id: str) -> None:
+ """Refresh a live task's durable record until cancelled.
+
+ The poll side (_resolve_task) declares a queued/running record orphaned once
+ it stops moving, so this beat is the runner's proof of life. A failed beat
+ is logged and retried on the next tick; it never touches the job itself.
+ """
+ while True:
+ await asyncio.sleep(HEARTBEAT_SECS)
+ try:
+ await _update_task(task_id)
+ except Exception as exc: # noqa: BLE001 - a missed beat must not kill the job
+ log.warning("[%s] heartbeat write failed: %s", task_id, exc)
+
+
+# A live runner refreshes its record every HEARTBEAT_SECS (see _heartbeat), so a
+# queued/running record that stops moving belongs to an instance that died
+# mid-job (an OOM kill, a crash, a scale-in) and nothing resumes persisted tasks.
+# instance_health.ORPHAN_AFTER_SECS bounds that silence; expiring the record
+# turns an endless client poll into a designed failure the router's poll-time
+# failover can redispatch while the client is still polling.
+_TERMINAL_STATUSES = frozenset({"done", "failed"})
+
+
+async def _resolve_task(task_id: str) -> dict:
+ """Shared poll reader. The instance-local cache is only trusted for
+ terminal records: caching a queued/running record would freeze that
+ status on this instance forever while the runner instance advances the
+ durable GCS record (polls have no session affinity). Non-terminal records
+ are always re-read from GCS and expired once orphaned."""
+ task = _tasks.get(task_id)
+ if task is not None and task.get("status") in _TERMINAL_STATUSES:
+ return task
+ loop = asyncio.get_event_loop()
+ try:
+ if _using_gcs():
+ data = await loop.run_in_executor(None, _task_blob(task_id).download_as_bytes)
+ task = json.loads(data)
+ else:
+ task = await loop.run_in_executor(None, _get_local_storage().read_task, task_id)
+ except (NotFound, FileNotFoundError, ValueError):
+ if task is not None:
+ # Local-only record (the initial persist raced or failed), serve
+ # the in-memory view rather than 404ing a task we know exists.
+ return task
+ raise HTTPException(status_code=404, detail="task not found")
+ except Exception as exc:
+ raise HTTPException(
+ status_code=502, detail=safe_error(exc, context="task lookup")
+ ) from exc
+ status = task.get("status")
+ if status in _TERMINAL_STATUSES:
+ _tasks[task_id] = task
+ return task
+ if task_is_orphaned(status, task.get("updated_at"), time.time()):
+ # Adopt the durable copy so the failure write keeps its fields rather
+ # than whatever partial view this instance had cached.
+ _tasks[task_id] = task
+ failed = await _update_task(
+ task_id,
+ status="failed",
+ error="task orphaned: its runner instance stopped mid-job "
+ "(restart or out of memory); retry the request",
+ )
+ _task_locks.pop(task_id, None)
+ return failed
+ return task
+
+
+async def _run_inference(task_id: str, *args, **kwargs) -> None:
+ """Run one accepted job with a heartbeat on its record, then decide whether
+ this instance should restart before it takes the next one."""
+ _live_tasks.add(task_id)
+ beat = asyncio.create_task(_heartbeat(task_id))
+ try:
+ await _run_job(task_id, *args, **kwargs)
+ finally:
+ beat.cancel()
+ _live_tasks.discard(task_id)
+ _task_locks.pop(task_id, None)
+ _recycle_if_bloated(task_id)
+
+
+def _recycle_if_bloated(task_id: str) -> None:
+ """Restart an idle instance whose memory has ratcheted toward its ceiling.
+
+ Even with the heap trimmed after every job, the native libraries in the
+ postprocess (xatlas, nvdiffrast, open3d) keep some of what they allocate,
+ and this instance can only ever have 32 GiB. Letting it run until a job
+ tips it over is what used to happen: the OOM kill took that job and the one
+ queued behind it. Restarting while idle costs one model load instead.
+
+ Once it decides, the instance drains: /infer refuses new work with a 503 so
+ the caller fails over, jobs already queued here still run, and the restart
+ happens when the last of them finishes. Runs on the event loop with no
+ await, so nothing can be accepted between the idle check and the signal.
+ uvicorn shuts down cleanly on SIGTERM, and Cloud Run starts a fresh instance
+ in its place to hold the warm minimum.
+ """
+ global _draining, _restart_signalled
+ sample = read_memory()
+ if sample is not None:
+ log.info("[%s] memory after job: %s", task_id, sample.describe())
+ if not _draining:
+ if not should_recycle(sample, _memory_baseline):
+ return
+ _draining = True
+ log.warning(
+ "recycling instance: memory %s, up from %s after load; draining %d queued job(s) first",
+ sample.describe(),
+ _memory_baseline.describe() if _memory_baseline else "unknown",
+ len(_live_tasks),
+ )
+ if _live_tasks or _restart_signalled:
+ return
+ _restart_signalled = True
+ log.warning("recycling instance: idle, restarting now")
+ signal.raise_signal(signal.SIGTERM)
+
+
+
+async def _run_job(
+ task_id: str,
+ images: list[str],
+ resolution: int | None = None,
+ tier: str | None = None,
+ seed: int | None = None,
+ texture_size: int | None = None,
+ decimation_target: int | None = None,
+) -> None:
+ # Wait for the background pipeline load before touching the GPU. Warm
+ # instances pass instantly; a cold one waits out the load rather than
+ # NoneType-crashing. A failed load surfaces as a designed task error.
+ if _load_error:
+ await _update_task(task_id, status="failed", error=f"pipeline unavailable: {_load_error}")
+ return
+ try:
+ await asyncio.wait_for(_ready.wait(), timeout=900)
+ except asyncio.TimeoutError:
+ await _update_task(task_id, status="failed", error="pipeline not ready (model load timed out)")
+ return
+ if _load_error:
+ await _update_task(task_id, status="failed", error=f"pipeline unavailable: {_load_error}")
+ return
+
+ requested = clamp_to_ceiling(resolve_resolution(resolution, tier), MAX_RESOLUTION)
+
+ async with _sem:
+ await _update_task(task_id, status="running", resolution=requested)
+ loop = asyncio.get_event_loop()
+ t0 = time.time()
+ try:
+ # TRELLIS.2 conditions on one image; the first is the subject.
+ image = await loop.run_in_executor(None, _decode_image, images[0])
+
+ served = requested
+ while True:
+ try:
+ result = await loop.run_in_executor(
+ None, _generate, image, served, seed, texture_size, decimation_target
+ )
+ break
+ except torch.cuda.OutOfMemoryError:
+ # The GPU class cannot hold this grid. Hand the memory back
+ # and retry one size down rather than failing the job: a
+ # 1024 asset beats an error.
+ await loop.run_in_executor(None, _release_gpu_memory)
+ smaller = step_down(served)
+ if smaller is None:
+ raise
+ log.warning("[%s] out of GPU memory at %d; retrying at %d", task_id, served, smaller)
+ served = smaller
+ glb_bytes, alpha_mode, packed = result
+
+ if _using_gcs():
+ blob_name = f"raw-meshes/trellis2/{task_id}.glb"
+ blob = _bucket.blob(blob_name)
+ await loop.run_in_executor(
+ None,
+ lambda: blob.upload_from_string(glb_bytes, content_type="model/gltf-binary"),
+ )
+ result_fields = {
+ "result_gcs_url": f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"
+ }
+ result_label = result_fields["result_gcs_url"]
+ else:
+ result_path = await loop.run_in_executor(
+ None, _get_local_storage().write_result, task_id, glb_bytes
+ )
+ result_fields = {
+ "result_url": f"/results/{task_id}.glb",
+ "result_path": str(result_path),
+ }
+ result_label = str(result_path)
+
+ elapsed = time.time() - t0
+ await _update_task(
+ task_id,
+ status="done",
+ **result_fields,
+ views_used=1,
+ resolution=requested,
+ resolution_served=served,
+ alpha_mode=alpha_mode,
+ packed=packed,
+ bytes=len(glb_bytes),
+ elapsed_ms=int(elapsed * 1000),
+ )
+ log.info(
+ "[%s] done in %.1fs (resolution=%d served=%d alpha=%s packed=%s) %d bytes -> %s",
+ task_id, elapsed, requested, served, alpha_mode, packed, len(glb_bytes), result_label,
+ )
+
+ 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,
+ status="failed",
+ error=safe_error(exc, context=f"[{task_id}] inference"),
+ elapsed_ms=int((time.time() - t0) * 1000),
+ )
+ finally:
+ # Hand this job's GPU memory back before releasing the semaphore so
+ # the next inference starts against a drained device. Torch's caching
+ # allocator and the native bake libraries hold freed blocks in
+ # reserve, so without this an instance's usable VRAM only shrinks
+ # until every later job fails out of memory while health still passes
+ # (the failure that took the v1 TRELLIS lane down on 2026-09-09).
+ await loop.run_in_executor(None, _release_gpu_memory)
+
+
+def _generate(
+ image: Image.Image,
+ resolution: int,
+ seed: int | None,
+ texture_size: int | None,
+ decimation_target: int | None,
+) -> tuple[bytes, str, bool]:
+ """One synchronous generation: sample, bake to a PBR GLB, keep alpha, pack."""
+ import o_voxel
+
+ outputs = _pipeline.run(
+ image,
+ seed=seed if seed is not None else 42,
+ pipeline_type=PIPELINE_TYPES[resolution],
+ preprocess_image=True,
+ )
+ mesh = outputs[0]
+ mesh.simplify(16777216) # nvdiffrast's face limit
+ bake = bake_params(resolution, texture_size, decimation_target)
+ glb = o_voxel.postprocess.to_glb(
+ vertices=mesh.vertices,
+ faces=mesh.faces,
+ attr_volume=mesh.attrs,
+ coords=mesh.coords,
+ attr_layout=mesh.layout,
+ voxel_size=mesh.voxel_size,
+ aabb=[[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]],
+ decimation_target=bake["decimation_target"],
+ texture_size=bake["texture_size"],
+ remesh=True,
+ remesh_band=1,
+ remesh_project=0,
+ verbose=False,
+ )
+ alpha_mode = glb_pack.blend_if_translucent(glb)
+ raw = glb.export(file_type="glb", extension_webp=True)
+ packed_bytes, packed = glb_pack.compress(raw)
+ return packed_bytes, alpha_mode, packed
+
+
+def _release_gpu_memory() -> None:
+ """Return a finished job's GPU allocations to the driver.
+
+ Blocking, so callers run it in the executor. Safe on CPU-only hosts (the unit
+ tests import this module without a GPU) because every CUDA call is gated on
+ availability.
+ """
+ gc.collect()
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ torch.cuda.ipc_collect()
+ # The host side leaks the same way: each executor thread's glibc arena keeps
+ # the job's freed heap. Hand it back to the kernel (see instance_health).
+ trim_heap()
+
+
+class InferRequest(BaseModel):
+ images: list[str] = Field(..., min_length=1, max_length=6)
+ body_type: str = "neutral"
+ job_id: str | None = None
+ # O-Voxel grid: 512 | 1024 | 1536. Omitted, the tier (or the 1024 default) decides.
+ resolution: int | None = None
+ # draft | standard | high | max, accepted for lane parity with the other
+ # image-to-3D workers. Maps to a resolution when none is sent.
+ tier: str | None = None
+ seed: int | None = None
+ # Optional bake overrides, clamped (power-of-two texture, bounded face budget).
+ texture_size: int | None = None
+ decimation_target: int | None = None
+
+
[email protected]("/infer", status_code=202)
+async def infer(
+ body: InferRequest,
+ background_tasks: BackgroundTasks,
+ authorization: str = Header(...),
+) -> dict:
+ _require_api_key(authorization)
+ # A latched load failure means this instance can never serve this job, so
+ # refuse it at submit time. 503 is what the caller's lane failover reads
+ # (api/forge.js isUpstreamUnavailable -> markLaneUnhealthy), which routes the
+ # request to another backend instead of accepting a job that can only fail.
+ if _load_error:
+ raise HTTPException(status_code=503, detail=f"pipeline unavailable: {_load_error}")
+ if _draining:
+ raise HTTPException(
+ status_code=503,
+ detail="instance restarting to reclaim memory; retry shortly",
+ )
+ task_id = str(uuid.uuid4())
+ # Persist the "queued" record before responding: a poll can reach a different
+ # instance than this one the moment the 202 lands.
+ await _update_task(task_id, status="queued", model="trellis2-4b")
+ background_tasks.add_task(
+ _run_inference,
+ task_id,
+ body.images,
+ body.resolution,
+ body.tier,
+ body.seed,
+ body.texture_size,
+ body.decimation_target,
+ )
+ return {"task_id": task_id, "status": "queued"}
+
+
[email protected]("/tasks/{task_id}")
+async def get_task(task_id: str, authorization: str = Header(...)) -> dict:
+ _require_api_key(authorization)
+ return await _resolve_task(task_id)
+
+
[email protected]("/results/{task_id}.glb")
+async def get_result(task_id: str, authorization: str = Header(...)):
+ """Download a generated GLB from the mounted local output volume."""
+ _require_api_key(authorization)
+ if _using_gcs():
+ raise HTTPException(status_code=404, detail="local result storage is not active")
+ try:
+ path = _get_local_storage().result_path(task_id)
+ except ValueError as exc:
+ raise HTTPException(status_code=404, detail="result not found") from exc
+ if not path.is_file():
+ raise HTTPException(status_code=404, detail="result not found")
+ return FileResponse(path, media_type="model/gltf-binary", filename=path.name)
+
+
+async def root() -> dict:
+ """Service descriptor, and the answer to the platform's warmth ping.
+
+ api/cron/gpu-keepwarm.js holds a scale-to-zero lane resident with an
+ authenticated GET against the worker root and treats any status below 500 as
+ "the container is up". Answering 200 keeps the log honest; routing itself
+ reads /health, which carries the load state this cannot.
+ """
+ return {
+ "service": "model-trellis2",
+ "model": "trellis2-4b",
+ "ready": bool(_ready and _ready.is_set()),
+ "endpoints": [
+ "POST /infer",
+ "GET /tasks/{task_id}",
+ "GET /results/{task_id}.glb",
+ "GET /health",
+ ],
+ }
+
+
+async def health(response: Response) -> dict:
+ """Readiness, answered honestly.
+
+ A spent load budget answers 503: the platform health probe reads that as down
+ (api/_lib/forge-health.js), and a Cloud Run liveness probe pointed here
+ recycles the container. A load still in progress stays 200 so an ordinary
+ cold start is never killed mid-load.
+ """
+ dead = _load_error is not None
+ if dead:
+ response.status_code = 503
+ return {
+ "ok": not dead,
+ "model": "trellis2-4b",
+ "gpu_available": torch.cuda.is_available(),
+ "gpu_name": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,
+ "pipeline_loaded": _pipeline is not None,
+ "ready": bool(_ready and _ready.is_set()),
+ "load_error": _load_error,
+ "load_attempts": _load_attempts,
+ "draining": _draining,
+ "resolutions": [r for r in RESOLUTIONS if r <= MAX_RESOLUTION],
+ "default_resolution": DEFAULT_RESOLUTION,
+ "output_backend": "gcs" if _using_gcs() else "local",
+ "output_dir": None if _using_gcs() else str(_get_local_storage().output_dir),
+ }
diff --git a/workers/model-trellis2/pipeline_config.py b/workers/model-trellis2/pipeline_config.py
new file mode 100644
index 000000000..5efde79b5
--- /dev/null
+++ b/workers/model-trellis2/pipeline_config.py
@@ -0,0 +1,99 @@
+"""Rewrite TRELLIS.2's pipeline.json so every weight loads from the staged tree.
+
+Pure stdlib, no torch, so it unit tests anywhere (test_pipeline_config.py).
+
+Upstream's pipeline.json reaches out to three places we do not want at serve
+time, and one of them is a licence problem:
+
+ * `sparse_structure_decoder` names a repo path in microsoft/TRELLIS-image-large
+ (MIT). We stage that one checkpoint inside the main tree, so the name is
+ rewritten to the staged copy.
+ * `image_cond_model` names the DINOv3 conditioner by Hub id. It is loaded from
+ the staged copy instead, so the load never touches the Hub. (DINOv3 is
+ gated on its original repo; the staged bytes come from an ungated mirror
+ and ship with the DINOv3 License text, see README.md.)
+ * `rembg_model` names briaai/RMBG-2.0, which is licensed CC BY-NC and cannot
+ ship in a commercial product. It is replaced with ZhengPeng7/BiRefNet (MIT),
+ which the same BiRefNet wrapper class loads unchanged.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+from typing import Iterable
+
+# Sub-trees of the staged weights, written by stage_weights.sh.
+SS_DECODER_DIR = "ss_dec/ckpts/ss_dec_conv3d_16l8_fp16"
+DINOV3_DIR = "dinov3"
+BIREFNET_DIR = "birefnet"
+
+REQUIRED_PATHS = (
+ "pipeline.json",
+ "ckpts/ss_flow_img_dit_1_3B_64_bf16.safetensors",
+ "ckpts/shape_dec_next_dc_f16c32_fp16.safetensors",
+ "ckpts/slat_flow_img2shape_dit_1_3B_512_bf16.safetensors",
+ "ckpts/slat_flow_img2shape_dit_1_3B_1024_bf16.safetensors",
+ "ckpts/tex_dec_next_dc_f16c32_fp16.safetensors",
+ "ckpts/slat_flow_imgshape2tex_dit_1_3B_512_bf16.safetensors",
+ "ckpts/slat_flow_imgshape2tex_dit_1_3B_1024_bf16.safetensors",
+ SS_DECODER_DIR + ".safetensors",
+ DINOV3_DIR + "/model.safetensors",
+ DINOV3_DIR + "/config.json",
+ BIREFNET_DIR + "/model.safetensors",
+ BIREFNET_DIR + "/config.json",
+)
+
+
+def missing_weights(present: Iterable[str]) -> list[str]:
+ """Every file the pipeline needs that is not in `present` (relative names)."""
+ have = set(present)
+ return [rel for rel in REQUIRED_PATHS if rel not in have]
+
+
+def localize(config: dict, aux_root: str | os.PathLike[str]) -> dict:
+ """Return a copy of `config` that loads the conditioner and matte locally.
+
+ `aux_root` holds the dinov3/ and birefnet/ directories, which are small
+ enough (about 1.7 GB together) to keep on local disk for the instance's life.
+ """
+ base = str(Path(aux_root))
+ out = json.loads(json.dumps(config))
+ args = out["args"]
+ args["models"]["sparse_structure_decoder"] = SS_DECODER_DIR
+ args["image_cond_model"]["args"]["model_name"] = f"{base}/{DINOV3_DIR}"
+ args["rembg_model"] = {
+ "name": "BiRefNet",
+ "args": {"model_name": f"{base}/{BIREFNET_DIR}"},
+ }
+ return out
+
+
+def write_local_config(
+ pipeline_json: str, aux_root: str | os.PathLike[str], out_dir: str | os.PathLike[str]
+) -> Path:
+ """Write the localized pipeline.json into `out_dir` and return its path."""
+ target = Path(out_dir)
+ target.mkdir(parents=True, exist_ok=True)
+ path = target / "pipeline.json"
+ path.write_text(json.dumps(localize(json.loads(pipeline_json), aux_root), indent=2))
+ return path
+
+
+def link_weight_tree(root: str | os.PathLike[str], out_dir: str | os.PathLike[str]) -> None:
+ """Symlink each top-level entry of a local weight tree into `out_dir`.
+
+ The pipeline resolves every model as `<config dir>/<relative name>`, so a
+ config dir holding the localized pipeline.json plus these links loads
+ straight from a mounted or pre-staged tree.
+ """
+ source = Path(root)
+ target = Path(out_dir)
+ target.mkdir(parents=True, exist_ok=True)
+ for entry in source.iterdir():
+ if entry.name == "pipeline.json":
+ continue
+ link = target / entry.name
+ if not link.exists() and not link.is_symlink():
+ link.symlink_to(entry.resolve())
diff --git a/workers/model-trellis2/request_policy.py b/workers/model-trellis2/request_policy.py
new file mode 100644
index 000000000..70aa3c255
--- /dev/null
+++ b/workers/model-trellis2/request_policy.py
@@ -0,0 +1,193 @@
+"""Request policy for the TRELLIS.2 worker: resolution tiers and transient-fetch retry.
+
+Free of torch, CUDA and the TRELLIS.2 source tree so the decisions that shape
+every generation import and unit test 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. Resolution resolution. A caller sends an optional `resolution` (512, 1024
+ or 1536) and/or a named `tier`; this module turns that into the pipeline
+ type, texture size and decimation target TRELLIS.2 runs with, and says how
+ to step down when the GPU cannot hold the requested size.
+ 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 worth retrying
+ and gives up at once on the ones that are not.
+"""
+
+from __future__ import annotations
+
+from typing import Callable, Optional
+
+import httpx
+
+# Resolution is the O-Voxel grid the shape and texture are generated at. The
+# cascade pipelines solve a coarse 512 structure first, then refine it, which is
+# how TRELLIS.2 reaches 1024 and 1536 inside a 24 GB card.
+RESOLUTIONS = (512, 1024, 1536)
+DEFAULT_RESOLUTION = 1024
+
+PIPELINE_TYPES = {
+ 512: "512",
+ 1024: "1024_cascade",
+ 1536: "1536_cascade",
+}
+
+# What each resolution bakes. Texture size must stay a power of two (the bake
+# builds a mip stack); the decimation target is the face budget handed to the
+# mesh simplifier before UV unwrapping. The 512 lane is the latency lane.
+RESOLUTION_PRESETS = {
+ 512: {"texture_size": 2048, "decimation_target": 300_000},
+ 1024: {"texture_size": 4096, "decimation_target": 1_000_000},
+ 1536: {"texture_size": 4096, "decimation_target": 1_500_000},
+}
+
+# The forge lanes already speak quality tiers; map them onto the resolutions so a
+# tier request and a resolution request land on the same presets.
+TIER_RESOLUTION = {
+ "draft": 512,
+ "standard": 1024,
+ "high": 1024,
+ "max": 1536,
+}
+
+TEXTURE_SIZE_MIN = 512
+TEXTURE_SIZE_MAX = 4096
+DECIMATION_MIN = 50_000
+DECIMATION_MAX = 2_000_000
+
+
+def normalize_tier(tier: Optional[str]) -> Optional[str]:
+ """Lowercase and trim a caller's tier string, or None when none was sent."""
+ if tier is None:
+ return None
+ key = str(tier).strip().lower()
+ return key or None
+
+
+def resolve_resolution(resolution: Optional[int], tier: Optional[str] = None) -> int:
+ """The grid resolution to run at.
+
+ An explicit `resolution` wins and snaps to the nearest supported size (a
+ caller asking for 2048 gets 1536, a 700 gets 512 or 1024 by closeness). With
+ none, the named tier decides, and with neither the platform default applies.
+ An unparseable value falls back to the default rather than failing the job.
+ """
+ if resolution is not None:
+ try:
+ wanted = int(resolution)
+ except (TypeError, ValueError):
+ return DEFAULT_RESOLUTION
+ return min(RESOLUTIONS, key=lambda r: (abs(r - wanted), r))
+ return TIER_RESOLUTION.get(normalize_tier(tier) or "", DEFAULT_RESOLUTION)
+
+
+def clamp_to_ceiling(resolution: int, ceiling: Optional[int]) -> int:
+ """Cap a resolution at what this deployment's GPU class can serve."""
+ if not ceiling:
+ return resolution
+ allowed = [r for r in RESOLUTIONS if r <= ceiling]
+ return min(resolution, max(allowed)) if allowed else RESOLUTIONS[0]
+
+
+def step_down(resolution: int) -> Optional[int]:
+ """The next smaller resolution to retry at after an out-of-memory failure."""
+ smaller = [r for r in RESOLUTIONS if r < resolution]
+ return max(smaller) if smaller else None
+
+
+def bake_params(
+ resolution: int,
+ texture_size: Optional[int] = None,
+ decimation_target: Optional[int] = None,
+) -> dict:
+ """The clamped bake parameters for a resolution plus optional overrides.
+
+ texture_size snaps DOWN to a power of two inside the envelope: the texture
+ bake hard-fails on any other extent. Unparseable overrides fall back to the
+ resolution's preset.
+ """
+ preset = RESOLUTION_PRESETS[resolution]
+
+ def number(raw, fallback, lo, hi):
+ if raw is None:
+ return fallback
+ try:
+ value = int(raw)
+ except (TypeError, ValueError):
+ return fallback
+ return max(lo, min(hi, value))
+
+ tex = number(texture_size, preset["texture_size"], TEXTURE_SIZE_MIN, TEXTURE_SIZE_MAX)
+ tex = 1 << (tex.bit_length() - 1)
+ return {
+ "texture_size": tex,
+ "decimation_target": number(
+ decimation_target, preset["decimation_target"], DECIMATION_MIN, DECIMATION_MAX
+ ),
+ }
+
+
+# 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-trellis2/stage_weights.sh b/workers/model-trellis2/stage_weights.sh
new file mode 100755
index 000000000..dffff9694
--- /dev/null
+++ b/workers/model-trellis2/stage_weights.sh
@@ -0,0 +1,70 @@
+#!/usr/bin/env bash
+# Stage every weight TRELLIS.2 needs into gs://three-ws-model-weights, streaming
+# straight from the source to the bucket (no local disk). Idempotent: an object
+# that already exists at the expected size is skipped.
+#
+# workers/model-trellis2/stage_weights.sh
+#
+# Layout written (the worker's WEIGHTS_GCS_URI points at the first prefix):
+# gs://<bucket>/trellis2-4b/ microsoft/TRELLIS.2-4B (MIT)
+# gs://<bucket>/trellis2-4b/ss_dec/ ss_dec_conv3d_16l8_fp16 from
+# microsoft/TRELLIS-image-large (MIT);
+# pipeline.json names it by repo path
+# gs://<bucket>/trellis2-4b/dinov3/ camenduru/dinov3-vitl16-pretrain-lvd1689m,
+# an ungated mirror of the DINOv3 ViT-L/16
+# weights that ships the DINOv3 LICENSE.md.
+# The official facebook repo is gated; to
+# use it instead, mirror it here with an
+# HF_TOKEN whose account accepted the terms.
+# gs://<bucket>/trellis2-4b/birefnet/ ZhengPeng7/BiRefNet (MIT), the background
+# matte. Replaces the upstream default,
+# RMBG-2.0, whose CC BY-NC licence excludes
+# commercial use.
+set -euo pipefail
+
+BUCKET="${WEIGHTS_BUCKET:-three-ws-model-weights}"
+PREFIX="${WEIGHTS_PREFIX:-trellis2-4b}"
+DEST="gs://${BUCKET}/${PREFIX}"
+AUTH=()
+if [[ -n "${HF_TOKEN:-}" ]]; then AUTH=(-H "Authorization: Bearer ${HF_TOKEN}"); fi
+
+list_repo() { # <repo> -> "path size" lines
+ curl -fsS "${AUTH[@]}" "https://huggingface.co/api/models/$1?blobs=true" \
+ | python3 -I -c 'import json,sys
+for s in json.load(sys.stdin)["siblings"]:
+ print(s["rfilename"], s.get("size") or 0)'
+}
+
+remote_size() { gcloud storage objects describe "$1" --format='value(size)' 2>/dev/null || true; }
+
+copy_one() { # <repo> <src path> <size> <dest uri>
+ local repo="$1" path="$2" size="$3" dest="$4"
+ if [[ "$(remote_size "$dest")" == "$size" && "$size" != "0" ]]; then
+ echo "skip $dest"
+ return
+ fi
+ echo "copy $repo/$path -> $dest ($size bytes)"
+ curl -fsSL "${AUTH[@]}" "https://huggingface.co/${repo}/resolve/main/${path}" \
+ | gcloud storage cp - "$dest" --quiet
+ local got
+ got="$(remote_size "$dest")"
+ if [[ "$size" != "0" && "$got" != "$size" ]]; then
+ echo "FAIL $dest: expected $size bytes, bucket has ${got:-none}" >&2
+ exit 1
+ fi
+}
+
+mirror_repo() { # <repo> <dest prefix> [path regex]
+ local repo="$1" dest="$2" only="${3:-.}"
+ while read -r path size; do
+ [[ "$path" =~ $only ]] || continue
+ [[ "$path" == .gitattributes ]] && continue
+ copy_one "$repo" "$path" "$size" "${dest}/${path}"
+ done < <(list_repo "$repo")
+}
+
+mirror_repo microsoft/TRELLIS.2-4B "${DEST}"
+mirror_repo microsoft/TRELLIS-image-large "${DEST}/ss_dec" '^ckpts/ss_dec_conv3d_16l8_fp16\.'
+mirror_repo camenduru/dinov3-vitl16-pretrain-lvd1689m "${DEST}/dinov3"
+mirror_repo ZhengPeng7/BiRefNet "${DEST}/birefnet"
+echo "trellis2 weights staged at ${DEST}"
diff --git a/workers/model-trellis2/storage_backend.py b/workers/model-trellis2/storage_backend.py
new file mode 100644
index 000000000..fcf7fc1a1
--- /dev/null
+++ b/workers/model-trellis2/storage_backend.py
@@ -0,0 +1,63 @@
+"""Storage primitives for the standalone TRELLIS container.
+
+Production persists tasks and results in GCS because requests can move between
+Cloud Run instances. An NGC user runs one container with a mounted output
+volume, so the same service needs a local backend with atomic writes and strict
+task-id validation.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import uuid
+from pathlib import Path
+
+
+def normalize_task_id(task_id: str) -> str:
+ """Return a canonical UUID or reject a value that could escape the volume."""
+ parsed = uuid.UUID(task_id)
+ canonical = str(parsed)
+ if task_id.lower() != canonical:
+ raise ValueError("task_id must be a canonical UUID")
+ return canonical
+
+
+class LocalStorage:
+ """Durable task metadata and GLB results on a mounted local volume."""
+
+ def __init__(self, output_dir: str | os.PathLike[str]):
+ self.output_dir = Path(output_dir).expanduser().resolve()
+ self.tasks_dir = self.output_dir / "tasks"
+ self.results_dir = self.output_dir / "results"
+ self.tasks_dir.mkdir(parents=True, exist_ok=True)
+ self.results_dir.mkdir(parents=True, exist_ok=True)
+
+ def task_path(self, task_id: str) -> Path:
+ return self.tasks_dir / f"{normalize_task_id(task_id)}.json"
+
+ def result_path(self, task_id: str) -> Path:
+ return self.results_dir / f"{normalize_task_id(task_id)}.glb"
+
+ @staticmethod
+ def _atomic_write(path: Path, data: bytes) -> None:
+ temporary = path.with_suffix(path.suffix + ".tmp")
+ with temporary.open("wb") as handle:
+ handle.write(data)
+ handle.flush()
+ os.fsync(handle.fileno())
+ temporary.replace(path)
+
+ def write_task(self, task: dict) -> Path:
+ path = self.task_path(str(task["task_id"]))
+ payload = json.dumps(task, separators=(",", ":"), sort_keys=True).encode("utf-8")
+ self._atomic_write(path, payload)
+ return path
+
+ def read_task(self, task_id: str) -> dict:
+ return json.loads(self.task_path(task_id).read_text(encoding="utf-8"))
+
+ def write_result(self, task_id: str, glb_bytes: bytes) -> Path:
+ path = self.result_path(task_id)
+ self._atomic_write(path, glb_bytes)
+ return path
diff --git a/workers/model-trellis2/test_app_contract.py b/workers/model-trellis2/test_app_contract.py
new file mode 100644
index 000000000..972b6d58f
--- /dev/null
+++ b/workers/model-trellis2/test_app_contract.py
@@ -0,0 +1,158 @@
+"""Smoke test for the served contract, run INSIDE the built image (it needs
+torch, FastAPI, PIL, google-cloud-storage, and the cloned TRELLIS.2 tree on
+PYTHONPATH):
+
+ docker build -t model-trellis2 workers/model-trellis2
+ docker run --rm model-trellis2 python3 test_app_contract.py
+
+It needs no GPU, no weights, and no GCP credentials: the ASGI lifespan (which
+opens the GCS client and starts the model load) is deliberately not run, so every
+assertion below is about request handling, not inference.
+
+What it proves:
+
+ 1. The TRELLIS.2 import chain resolves, including the compiled CuMesh,
+ FlexGEMM, O-Voxel and nvdiffrast extensions the GLB bake needs. A missing
+ extension otherwise surfaces minutes after the port opens, as a revision that
+ answers /health with a load_error and can never generate.
+ 2. The whole app module imports.
+ 3. The auth boundary rejects a wrong bearer on both authenticated routes.
+ 4. The unauthenticated probe surfaces (/ and /health) answer, and a dead
+ pipeline says so on both /health and /infer so the caller fails over.
+ 5. Request validation rejects an empty or oversized images array.
+ 6. The image decoder keeps an RGBA cutout's alpha and refuses everything the
+ SSRF guard should refuse.
+"""
+
+from __future__ import annotations
+
+import base64
+import io
+import os
+import sys
+
+os.environ.setdefault("API_KEY", "smoke-test-key")
+os.environ.setdefault("GCS_BUCKET", "smoke-test-bucket")
+
+KEY = os.environ["API_KEY"]
+
+PASSED = 0
+
+
+def check(name: str, condition: bool, detail: str = "") -> None:
+ global PASSED
+ if not condition:
+ print(f"FAIL {name} {detail}")
+ sys.exit(1)
+ PASSED += 1
+ print(f"ok {name}")
+
+
+def png_data_uri(color=(20, 20, 20, 255), size=(24, 24)) -> str:
+ from PIL import Image
+
+ img = Image.new("RGBA", size, color)
+ buf = io.BytesIO()
+ img.save(buf, format="PNG")
+ return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()
+
+
+# Libraries the NVIDIA container runtime mounts into a GPU instance. The image
+# cannot ship them, so their absence on the CPU-only builder is expected.
+_GPU_DRIVER_LIBS = ("libcuda.so", "libnvidia", "libnvrtc")
+
+
+def _is_gpu_driver_absence(exc: BaseException) -> bool:
+ text = str(exc)
+ if "cannot open shared object file" in text:
+ return any(lib in text for lib in _GPU_DRIVER_LIBS)
+ lowered = text.lower()
+ return "cuda" in lowered or "nvidia driver" in lowered or "no gpu" in lowered
+
+
+def main() -> int:
+ try:
+ from trellis2.pipelines import Trellis2ImageTo3DPipeline # noqa: F401
+ import o_voxel.postprocess # noqa: F401
+ import cumesh # noqa: F401
+ import flex_gemm # noqa: F401
+
+ check("trellis2 import chain resolves", True)
+ except ModuleNotFoundError as exc:
+ check("trellis2 import chain resolves", False, str(exc))
+ except Exception as exc: # noqa: BLE001 - classified below
+ if _is_gpu_driver_absence(exc):
+ print(f"skip trellis2 import chain (no GPU on this host): {type(exc).__name__}: {exc}")
+ else:
+ check("trellis2 import chain resolves", False, f"{type(exc).__name__}: {exc}")
+
+ import main as app_module
+ from fastapi.testclient import TestClient
+
+ client = TestClient(app_module.app)
+
+ bad = {"Authorization": "Bearer wrong-key"}
+ res = client.get("/tasks/does-not-exist", headers=bad)
+ check("GET /tasks rejects a wrong bearer", res.status_code == 401, f"got {res.status_code}")
+ res = client.post("/infer", headers=bad, json={"images": [png_data_uri()]})
+ check("POST /infer rejects a wrong bearer", res.status_code == 401, f"got {res.status_code}")
+
+ res = client.get("/health")
+ body = res.json()
+ check("GET /health answers 200", res.status_code == 200, f"got {res.status_code}")
+ check("health names the model", body.get("model") == "trellis2-4b", str(body)[:120])
+ check("health lists the resolutions", body.get("resolutions") == [512, 1024, 1536], str(body.get("resolutions")))
+ res = client.get("/")
+ body = res.json()
+ check("GET / answers 200 for the keep-warm ping", res.status_code == 200, f"got {res.status_code}")
+ check("root names the service", body.get("service") == "model-trellis2", str(body)[:120])
+ check("root lists the working endpoints", "POST /infer" in body.get("endpoints", []), str(body)[:160])
+
+ # A dead instance must SAY it is dead, on both surfaces. A latched load error
+ # that /health ignores and /infer keeps accepting past is how the v1 TRELLIS
+ # lane lost 70 generations on 2026-09-02 while every health view stayed green.
+ app_module._load_error = "internal error (ref deadbeefcafe)"
+ try:
+ res = client.get("/health")
+ body = res.json()
+ check("a dead pipeline makes /health answer 503", res.status_code == 503, f"got {res.status_code}")
+ check("a dead pipeline makes /health report ok:false", body.get("ok") is False, str(body)[:160])
+ check("health surfaces the load error", "deadbeefcafe" in str(body.get("load_error")), str(body)[:160])
+ res = client.post("/infer", headers={"Authorization": f"Bearer {KEY}"}, json={"images": [png_data_uri()]})
+ check("a dead pipeline makes /infer refuse with 503", res.status_code == 503, f"got {res.status_code}")
+ finally:
+ app_module._load_error = None
+ res = client.get("/health")
+ check("a live pipeline still answers /health 200", res.status_code == 200, f"got {res.status_code}")
+ check("a live pipeline reports ok:true", res.json().get("ok") is True, str(res.json())[:160])
+
+ good = {"Authorization": f"Bearer {KEY}"}
+ res = client.post("/infer", headers=good, json={"images": []})
+ check("POST /infer rejects an empty images array", res.status_code == 422, f"got {res.status_code}")
+ res = client.post("/infer", headers=good, json={"images": [png_data_uri()] * 7})
+ check("POST /infer rejects more than six views", res.status_code == 422, f"got {res.status_code}")
+
+ img = app_module._decode_image(png_data_uri())
+ check("data uri decodes with its alpha channel", img.mode == "RGBA" and img.size == (24, 24), f"{img.mode} {img.size}")
+
+ for label, src in [
+ ("cleartext http", "http://example.com/a.png"),
+ ("bare path", "/etc/passwd"),
+ ("loopback https", "https://127.0.0.1/a.png"),
+ ("cloud metadata", "https://169.254.169.254/latest/meta-data/"),
+ ("corrupt data uri", "data:image/png;base64,not-base64!!"),
+ ]:
+ try:
+ app_module._decode_image(src)
+ check(f"refuses {label}", False, "no exception raised")
+ except app_module.ImageSourceError:
+ check(f"refuses {label}", True)
+ except Exception as exc: # noqa: BLE001 - must be the caller-facing class
+ check(f"refuses {label}", False, f"raised {type(exc).__name__}: {exc}")
+
+ print(f"\n{PASSED} contract assertions passed")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/workers/model-trellis2/test_glb_pack.py b/workers/model-trellis2/test_glb_pack.py
new file mode 100644
index 000000000..a8a1f8ffa
--- /dev/null
+++ b/workers/model-trellis2/test_glb_pack.py
@@ -0,0 +1,106 @@
+"""Unit tests for GLB post-processing: alpha mode and the gltfpack step.
+
+Needs numpy only; the gltfpack round trip runs when the binary is installed
+(every built image has it):
+
+ cd workers/model-trellis2 && python3 -m pytest test_glb_pack.py -q
+"""
+
+import json
+import shutil
+import struct
+
+import numpy as np
+import pytest
+
+import glb_pack
+
+
+class _Texture:
+ def __init__(self, alpha):
+ self.mode = "RGBA"
+ self._array = np.dstack([np.zeros_like(alpha)] * 3 + [alpha])
+
+ def __array__(self, dtype=None, copy=None):
+ return self._array
+
+
+class _Material:
+ def __init__(self, texture):
+ self.baseColorTexture = texture
+ self.alphaMode = "OPAQUE"
+
+
+class _Mesh:
+ def __init__(self, alpha):
+ self.visual = type("V", (), {"material": _Material(_Texture(alpha))})()
+
+
+def test_solid_alpha_stays_opaque():
+ assert glb_pack.alpha_mode_for(np.full((64, 64), 255, dtype=np.uint8)) == "OPAQUE"
+
+
+def test_stray_seam_pixels_do_not_flip_a_solid_asset():
+ alpha = np.full((100, 100), 255, dtype=np.uint8)
+ alpha[0, :50] = 0
+ assert glb_pack.alpha_mode_for(alpha) == "OPAQUE"
+
+
+def test_translucent_regions_flip_to_blend():
+ alpha = np.full((100, 100), 255, dtype=np.uint8)
+ alpha[:20] = 40
+ assert glb_pack.alpha_mode_for(alpha) == "BLEND"
+
+
+def test_empty_plane_is_opaque():
+ assert glb_pack.alpha_mode_for(np.zeros((0, 0), dtype=np.uint8)) == "OPAQUE"
+
+
+def test_blend_if_translucent_sets_the_material():
+ alpha = np.full((10, 10), 255, dtype=np.uint8)
+ alpha[:5] = 10
+ mesh = _Mesh(alpha)
+ assert glb_pack.blend_if_translucent(mesh) == "BLEND"
+ assert mesh.visual.material.alphaMode == "BLEND"
+
+
+def test_mesh_without_a_texture_is_left_alone():
+ assert glb_pack.blend_if_translucent(object()) == "OPAQUE"
+
+
+def test_missing_gltfpack_returns_the_uncompressed_glb():
+ data = b"glTF" + b"\x00" * 32
+ out, packed = glb_pack.compress(data, gltfpack_bin="gltfpack-not-installed")
+ assert out == data and packed is False
+
+
+def _minimal_glb() -> bytes:
+ positions = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0]], dtype="<f4").tobytes()
+ doc = {
+ "asset": {"version": "2.0"},
+ "scene": 0,
+ "scenes": [{"nodes": [0]}],
+ "nodes": [{"mesh": 0}],
+ "meshes": [{"primitives": [{"attributes": {"POSITION": 0}}]}],
+ "accessors": [{"bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3", "min": [0, 0, 0], "max": [1, 1, 0]}],
+ "bufferViews": [{"buffer": 0, "byteLength": len(positions)}],
+ "buffers": [{"byteLength": len(positions)}],
+ }
+ js = json.dumps(doc).encode()
+ js += b" " * (-len(js) % 4)
+ body = positions + b"\x00" * (-len(positions) % 4)
+ total = 12 + 8 + len(js) + 8 + len(body)
+ return (
+ struct.pack("<4sII", b"glTF", 2, total)
+ + struct.pack("<I4s", len(js), b"JSON") + js
+ + struct.pack("<I4s", len(body), b"BIN\x00") + body
+ )
+
+
[email protected](shutil.which(glb_pack.GLTFPACK_BIN) is None, reason="gltfpack not installed")
+def test_gltfpack_round_trip_yields_a_meshopt_glb():
+ out, packed = glb_pack.compress(_minimal_glb())
+ assert packed is True and out[:4] == b"glTF"
+ js_len = int.from_bytes(out[12:16], "little")
+ doc = json.loads(out[20:20 + js_len])
+ assert "EXT_meshopt_compression" in (doc.get("extensionsUsed") or [])
diff --git a/workers/model-trellis2/test_instance_health.py b/workers/model-trellis2/test_instance_health.py
new file mode 100644
index 000000000..261a66c29
--- /dev/null
+++ b/workers/model-trellis2/test_instance_health.py
@@ -0,0 +1,142 @@
+"""Unit tests for instance self-care: memory reading, recycle, orphan expiry.
+
+Pure stdlib, no torch and no CUDA, so this runs anywhere:
+
+ cd workers/model-trellis2 && python3 -m pytest test_instance_health.py -q
+
+These decisions run after every generation on the production instance. A wrong
+memory reading either restarts a healthy instance after every job or never
+restarts a bloated one, and a wrong orphan rule either fails live jobs or leaves
+dead ones polling for half an hour, which is the outage this module fixed.
+"""
+
+from pathlib import Path
+
+from instance_health import (
+ HEARTBEAT_SECS,
+ ORPHAN_AFTER_SECS,
+ MemorySample,
+ read_memory,
+ should_recycle,
+ task_is_orphaned,
+ trim_heap,
+)
+
+GIB = 1024 ** 3
+
+
+def _write(path: Path, text: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="ascii")
+
+
+# ---------------------------------------------------------------- read_memory
+
+
+def test_cgroup_v2_counts_heap_and_tmpfs_but_not_page_cache(tmp_path):
+ v2 = tmp_path / "v2"
+ _write(v2 / "memory.stat", f"anon {20 * GIB}\nfile {9 * GIB}\nshmem {3 * GIB}\n")
+ _write(v2 / "memory.max", f"{32 * GIB}\n")
+ sample = read_memory(str(v2), str(tmp_path / "none"), str(tmp_path / "none"))
+ assert sample == MemorySample(23 * GIB, 32 * GIB, "cgroup2")
+ assert abs(sample.fraction - 23 / 32) < 1e-9
+
+
+def test_cgroup_v2_without_a_limit_falls_through_to_meminfo(tmp_path):
+ v2 = tmp_path / "v2"
+ _write(v2 / "memory.stat", f"anon {GIB}\n")
+ _write(v2 / "memory.max", "max\n")
+ meminfo = tmp_path / "meminfo"
+ _write(meminfo, "MemTotal: 33554432 kB\nMemAvailable: 8388608 kB\n")
+ sample = read_memory(str(v2), str(tmp_path / "none"), str(meminfo))
+ assert sample.source == "meminfo"
+ assert sample.used_bytes == 24 * GIB
+ assert sample.limit_bytes == 32 * GIB
+
+
+def test_cgroup_v1_reads_rss_plus_shmem(tmp_path):
+ v1 = tmp_path / "v1"
+ _write(v1 / "memory.stat", f"total_rss {10 * GIB}\ntotal_cache {5 * GIB}\ntotal_shmem {2 * GIB}\n")
+ _write(v1 / "memory.limit_in_bytes", f"{16 * GIB}\n")
+ sample = read_memory(str(tmp_path / "none"), str(v1), str(tmp_path / "none"))
+ assert sample == MemorySample(12 * GIB, 16 * GIB, "cgroup1")
+
+
+def test_unlimited_cgroup_v1_is_not_a_ceiling(tmp_path):
+ v1 = tmp_path / "v1"
+ _write(v1 / "memory.stat", f"total_rss {GIB}\n")
+ _write(v1 / "memory.limit_in_bytes", "9223372036854771712\n")
+ assert read_memory(str(tmp_path / "none"), str(v1), str(tmp_path / "none")) is None
+
+
+def test_nothing_readable_is_unknown_not_an_error(tmp_path):
+ missing = str(tmp_path / "missing")
+ assert read_memory(missing, missing, missing) is None
+
+
+def test_describe_is_human_readable():
+ text = MemorySample(24 * GIB, 32 * GIB, "cgroup2").describe()
+ assert text == "24.0/32.0 GiB (75%, cgroup2)"
+
+
+# ---------------------------------------------------------------- should_recycle
+
+
+def _at(fraction: float) -> MemorySample:
+ return MemorySample(int(fraction * 32 * GIB), 32 * GIB, "cgroup2")
+
+
+def test_recycles_a_ratcheted_instance():
+ assert should_recycle(_at(0.88), _at(0.46))
+
+
+def test_leaves_a_healthy_instance_alone():
+ assert not should_recycle(_at(0.60), _at(0.46))
+
+
+def test_high_baseline_alone_never_recycles():
+ # A baseline that already reads high (a big model, or a reading that counts
+ # more than it should) must not restart the instance after every job.
+ assert not should_recycle(_at(0.84), _at(0.80))
+
+
+def test_unknown_memory_never_recycles():
+ assert not should_recycle(None, _at(0.40))
+ assert not should_recycle(_at(0.95), None)
+
+
+# ---------------------------------------------------------------- task_is_orphaned
+
+
+NOW = 1_800_000_000.0
+
+
+def test_a_beating_task_is_alive():
+ assert not task_is_orphaned("running", NOW - HEARTBEAT_SECS, NOW)
+ assert not task_is_orphaned("queued", NOW - ORPHAN_AFTER_SECS + 1, NOW)
+
+
+def test_a_silent_task_is_orphaned_within_minutes():
+ assert task_is_orphaned("running", NOW - ORPHAN_AFTER_SECS - 1, NOW)
+ # The old rule waited 1800 s; the whole point is that a client still polls.
+ assert ORPHAN_AFTER_SECS <= 300
+ # Several missed beats, never one, decide it.
+ assert ORPHAN_AFTER_SECS >= 4 * HEARTBEAT_SECS
+
+
+def test_a_record_without_a_timestamp_cannot_prove_it_is_alive():
+ assert task_is_orphaned("queued", None, NOW)
+ assert task_is_orphaned("running", "yesterday", NOW)
+ assert task_is_orphaned("running", True, NOW)
+
+
+def test_terminal_and_unknown_records_are_never_orphaned():
+ for status in ("done", "failed", None, "weird"):
+ assert not task_is_orphaned(status, NOW - 10 * ORPHAN_AFTER_SECS, NOW)
+
+
+# ---------------------------------------------------------------- trim_heap
+
+
+def test_trim_heap_never_raises():
+ assert trim_heap() in (True, False)
diff --git a/workers/model-trellis2/test_pipeline_config.py b/workers/model-trellis2/test_pipeline_config.py
new file mode 100644
index 000000000..480adf61f
--- /dev/null
+++ b/workers/model-trellis2/test_pipeline_config.py
@@ -0,0 +1,88 @@
+"""Unit tests for the pipeline.json rewrite: stdlib only, runs anywhere.
+
+ cd workers/model-trellis2 && python3 -m pytest test_pipeline_config.py -q
+
+The rewrite is what keeps the non-commercial RMBG-2.0 matte out of the served
+pipeline and keeps the model load off the Hugging Face Hub, so both are asserted.
+"""
+
+import json
+
+import pipeline_config
+
+# The shape of microsoft/TRELLIS.2-4B's pipeline.json, reduced to the fields the
+# rewrite touches plus the sampler block that must pass through unchanged.
+UPSTREAM = {
+ "name": "Trellis2ImageTo3DPipeline",
+ "args": {
+ "models": {
+ "sparse_structure_decoder": "microsoft/TRELLIS-image-large/ckpts/ss_dec_conv3d_16l8_fp16",
+ "sparse_structure_flow_model": "ckpts/ss_flow_img_dit_1_3B_64_bf16",
+ "shape_slat_decoder": "ckpts/shape_dec_next_dc_f16c32_fp16",
+ },
+ "shape_slat_sampler": {"name": "FlowEulerGuidanceIntervalSampler", "params": {"steps": 12}},
+ "image_cond_model": {
+ "name": "DinoV3FeatureExtractor",
+ "args": {"model_name": "facebook/dinov3-vitl16-pretrain-lvd1689m"},
+ },
+ "rembg_model": {"name": "BiRefNet", "args": {"model_name": "briaai/RMBG-2.0"}},
+ "default_pipeline_type": "1024_cascade",
+ },
+}
+
+
+def test_matte_is_replaced_by_the_mit_birefnet_checkpoint():
+ out = pipeline_config.localize(UPSTREAM, "/aux")
+ assert "RMBG" not in json.dumps(out)
+ assert out["args"]["rembg_model"] == {"name": "BiRefNet", "args": {"model_name": "/aux/birefnet"}}
+
+
+def test_conditioner_loads_from_the_staged_copy_not_the_hub():
+ out = pipeline_config.localize(UPSTREAM, "/aux")
+ assert out["args"]["image_cond_model"]["args"]["model_name"] == "/aux/dinov3"
+ assert "facebook/" not in json.dumps(out)
+
+
+def test_ss_decoder_points_inside_the_staged_tree():
+ out = pipeline_config.localize(UPSTREAM, "/aux")
+ assert out["args"]["models"]["sparse_structure_decoder"] == "ss_dec/ckpts/ss_dec_conv3d_16l8_fp16"
+
+
+def test_unrelated_fields_pass_through_and_input_is_not_mutated():
+ before = json.dumps(UPSTREAM)
+ out = pipeline_config.localize(UPSTREAM, "/aux")
+ assert json.dumps(UPSTREAM) == before
+ assert out["args"]["shape_slat_sampler"] == UPSTREAM["args"]["shape_slat_sampler"]
+ assert out["args"]["default_pipeline_type"] == "1024_cascade"
+ assert out["args"]["models"]["shape_slat_decoder"] == "ckpts/shape_dec_next_dc_f16c32_fp16"
+
+
+def test_missing_weights_names_every_absent_file():
+ present = set(pipeline_config.REQUIRED_PATHS) - {"dinov3/model.safetensors", "birefnet/config.json"}
+ assert pipeline_config.missing_weights(present) == ["dinov3/model.safetensors", "birefnet/config.json"]
+ assert pipeline_config.missing_weights(pipeline_config.REQUIRED_PATHS) == []
+
+
+def test_required_paths_cover_every_checkpoint_the_resolutions_use():
+ needed = {
+ "ckpts/slat_flow_img2shape_dit_1_3B_512_bf16.safetensors",
+ "ckpts/slat_flow_img2shape_dit_1_3B_1024_bf16.safetensors",
+ "ckpts/slat_flow_imgshape2tex_dit_1_3B_512_bf16.safetensors",
+ "ckpts/slat_flow_imgshape2tex_dit_1_3B_1024_bf16.safetensors",
+ }
+ assert needed <= set(pipeline_config.REQUIRED_PATHS)
+
+
+def test_write_local_config_and_link_tree(tmp_path):
+ root = tmp_path / "weights"
+ (root / "ckpts").mkdir(parents=True)
+ (root / "pipeline.json").write_text(json.dumps(UPSTREAM))
+ out_dir = tmp_path / "cfg"
+ path = pipeline_config.write_local_config((root / "pipeline.json").read_text(), "/aux", out_dir)
+ pipeline_config.link_weight_tree(root, out_dir)
+ written = json.loads(path.read_text())
+ assert written["args"]["rembg_model"]["args"]["model_name"] == "/aux/birefnet"
+ assert (out_dir / "ckpts").is_symlink()
+ assert not (out_dir / "pipeline.json").is_symlink()
+ # Idempotent: a load retry re-links without raising.
+ pipeline_config.link_weight_tree(root, out_dir)
diff --git a/workers/model-trellis2/test_request_policy.py b/workers/model-trellis2/test_request_policy.py
new file mode 100644
index 000000000..9028b54a0
--- /dev/null
+++ b/workers/model-trellis2/test_request_policy.py
@@ -0,0 +1,138 @@
+"""Unit tests for the TRELLIS.2 request policy: resolutions and transient-fetch retry.
+
+Pure stdlib plus httpx, no torch and no CUDA, so this runs anywhere:
+
+ cd workers/model-trellis2 && python3 -m pytest test_request_policy.py -q
+"""
+
+import httpx
+import pytest
+
+from request_policy import (
+ DEFAULT_RESOLUTION,
+ FETCH_ATTEMPTS,
+ PIPELINE_TYPES,
+ RESOLUTIONS,
+ RESOLUTION_PRESETS,
+ bake_params,
+ call_with_retry,
+ clamp_to_ceiling,
+ is_transient_fetch_error,
+ resolve_resolution,
+ retry_delays,
+ step_down,
+)
+
+
+def test_default_is_1024():
+ assert resolve_resolution(None) == DEFAULT_RESOLUTION == 1024
+
+
[email protected]("wanted,expected", [(512, 512), (1024, 1024), (1536, 1536), (2048, 1536), (700, 512), (900, 1024), (1, 512)])
+def test_explicit_resolution_snaps_to_a_supported_size(wanted, expected):
+ assert resolve_resolution(wanted) == expected
+
+
+def test_garbage_resolution_falls_back_to_the_default():
+ assert resolve_resolution("big") == 1024
+ assert resolve_resolution([]) == 1024
+
+
[email protected]("tier,expected", [("draft", 512), ("standard", 1024), ("high", 1024), ("max", 1536), (" MAX ", 1536), ("nonsense", 1024), (None, 1024)])
+def test_tier_maps_to_a_resolution(tier, expected):
+ assert resolve_resolution(None, tier) == expected
+
+
+def test_explicit_resolution_beats_the_tier():
+ assert resolve_resolution(512, "max") == 512
+
+
+def test_every_resolution_has_a_pipeline_type_and_a_preset():
+ for r in RESOLUTIONS:
+ assert r in PIPELINE_TYPES and r in RESOLUTION_PRESETS
+ assert PIPELINE_TYPES == {512: "512", 1024: "1024_cascade", 1536: "1536_cascade"}
+
+
+def test_ceiling_caps_the_request():
+ assert clamp_to_ceiling(1536, 1024) == 1024
+ assert clamp_to_ceiling(512, 1024) == 512
+ assert clamp_to_ceiling(1536, None) == 1536
+ assert clamp_to_ceiling(1536, 100) == 512
+
+
+def test_step_down_walks_the_ladder_and_stops():
+ assert step_down(1536) == 1024
+ assert step_down(1024) == 512
+ assert step_down(512) is None
+
+
+def test_bake_params_default_to_the_preset():
+ assert bake_params(1024) == {"texture_size": 4096, "decimation_target": 1_000_000}
+ assert bake_params(512)["texture_size"] == 2048
+
+
+def test_texture_size_snaps_down_to_a_power_of_two_inside_the_envelope():
+ assert bake_params(1024, texture_size=3072)["texture_size"] == 2048
+ assert bake_params(1024, texture_size=100000)["texture_size"] == 4096
+ assert bake_params(1024, texture_size=10)["texture_size"] == 512
+
+
+def test_decimation_is_bounded_and_garbage_falls_back():
+ assert bake_params(1024, decimation_target=10)["decimation_target"] == 50_000
+ assert bake_params(1024, decimation_target=10**9)["decimation_target"] == 2_000_000
+ assert bake_params(1024, decimation_target="lots")["decimation_target"] == 1_000_000
+ assert bake_params(1024, texture_size="x")["texture_size"] == 4096
+
+
+def test_retry_delays_double():
+ assert retry_delays(3, 1.0) == [1.0, 2.0]
+
+
+def _status_error(code):
+ request = httpx.Request("GET", "https://example.com/a.png")
+ return httpx.HTTPStatusError("x", request=request, response=httpx.Response(code, request=request))
+
+
+def test_transient_classification():
+ assert is_transient_fetch_error(httpx.ReadTimeout("t"))
+ assert is_transient_fetch_error(_status_error(503))
+ assert not is_transient_fetch_error(_status_error(404))
+ assert not is_transient_fetch_error(ValueError("nope"))
+
+
+def test_call_with_retry_recovers_from_a_blip():
+ calls = []
+ sleeps = []
+
+ def flaky():
+ calls.append(1)
+ if len(calls) < 2:
+ raise httpx.ReadTimeout("slow")
+ return "ok"
+
+ assert call_with_retry(flaky, sleep=sleeps.append) == "ok"
+ assert len(calls) == 2 and sleeps == [1.0]
+
+
+def test_call_with_retry_gives_up_on_a_permanent_error_immediately():
+ calls = []
+
+ def gone():
+ calls.append(1)
+ raise _status_error(404)
+
+ with pytest.raises(httpx.HTTPStatusError):
+ call_with_retry(gone, sleep=lambda s: None)
+ assert len(calls) == 1
+
+
+def test_call_with_retry_spends_the_budget_then_raises():
+ calls = []
+
+ def down():
+ calls.append(1)
+ raise httpx.ConnectError("down")
+
+ with pytest.raises(httpx.ConnectError):
+ call_with_retry(down, sleep=lambda s: None)
+ assert len(calls) == FETCH_ATTEMPTS
diff --git a/workers/model-trellis2/test_storage_backend.py b/workers/model-trellis2/test_storage_backend.py
new file mode 100644
index 000000000..fa6d14adb
--- /dev/null
+++ b/workers/model-trellis2/test_storage_backend.py
@@ -0,0 +1,54 @@
+from __future__ import annotations
+
+import json
+import uuid
+
+import pytest
+
+from storage_backend import LocalStorage, normalize_task_id
+
+
+def test_task_round_trip_survives_process_memory(tmp_path):
+ storage = LocalStorage(tmp_path)
+ task_id = str(uuid.uuid4())
+ task = {"task_id": task_id, "status": "done", "updated_at": 123.0}
+
+ path = storage.write_task(task)
+
+ assert path == tmp_path / "tasks" / f"{task_id}.json"
+ assert storage.read_task(task_id) == task
+ assert json.loads(path.read_text()) == task
+
+
+def test_result_is_written_to_the_mounted_volume(tmp_path):
+ storage = LocalStorage(tmp_path)
+ task_id = str(uuid.uuid4())
+ payload = b"glTF" + bytes(range(32))
+
+ path = storage.write_result(task_id, payload)
+
+ assert path == tmp_path / "results" / f"{task_id}.glb"
+ assert path.read_bytes() == payload
+
+
+ "task_id",
+ ["../escape", "not-a-uuid", "{00000000-0000-0000-0000-000000000000}", "00000000-0000-0000-0000-000000000000/mesh"],
+)
+def test_task_ids_cannot_escape_the_output_volume(task_id):
+ with pytest.raises(ValueError):
+ normalize_task_id(task_id)
+
+
+def test_atomic_writes_leave_no_temporary_files(tmp_path):
+ storage = LocalStorage(tmp_path)
+ task_id = str(uuid.uuid4())
+
+ storage.write_task({"task_id": task_id, "status": "queued"})
+ storage.write_task({"task_id": task_id, "status": "running"})
+ storage.write_result(task_id, b"first")
+ storage.write_result(task_id, b"second")
+
+ assert storage.read_task(task_id)["status"] == "running"
+ assert storage.result_path(task_id).read_bytes() == b"second"
+ assert list(tmp_path.rglob("*.tmp")) == []
diff --git a/workers/model-trellis2/worker_security.py b/workers/model-trellis2/worker_security.py
new file mode 100644
index 000000000..21951efcd
--- /dev/null
+++ b/workers/model-trellis2/worker_security.py
@@ -0,0 +1,233 @@
+"""
+Shared security helpers for the three.ws GPU/CPU workers.
+
+This module is intentionally dependency-light (stdlib only) so it can be
+COPYed verbatim into every worker's Docker build context. The same canonical
+file lives in each worker directory; keep them byte-identical when editing.
+
+It provides three primitives that every worker needs:
+
+ 1. ``require_api_key`` - constant-time bearer-token check (timing-safe).
+ 2. ``fetch_remote_bytes`` - SSRF-hardened HTTP(S) fetch of caller-supplied
+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata
+ IP rejection, per-hop redirect re-validation, and a bounded response size.
+ 3. ``safe_error`` - turns an exception into an opaque, correlation-id-tagged
+ message safe to persist/return to callers, after logging the full
+ traceback server-side only.
+"""
+
+from __future__ import annotations
+
+import hmac
+import ipaddress
+import logging
+import socket
+import uuid
+from typing import Iterable, Optional
+from urllib.parse import urlsplit
+
+import httpx
+
+log = logging.getLogger("worker_security")
+
+# ── auth ────────────────────────────────────────────────────────────────────────
+
+
+def require_api_key(authorization: Optional[str], api_key: str) -> None:
+ """Validate a ``Bearer <token>`` header in constant time.
+
+ Raises ``PermissionError`` on any failure so callers can translate it into
+ the framework's 401 (FastAPI workers map this to HTTPException(401)).
+ """
+ # Fail closed on an empty configured key: with api_key == "" a bare
+ # "Bearer " header would otherwise strip to "" and compare equal.
+ if not api_key:
+ raise PermissionError("worker api key not configured")
+ if not authorization or not authorization.startswith("Bearer "):
+ raise PermissionError("missing bearer token")
+ token = authorization[len("Bearer "):].strip()
+ if not token:
+ raise PermissionError("missing bearer token")
+ # Compare bytes: hmac.compare_digest is timing-safe, and on str operands it
+ # raises TypeError for non-ASCII input, which would surface as a 500.
+ if not hmac.compare_digest(token.encode("utf-8"), api_key.encode("utf-8")):
+ raise PermissionError("invalid api key")
+
+
+# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────
+
+# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes
+# are comfortably under this; anything larger is almost certainly abuse.
+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB
+_MAX_REDIRECTS = 4
+
+
+class UnsafeUrlError(ValueError):
+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""
+
+
+def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:
+ """Reject any address that could reach internal infrastructure.
+
+ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud
+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),
+ multicast, reserved, unspecified, and any other non-global address (CGNAT
+ 100.64.0.0/10 included). IPv4-mapped IPv6 addresses
+ are unwrapped first so a mapped private v4 can't slip through.
+ """
+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
+ ip = ip.ipv4_mapped
+ return (
+ ip.is_private
+ or ip.is_loopback
+ or ip.is_link_local
+ or ip.is_multicast
+ or ip.is_reserved
+ or ip.is_unspecified
+ # Anything not globally routable, which also covers the CGNAT shared
+ # space 100.64.0.0/10 that is_private does not flag.
+ or not ip.is_global
+ )
+
+
+def _resolve_safe_host(host: str) -> None:
+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.
+
+ Resolving and checking every returned address closes the gap where a name
+ resolves to both a public and a private address.
+ """
+ if not host:
+ raise UnsafeUrlError("missing host")
+ try:
+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
+ except socket.gaierror as exc:
+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc
+
+ addrs = {info[4][0] for info in infos}
+ if not addrs:
+ raise UnsafeUrlError(f"no addresses for host: {host}")
+ for addr in addrs:
+ ip = ipaddress.ip_address(addr)
+ if _is_blocked_ip(ip):
+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")
+
+
+def assert_safe_url(url: str, *, allow_http: bool = False) -> str:
+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.
+
+ https is required by default; ``allow_http`` exists only for callers that
+ legitimately need cleartext (not used by the workers).
+ """
+ parts = urlsplit(url)
+ scheme = parts.scheme.lower()
+ allowed = ("https", "http") if allow_http else ("https",)
+ if scheme not in allowed:
+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")
+ if not parts.hostname:
+ raise UnsafeUrlError("missing host")
+ _resolve_safe_host(parts.hostname)
+ return url
+
+
+def fetch_remote_bytes(
+ url: str,
+ *,
+ timeout: float = 30.0,
+ max_bytes: int = DEFAULT_MAX_BYTES,
+ allow_http: bool = False,
+ headers: Optional[dict] = None,
+) -> bytes:
+ """Fetch ``url`` safely and return its body bytes.
+
+ Hardening applied:
+ * https-only (unless ``allow_http``).
+ * every URL - including each redirect target - is DNS-resolved and
+ rejected if it maps to a private/loopback/link-local/metadata address.
+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is
+ re-validated; httpx's own redirect following is disabled.
+ * the response body is streamed and aborted once it exceeds ``max_bytes``.
+
+ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /
+ ``ValueError`` for transport or size failures.
+ """
+ current = assert_safe_url(url, allow_http=allow_http)
+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:
+ for _ in range(_MAX_REDIRECTS + 1):
+ with client.stream("GET", current, headers=headers) as resp:
+ if resp.is_redirect:
+ location = resp.headers.get("location")
+ if not location:
+ raise UnsafeUrlError("redirect without Location header")
+ current = assert_safe_url(
+ str(resp.url.join(location)), allow_http=allow_http
+ )
+ continue
+ resp.raise_for_status()
+ declared = resp.headers.get("content-length")
+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:
+ raise ValueError(f"response too large: {declared} bytes")
+ chunks: list[bytes] = []
+ total = 0
+ for chunk in resp.iter_bytes(65536):
+ total += len(chunk)
+ if total > max_bytes:
+ raise ValueError(f"response exceeded {max_bytes} bytes")
+ chunks.append(chunk)
+ return b"".join(chunks)
+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")
+
+
+async def fetch_remote_bytes_async(
+ client: "httpx.AsyncClient",
+ url: str,
+ *,
+ max_bytes: int = DEFAULT_MAX_BYTES,
+ allow_http: bool = False,
+ headers: Optional[dict] = None,
+) -> bytes:
+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.
+
+ The provided ``client`` MUST be constructed with ``follow_redirects=False``
+ so this function can re-validate each redirect hop itself.
+ """
+ current = assert_safe_url(url, allow_http=allow_http)
+ for _ in range(_MAX_REDIRECTS + 1):
+ async with client.stream("GET", current, headers=headers) as resp:
+ if resp.is_redirect:
+ location = resp.headers.get("location")
+ if not location:
+ raise UnsafeUrlError("redirect without Location header")
+ current = assert_safe_url(
+ str(resp.url.join(location)), allow_http=allow_http
+ )
+ continue
+ resp.raise_for_status()
+ declared = resp.headers.get("content-length")
+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:
+ raise ValueError(f"response too large: {declared} bytes")
+ chunks: list[bytes] = []
+ total = 0
+ async for chunk in resp.aiter_bytes(65536):
+ total += len(chunk)
+ if total > max_bytes:
+ raise ValueError(f"response exceeded {max_bytes} bytes")
+ chunks.append(chunk)
+ return b"".join(chunks)
+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")
+
+
+# ── opaque error handling ───────────────────────────────────────────────────────
+
+
+def safe_error(exc: BaseException, *, context: str = "") -> str:
+ """Log the full traceback server-side and return an opaque client message.
+
+ Never leak ``traceback.format_exc()`` (absolute paths, library versions,
+ internal hostnames, fragments of upstream responses) to callers. A short
+ correlation id is embedded in both the log line and the returned string so
+ operators can join a client-reported failure to the server log.
+ """
+ correlation_id = uuid.uuid4().hex[:12]
+ label = f"{context} " if context else ""
+ log.exception("%serror [correlation_id=%s]", label, correlation_id)
+ return f"internal error (ref {correlation_id})"