Skip to content

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

fix(workers): decode EXT_meshopt_compression before any worker reads a caller mesh

nirholas84c8b513f07c
diff --git a/scripts/check-vendored-workers.mjs b/scripts/check-vendored-workers.mjs
new file mode 100644
index 000000000..5e9abd09d
--- /dev/null
+++ b/scripts/check-vendored-workers.mjs
@@ -0,0 +1,91 @@
+#!/usr/bin/env node
+/**
+ * Guard the vendored worker modules.
+ *
+ * Each worker's Docker build context is its own directory, so `../` is
+ * unreachable and shared code lives as a byte-identical copy in every worker
+ * that needs it (worker_security.py, oin.py, gltf_meshopt.py and their vendored
+ * tests). Nothing enforced that, so a fix applied to one copy could silently
+ * leave the other seventeen on the old behaviour: the exact shape of bug this
+ * repo has already paid for once.
+ *
+ * This compares every copy of every vendored file against the copy with the
+ * most instances (the de-facto canonical one) and fails on any divergence,
+ * naming the file, the workers that differ, and how to resync them.
+ *
+ * node scripts/check-vendored-workers.mjs
+ */
+
+import { readFileSync, readdirSync, statSync } from 'node:fs';
+import { createHash } from 'node:crypto';
+import { join } from 'node:path';
+
+// Files that MUST be identical wherever they appear under workers/.
+const VENDORED = [
+ 'worker_security.py',
+ 'oin.py',
+ 'oin_upload.py',
+ 'gltf_meshopt.py',
+ 'test_gltf_meshopt.py',
+];
+
+const WORKERS_DIR = 'workers';
+
+function digest(path) {
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
+}
+
+function workerDirs() {
+ return readdirSync(WORKERS_DIR)
+ .filter((name) => {
+ try {
+ return statSync(join(WORKERS_DIR, name)).isDirectory();
+ } catch {
+ return false;
+ }
+ })
+ .sort();
+}
+
+const dirs = workerDirs();
+const failures = [];
+let checked = 0;
+
+for (const file of VENDORED) {
+ const copies = [];
+ for (const dir of dirs) {
+ const path = join(WORKERS_DIR, dir, file);
+ try {
+ statSync(path);
+ } catch {
+ continue;
+ }
+ copies.push({ dir, path, sha: digest(path) });
+ }
+ if (copies.length < 2) continue;
+ checked += copies.length;
+
+ const counts = new Map();
+ for (const copy of copies) counts.set(copy.sha, (counts.get(copy.sha) || 0) + 1);
+ const [canonicalSha] = [...counts.entries()].sort((a, b) => b[1] - a[1])[0];
+ const canonical = copies.find((c) => c.sha === canonicalSha);
+ const drifted = copies.filter((c) => c.sha !== canonicalSha);
+
+ if (drifted.length) {
+ failures.push(
+ `${file}: ${drifted.length} of ${copies.length} copies differ from ${canonical.path}\n` +
+ drifted.map((c) => ` ${c.path} (resync: cp ${canonical.path} ${c.path})`).join('\n'),
+ );
+ }
+}
+
+if (failures.length) {
+ console.error('[check-vendored-workers] vendored worker files have drifted:\n');
+ for (const failure of failures) console.error(` ${failure}\n`);
+ console.error('Fix the canonical copy, mirror it to every worker, and rerun.');
+ process.exit(1);
+}
+
+console.log(
+ `[check-vendored-workers] OK: ${checked} vendored file copies across ${dirs.length} workers are byte-identical`,
+);
diff --git a/workers/remesh/Dockerfile b/workers/remesh/Dockerfile
index 54096c340..981900f0b 100644
--- a/workers/remesh/Dockerfile
+++ b/workers/remesh/Dockerfile
@@ -1,4 +1,19 @@
+# gltfpack (zeux/meshoptimizer, MIT) decodes EXT_meshopt_compression, which
+# trimesh cannot read and which most three.ws avatars ship as. Pinned by release
+# tag and checksum so the image never picks up a binary we did not audit.
+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 ca-certificates curl unzip \
+ && 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 python:3.11-slim
+COPY --from=gltfpack /usr/local/bin/gltfpack /usr/local/bin/gltfpack
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
@@ -46,6 +61,7 @@ RUN pip install -r /app/requirements.txt
WORKDIR /app
COPY worker_security.py /app/worker_security.py
+COPY gltf_meshopt.py /app/gltf_meshopt.py
COPY blender_fbx.py /app/blender_fbx.py
COPY verify_fbx.py /app/verify_fbx.py
COPY main.py /app/main.py
@@ -54,7 +70,9 @@ COPY main.py /app/main.py
# GLB to FBX round trip run against synthetic fixtures at build time, so a
# regression fails the image instead of reaching Cloud Run. No network, no GCS.
COPY test_remesh.py /app/test_remesh.py
-RUN API_KEY=build-gate GCS_BUCKET=build-gate python test_remesh.py
+COPY test_gltf_meshopt.py /app/test_gltf_meshopt.py
+RUN API_KEY=build-gate GCS_BUCKET=build-gate python test_remesh.py \
+ && python test_gltf_meshopt.py
EXPOSE 8080
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "1"]
diff --git a/workers/remesh/gltf_meshopt.py b/workers/remesh/gltf_meshopt.py
new file mode 100644
index 000000000..10f7ba4ad
--- /dev/null
+++ b/workers/remesh/gltf_meshopt.py
@@ -0,0 +1,107 @@
+"""EXT_meshopt_compression decoding for caller-supplied glTF input.
+
+Vendored byte-identical into every worker that loads a mesh a caller handed it,
+exactly like worker_security.py: each worker's Docker build context is its own
+directory, so `../` is unreachable. `npm run check:vendored` fails if the copies
+drift apart.
+
+Why it exists: trimesh has no decoder for EXT_meshopt_compression. A compressed
+asset stores its geometry in compressed buffer views and declares a second,
+empty "fallback" buffer that only exists once something decodes into it, so
+trimesh dies on the bufferView lookup with a bare `IndexError: list index out of
+range`. Meshopt is what gltfpack emits and what most three.ws avatars ship as,
+so this was a hard failure on our own assets (verified 2026-08-13:
+/avatars/michelle.glb failed every stylize filter in production). gltfpack is
+the same project's CLI and decodes what it encoded, so the fix is to transcode
+the asset to plain glTF before any reader touches it.
+
+The binary is pinned by release tag and checksum in each worker's Dockerfile.
+Set GLTFPACK_BIN to run the path against your own copy locally.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import subprocess
+import tempfile
+from pathlib import Path
+from typing import Optional
+
+log = logging.getLogger("gltf-meshopt")
+
+MESHOPT_EXTENSION = "EXT_meshopt_compression"
+GLTFPACK_BIN = os.environ.get("GLTFPACK_BIN", "gltfpack")
+GLTFPACK_TIMEOUT_S = int(os.environ.get("GLTFPACK_TIMEOUT_S", "120"))
+
+
+def gltf_document(data: bytes, suffix: str = ".glb") -> Optional[dict]:
+ """The glTF JSON of a .glb/.gltf payload, or None when it is neither."""
+ if suffix == ".gltf":
+ try:
+ return json.loads(data)
+ except ValueError:
+ return None
+ if suffix != ".glb" or len(data) < 20 or data[:4] != b"glTF":
+ return None
+ chunk_length = int.from_bytes(data[12:16], "little")
+ if data[16:20] != b"JSON":
+ return None
+ try:
+ return json.loads(data[20:20 + chunk_length])
+ except ValueError:
+ return None
+
+
+def uses_meshopt(document: Optional[dict]) -> bool:
+ """True when the asset needs a meshopt decode before any reader can use it.
+
+ Checked against both extension lists: an asset that only *uses* the
+ extension still stores its geometry in the compressed views, and its
+ fallback buffer stays empty until something decodes into it.
+ """
+ if not document:
+ return False
+ declared = set(document.get("extensionsRequired") or []) | set(document.get("extensionsUsed") or [])
+ return MESHOPT_EXTENSION in declared
+
+
+def transcode_meshopt(data: bytes, suffix: str = ".glb") -> bytes:
+ """Rewrite a meshopt-compressed asset as a plain GLB with gltfpack.
+
+ `-noq` keeps the source quantization instead of re-quantizing on the way
+ out, so downstream geometry is derived from what the author shipped.
+ """
+ with tempfile.TemporaryDirectory() as tmpdir:
+ src = Path(tmpdir) / f"input{suffix}"
+ dst = Path(tmpdir) / "decoded.glb"
+ src.write_bytes(data)
+ try:
+ proc = subprocess.run(
+ [GLTFPACK_BIN, "-i", str(src), "-o", str(dst), "-noq"],
+ capture_output=True,
+ timeout=GLTFPACK_TIMEOUT_S,
+ )
+ except FileNotFoundError as exc:
+ raise ValueError(
+ f"input uses {MESHOPT_EXTENSION} and the gltfpack decoder is not installed"
+ ) from exc
+ except subprocess.TimeoutExpired as exc:
+ raise ValueError(f"{MESHOPT_EXTENSION} decode timed out") from exc
+ if proc.returncode != 0 or not dst.exists():
+ detail = (proc.stderr or b"").decode("utf-8", "replace").strip().splitlines()
+ raise ValueError(f"{MESHOPT_EXTENSION} decode failed: {detail[-1][:200] if detail else 'no output'}")
+ return dst.read_bytes()
+
+
+def decode_if_meshopt(data: bytes, suffix: str = ".glb") -> tuple[bytes, str]:
+ """Return (data, suffix) ready for trimesh, decoding meshopt when present.
+
+ A payload that is not compressed glTF is handed back untouched, so this is
+ safe to call on every input path.
+ """
+ if not uses_meshopt(gltf_document(data, suffix)):
+ return data, suffix
+ log.info("input declares %s; decoding with gltfpack before load", MESHOPT_EXTENSION)
+ return transcode_meshopt(data, suffix), ".glb"
diff --git a/workers/remesh/main.py b/workers/remesh/main.py
index 0aba9e1c5..636b51b1b 100644
--- a/workers/remesh/main.py
+++ b/workers/remesh/main.py
@@ -68,6 +68,7 @@ from fastapi import FastAPI, HTTPException, Header, BackgroundTasks
from google.cloud import storage
from pydantic import BaseModel, Field, field_validator
+from gltf_meshopt import decode_if_meshopt
from worker_security import (
UnsafeUrlError,
fetch_remote_bytes,
@@ -148,7 +149,10 @@ def _fetch_mesh(url: str) -> tuple[bytes, str]:
suffix = Path(url.split("?")[0]).suffix.lower()
if suffix not in SUPPORTED_INPUT_FORMATS:
suffix = ".glb"
- return data, suffix
+ # A meshopt-compressed asset is transcoded here, before any loader sees it:
+ # trimesh cannot read one, and it is the format most three.ws avatars ship
+ # as. Anything else passes through untouched.
+ return decode_if_meshopt(data, suffix)
def _load_concatenated(data: bytes, suffix: str):
diff --git a/workers/remesh/test_gltf_meshopt.py b/workers/remesh/test_gltf_meshopt.py
new file mode 100644
index 000000000..2d2e9d502
--- /dev/null
+++ b/workers/remesh/test_gltf_meshopt.py
@@ -0,0 +1,141 @@
+"""Tests for gltf_meshopt.py, the shared EXT_meshopt_compression decoder.
+
+Vendored byte-identical into every worker that ships gltf_meshopt.py, exactly
+like the module itself, and run as a Docker build gate in each of them:
+
+ python3 test_gltf_meshopt.py
+
+The round-trip section needs the `gltfpack` binary (present in every worker
+image, pinned in the Dockerfile). Without it the suite still runs and pins the
+readable failure a caller gets instead, so a laptop run stays green.
+"""
+
+from __future__ import annotations
+
+import io
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+import trimesh # noqa: E402
+
+import gltf_meshopt # noqa: E402
+
+PASS = 0
+
+
+def check(name: str, condition: bool, detail: str = "") -> None:
+ global PASS
+ if not condition:
+ print(f"FAIL {name} {detail}")
+ sys.exit(1)
+ PASS += 1
+ print(f"ok {name}")
+
+
+plain_glb = trimesh.Scene({"a": trimesh.creation.icosphere(subdivisions=2)}).export(file_type="glb")
+
+# ── document parsing ────────────────────────────────────────────────────────────
+
+doc = gltf_meshopt.gltf_document(plain_glb, ".glb")
+check("a glb's json chunk parses", isinstance(doc, dict) and "asset" in doc, str(type(doc)))
+check(
+ "a gltf json payload parses",
+ isinstance(gltf_meshopt.gltf_document(b'{"asset":{"version":"2.0"}}', ".gltf"), dict),
+)
+for payload, suffix, label in (
+ (b"ply\nformat ascii 1.0\n", ".ply", "a ply"),
+ (b"not json at all", ".gltf", "malformed gltf json"),
+ (b"glTF" + b"\x00" * 4, ".glb", "a truncated glb"),
+ (b"solid mesh\n", ".stl", "an stl"),
+):
+ check(f"{label} yields no gltf document", gltf_meshopt.gltf_document(payload, suffix) is None)
+
+# ── extension detection ─────────────────────────────────────────────────────────
+
+check("a plain glb needs no decode", not gltf_meshopt.uses_meshopt(doc))
+check("an empty document needs no decode", not gltf_meshopt.uses_meshopt(None))
+for declared in ("extensionsRequired", "extensionsUsed"):
+ check(
+ f"{declared} announcing {gltf_meshopt.MESHOPT_EXTENSION} needs a decode",
+ gltf_meshopt.uses_meshopt({declared: [gltf_meshopt.MESHOPT_EXTENSION]}),
+ )
+check(
+ "an unrelated extension needs no decode",
+ not gltf_meshopt.uses_meshopt({"extensionsUsed": ["KHR_materials_unlit"]}),
+)
+check(
+ "an uncompressed payload passes through decode_if_meshopt untouched",
+ gltf_meshopt.decode_if_meshopt(plain_glb, ".glb") == (plain_glb, ".glb"),
+)
+
+# ── the real decode ─────────────────────────────────────────────────────────────
+
+if shutil.which(gltf_meshopt.GLTFPACK_BIN):
+ with tempfile.TemporaryDirectory() as packdir:
+ raw = Path(packdir) / "raw.glb"
+ packed = Path(packdir) / "packed.glb"
+ raw.write_bytes(plain_glb)
+ subprocess.run(
+ [gltf_meshopt.GLTFPACK_BIN, "-i", str(raw), "-o", str(packed), "-cc"],
+ capture_output=True,
+ check=True,
+ timeout=gltf_meshopt.GLTFPACK_TIMEOUT_S,
+ )
+ packed_bytes = packed.read_bytes()
+
+ check(
+ "a gltfpack-compressed glb is detected",
+ gltf_meshopt.uses_meshopt(gltf_meshopt.gltf_document(packed_bytes, ".glb")),
+ )
+
+ # The bug this module exists for: trimesh dies on the compressed asset's
+ # fallback buffer, which is why every worker loading one failed.
+ try:
+ trimesh.load(io.BytesIO(packed_bytes), file_type="glb", force="mesh", process=False)
+ raw_load_failed = False
+ except Exception: # noqa: BLE001: the exact trimesh error is not the contract
+ raw_load_failed = True
+ check("trimesh alone cannot read a meshopt glb", raw_load_failed)
+
+ decoded, suffix = gltf_meshopt.decode_if_meshopt(packed_bytes, ".glb")
+ check("the decode returns a glb", suffix == ".glb" and decoded[:4] == b"glTF", suffix)
+ check("the decode is not a passthrough", decoded != packed_bytes)
+ check(
+ "the decoded asset no longer declares the extension",
+ not gltf_meshopt.uses_meshopt(gltf_meshopt.gltf_document(decoded, ".glb")),
+ )
+
+ mesh = trimesh.load(io.BytesIO(decoded), file_type="glb", force="mesh", process=False)
+ check(
+ "the decoded asset loads as real geometry",
+ len(mesh.faces) > 0 and len(mesh.vertices) > 0,
+ f"faces={len(mesh.faces)}",
+ )
+ source = trimesh.load(io.BytesIO(plain_glb), file_type="glb", force="mesh", process=False)
+ check(
+ "the decoded geometry matches the source face count",
+ len(mesh.faces) == len(source.faces),
+ f"{len(mesh.faces)} vs {len(source.faces)}",
+ )
+else:
+ original_bin = gltf_meshopt.GLTFPACK_BIN
+ try:
+ gltf_meshopt.GLTFPACK_BIN = "gltfpack-not-installed"
+ gltf_meshopt.transcode_meshopt(plain_glb, ".glb")
+ check("a missing gltfpack is a readable error", False, "no ValueError raised")
+ except ValueError as exc:
+ check(
+ "a missing gltfpack is a readable error",
+ gltf_meshopt.MESHOPT_EXTENSION in str(exc),
+ str(exc),
+ )
+ finally:
+ gltf_meshopt.GLTFPACK_BIN = original_bin
+
+print(f"\n{PASS} checks passed")
diff --git a/workers/remesh/test_remesh.py b/workers/remesh/test_remesh.py
index bdeeb8b5d..7ef8abddc 100644
--- a/workers/remesh/test_remesh.py
+++ b/workers/remesh/test_remesh.py
@@ -560,4 +560,47 @@ if has_bpy:
check("fbx convert reports no quads and no bake", meta["quad_ratio"] == 0.0 and meta["textured"] is False)
+# ── meshopt-compressed input ─────────────────────────────────────────────────
+# Callers hand this worker avatar URLs, and most three.ws avatars are saved with
+# EXT_meshopt_compression, which trimesh cannot read: every remesh of one failed
+# until _fetch_mesh started transcoding. gltf_meshopt.py owns the decode (and
+# has its own suite); this pins that the worker's own loaders accept the result.
+
+import gltf_meshopt # noqa: E402
+
+_source = trimesh.creation.icosphere(subdivisions=2)
+_plain_glb = trimesh.Scene({"a": _source}).export(file_type="glb")
+
+if shutil.which(gltf_meshopt.GLTFPACK_BIN):
+ with tempfile.TemporaryDirectory() as _packdir:
+ _raw = Path(_packdir) / "raw.glb"
+ _packed = Path(_packdir) / "packed.glb"
+ _raw.write_bytes(_plain_glb)
+ subprocess.run(
+ [gltf_meshopt.GLTFPACK_BIN, "-i", str(_raw), "-o", str(_packed), "-cc"],
+ capture_output=True,
+ check=True,
+ timeout=gltf_meshopt.GLTFPACK_TIMEOUT_S,
+ )
+ _packed_bytes = _packed.read_bytes()
+
+ try:
+ remesh._load_concatenated(_packed_bytes, ".glb")
+ _raw_failed = False
+ except Exception: # noqa: BLE001: the exact trimesh error is not the contract
+ _raw_failed = True
+ check("a compressed glb is unreadable without the decode", _raw_failed)
+
+ _decoded, _suffix = gltf_meshopt.decode_if_meshopt(_packed_bytes, ".glb")
+ _mesh = remesh._load_concatenated(_decoded, _suffix)
+ check(
+ "the triangle loader accepts a decoded meshopt glb",
+ len(_mesh.faces) == len(_source.faces),
+ f"{len(_mesh.faces)} vs {len(_source.faces)}",
+ )
+ _textured = remesh._load_textured(_decoded, _suffix)
+ check("the textured loader accepts a decoded meshopt glb", len(_textured.faces) > 0)
+else:
+ SKIPPED.append("meshopt decode (no gltfpack binary)")
+
print(f"\n{PASSED} checks passed" + (f", {len(SKIPPED)} sections skipped: {', '.join(SKIPPED)}" if SKIPPED else ""))
diff --git a/workers/rig/Dockerfile b/workers/rig/Dockerfile
index cdab141aa..89c269e25 100644
--- a/workers/rig/Dockerfile
+++ b/workers/rig/Dockerfile
@@ -1,4 +1,19 @@
+# gltfpack (zeux/meshoptimizer, MIT) decodes EXT_meshopt_compression, which
+# trimesh cannot read and which most three.ws avatars ship as. Pinned by release
+# tag and checksum so the image never picks up a binary we did not audit.
+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 ca-certificates curl unzip \
+ && 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.1.1-runtime-ubuntu22.04
+COPY --from=gltfpack /usr/local/bin/gltfpack /usr/local/bin/gltfpack
# runtime (not devel) base: every heavy dependency (torch, torch-cluster,
# pytorch3d) installs from prebuilt cu121 wheels, so no nvcc is needed.
@@ -41,8 +56,8 @@ RUN git clone https://github.com/jasongzy/Make-It-Animatable.git /app/mia \
&& rm -rf /app/mia/.git
WORKDIR /app
-COPY worker_security.py rig_glb.py blendshapes.py engine_mia.py main.py entrypoint.sh /app/
-COPY test_rig_glb.py test_blendshapes.py test_pipeline.py /app/
+COPY worker_security.py gltf_meshopt.py rig_glb.py blendshapes.py engine_mia.py main.py entrypoint.sh /app/
+COPY test_rig_glb.py test_blendshapes.py test_pipeline.py test_gltf_meshopt.py /app/
RUN chmod +x /app/entrypoint.sh
# Build-time guards, the same pattern workers/garment-forge uses. These three
@@ -53,7 +68,8 @@ RUN chmod +x /app/entrypoint.sh
# keys on, ARKit-52 targetNames on the head only, textures byte-preserved).
RUN python3 /app/test_rig_glb.py \
&& python3 /app/test_blendshapes.py \
- && python3 /app/test_pipeline.py
+ && python3 /app/test_pipeline.py \
+ && python3 /app/test_gltf_meshopt.py
# Weights, Mixamo bone templates, and the baked ARKit template are staged in
# GCS (stage-assets.sh) and mounted at /weights by Cloud Run; entrypoint.sh
diff --git a/workers/rig/gltf_meshopt.py b/workers/rig/gltf_meshopt.py
new file mode 100644
index 000000000..10f7ba4ad
--- /dev/null
+++ b/workers/rig/gltf_meshopt.py
@@ -0,0 +1,107 @@
+"""EXT_meshopt_compression decoding for caller-supplied glTF input.
+
+Vendored byte-identical into every worker that loads a mesh a caller handed it,
+exactly like worker_security.py: each worker's Docker build context is its own
+directory, so `../` is unreachable. `npm run check:vendored` fails if the copies
+drift apart.
+
+Why it exists: trimesh has no decoder for EXT_meshopt_compression. A compressed
+asset stores its geometry in compressed buffer views and declares a second,
+empty "fallback" buffer that only exists once something decodes into it, so
+trimesh dies on the bufferView lookup with a bare `IndexError: list index out of
+range`. Meshopt is what gltfpack emits and what most three.ws avatars ship as,
+so this was a hard failure on our own assets (verified 2026-08-13:
+/avatars/michelle.glb failed every stylize filter in production). gltfpack is
+the same project's CLI and decodes what it encoded, so the fix is to transcode
+the asset to plain glTF before any reader touches it.
+
+The binary is pinned by release tag and checksum in each worker's Dockerfile.
+Set GLTFPACK_BIN to run the path against your own copy locally.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import subprocess
+import tempfile
+from pathlib import Path
+from typing import Optional
+
+log = logging.getLogger("gltf-meshopt")
+
+MESHOPT_EXTENSION = "EXT_meshopt_compression"
+GLTFPACK_BIN = os.environ.get("GLTFPACK_BIN", "gltfpack")
+GLTFPACK_TIMEOUT_S = int(os.environ.get("GLTFPACK_TIMEOUT_S", "120"))
+
+
+def gltf_document(data: bytes, suffix: str = ".glb") -> Optional[dict]:
+ """The glTF JSON of a .glb/.gltf payload, or None when it is neither."""
+ if suffix == ".gltf":
+ try:
+ return json.loads(data)
+ except ValueError:
+ return None
+ if suffix != ".glb" or len(data) < 20 or data[:4] != b"glTF":
+ return None
+ chunk_length = int.from_bytes(data[12:16], "little")
+ if data[16:20] != b"JSON":
+ return None
+ try:
+ return json.loads(data[20:20 + chunk_length])
+ except ValueError:
+ return None
+
+
+def uses_meshopt(document: Optional[dict]) -> bool:
+ """True when the asset needs a meshopt decode before any reader can use it.
+
+ Checked against both extension lists: an asset that only *uses* the
+ extension still stores its geometry in the compressed views, and its
+ fallback buffer stays empty until something decodes into it.
+ """
+ if not document:
+ return False
+ declared = set(document.get("extensionsRequired") or []) | set(document.get("extensionsUsed") or [])
+ return MESHOPT_EXTENSION in declared
+
+
+def transcode_meshopt(data: bytes, suffix: str = ".glb") -> bytes:
+ """Rewrite a meshopt-compressed asset as a plain GLB with gltfpack.
+
+ `-noq` keeps the source quantization instead of re-quantizing on the way
+ out, so downstream geometry is derived from what the author shipped.
+ """
+ with tempfile.TemporaryDirectory() as tmpdir:
+ src = Path(tmpdir) / f"input{suffix}"
+ dst = Path(tmpdir) / "decoded.glb"
+ src.write_bytes(data)
+ try:
+ proc = subprocess.run(
+ [GLTFPACK_BIN, "-i", str(src), "-o", str(dst), "-noq"],
+ capture_output=True,
+ timeout=GLTFPACK_TIMEOUT_S,
+ )
+ except FileNotFoundError as exc:
+ raise ValueError(
+ f"input uses {MESHOPT_EXTENSION} and the gltfpack decoder is not installed"
+ ) from exc
+ except subprocess.TimeoutExpired as exc:
+ raise ValueError(f"{MESHOPT_EXTENSION} decode timed out") from exc
+ if proc.returncode != 0 or not dst.exists():
+ detail = (proc.stderr or b"").decode("utf-8", "replace").strip().splitlines()
+ raise ValueError(f"{MESHOPT_EXTENSION} decode failed: {detail[-1][:200] if detail else 'no output'}")
+ return dst.read_bytes()
+
+
+def decode_if_meshopt(data: bytes, suffix: str = ".glb") -> tuple[bytes, str]:
+ """Return (data, suffix) ready for trimesh, decoding meshopt when present.
+
+ A payload that is not compressed glTF is handed back untouched, so this is
+ safe to call on every input path.
+ """
+ if not uses_meshopt(gltf_document(data, suffix)):
+ return data, suffix
+ log.info("input declares %s; decoding with gltfpack before load", MESHOPT_EXTENSION)
+ return transcode_meshopt(data, suffix), ".glb"
diff --git a/workers/rig/main.py b/workers/rig/main.py
index 87a5090ee..4840fe5c4 100644
--- a/workers/rig/main.py
+++ b/workers/rig/main.py
@@ -58,6 +58,7 @@ from pydantic import BaseModel
import engine_mia
import rig_glb
from blendshapes import head_mask_from_weights, load_template, transfer_blendshapes
+from gltf_meshopt import decode_if_meshopt
from worker_security import (
UnsafeUrlError,
fetch_remote_bytes_async,
@@ -162,6 +163,11 @@ async def _run_task(task_id: str, mesh_gcs_url: str, want_blendshapes: bool) ->
except UnsafeUrlError as exc:
raise RuntimeError(f"refused to fetch mesh url: {exc}") from exc
+ # A meshopt-compressed GLB is transcoded before anything reads
+ # it: neither trimesh nor pygltflib can decode that extension,
+ # and it is the format most three.ws avatars ship as.
+ mesh_bytes, _ = decode_if_meshopt(mesh_bytes, ".glb")
+
rigged = await loop.run_in_executor(
None, _rig_sync, mesh_bytes, want_blendshapes
)
diff --git a/workers/rig/test_gltf_meshopt.py b/workers/rig/test_gltf_meshopt.py
new file mode 100644
index 000000000..2d2e9d502
--- /dev/null
+++ b/workers/rig/test_gltf_meshopt.py
@@ -0,0 +1,141 @@
+"""Tests for gltf_meshopt.py, the shared EXT_meshopt_compression decoder.
+
+Vendored byte-identical into every worker that ships gltf_meshopt.py, exactly
+like the module itself, and run as a Docker build gate in each of them:
+
+ python3 test_gltf_meshopt.py
+
+The round-trip section needs the `gltfpack` binary (present in every worker
+image, pinned in the Dockerfile). Without it the suite still runs and pins the
+readable failure a caller gets instead, so a laptop run stays green.
+"""
+
+from __future__ import annotations
+
+import io
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+import trimesh # noqa: E402
+
+import gltf_meshopt # noqa: E402
+
+PASS = 0
+
+
+def check(name: str, condition: bool, detail: str = "") -> None:
+ global PASS
+ if not condition:
+ print(f"FAIL {name} {detail}")
+ sys.exit(1)
+ PASS += 1
+ print(f"ok {name}")
+
+
+plain_glb = trimesh.Scene({"a": trimesh.creation.icosphere(subdivisions=2)}).export(file_type="glb")
+
+# ── document parsing ────────────────────────────────────────────────────────────
+
+doc = gltf_meshopt.gltf_document(plain_glb, ".glb")
+check("a glb's json chunk parses", isinstance(doc, dict) and "asset" in doc, str(type(doc)))
+check(
+ "a gltf json payload parses",
+ isinstance(gltf_meshopt.gltf_document(b'{"asset":{"version":"2.0"}}', ".gltf"), dict),
+)
+for payload, suffix, label in (
+ (b"ply\nformat ascii 1.0\n", ".ply", "a ply"),
+ (b"not json at all", ".gltf", "malformed gltf json"),
+ (b"glTF" + b"\x00" * 4, ".glb", "a truncated glb"),
+ (b"solid mesh\n", ".stl", "an stl"),
+):
+ check(f"{label} yields no gltf document", gltf_meshopt.gltf_document(payload, suffix) is None)
+
+# ── extension detection ─────────────────────────────────────────────────────────
+
+check("a plain glb needs no decode", not gltf_meshopt.uses_meshopt(doc))
+check("an empty document needs no decode", not gltf_meshopt.uses_meshopt(None))
+for declared in ("extensionsRequired", "extensionsUsed"):
+ check(
+ f"{declared} announcing {gltf_meshopt.MESHOPT_EXTENSION} needs a decode",
+ gltf_meshopt.uses_meshopt({declared: [gltf_meshopt.MESHOPT_EXTENSION]}),
+ )
+check(
+ "an unrelated extension needs no decode",
+ not gltf_meshopt.uses_meshopt({"extensionsUsed": ["KHR_materials_unlit"]}),
+)
+check(
+ "an uncompressed payload passes through decode_if_meshopt untouched",
+ gltf_meshopt.decode_if_meshopt(plain_glb, ".glb") == (plain_glb, ".glb"),
+)
+
+# ── the real decode ─────────────────────────────────────────────────────────────
+
+if shutil.which(gltf_meshopt.GLTFPACK_BIN):
+ with tempfile.TemporaryDirectory() as packdir:
+ raw = Path(packdir) / "raw.glb"
+ packed = Path(packdir) / "packed.glb"
+ raw.write_bytes(plain_glb)
+ subprocess.run(
+ [gltf_meshopt.GLTFPACK_BIN, "-i", str(raw), "-o", str(packed), "-cc"],
+ capture_output=True,
+ check=True,
+ timeout=gltf_meshopt.GLTFPACK_TIMEOUT_S,
+ )
+ packed_bytes = packed.read_bytes()
+
+ check(
+ "a gltfpack-compressed glb is detected",
+ gltf_meshopt.uses_meshopt(gltf_meshopt.gltf_document(packed_bytes, ".glb")),
+ )
+
+ # The bug this module exists for: trimesh dies on the compressed asset's
+ # fallback buffer, which is why every worker loading one failed.
+ try:
+ trimesh.load(io.BytesIO(packed_bytes), file_type="glb", force="mesh", process=False)
+ raw_load_failed = False
+ except Exception: # noqa: BLE001: the exact trimesh error is not the contract
+ raw_load_failed = True
+ check("trimesh alone cannot read a meshopt glb", raw_load_failed)
+
+ decoded, suffix = gltf_meshopt.decode_if_meshopt(packed_bytes, ".glb")
+ check("the decode returns a glb", suffix == ".glb" and decoded[:4] == b"glTF", suffix)
+ check("the decode is not a passthrough", decoded != packed_bytes)
+ check(
+ "the decoded asset no longer declares the extension",
+ not gltf_meshopt.uses_meshopt(gltf_meshopt.gltf_document(decoded, ".glb")),
+ )
+
+ mesh = trimesh.load(io.BytesIO(decoded), file_type="glb", force="mesh", process=False)
+ check(
+ "the decoded asset loads as real geometry",
+ len(mesh.faces) > 0 and len(mesh.vertices) > 0,
+ f"faces={len(mesh.faces)}",
+ )
+ source = trimesh.load(io.BytesIO(plain_glb), file_type="glb", force="mesh", process=False)
+ check(
+ "the decoded geometry matches the source face count",
+ len(mesh.faces) == len(source.faces),
+ f"{len(mesh.faces)} vs {len(source.faces)}",
+ )
+else:
+ original_bin = gltf_meshopt.GLTFPACK_BIN
+ try:
+ gltf_meshopt.GLTFPACK_BIN = "gltfpack-not-installed"
+ gltf_meshopt.transcode_meshopt(plain_glb, ".glb")
+ check("a missing gltfpack is a readable error", False, "no ValueError raised")
+ except ValueError as exc:
+ check(
+ "a missing gltfpack is a readable error",
+ gltf_meshopt.MESHOPT_EXTENSION in str(exc),
+ str(exc),
+ )
+ finally:
+ gltf_meshopt.GLTFPACK_BIN = original_bin
+
+print(f"\n{PASS} checks passed")
diff --git a/workers/segment/Dockerfile b/workers/segment/Dockerfile
index 5dc2e1991..1d948dd75 100644
--- a/workers/segment/Dockerfile
+++ b/workers/segment/Dockerfile
@@ -1,4 +1,19 @@
+# gltfpack (zeux/meshoptimizer, MIT) decodes EXT_meshopt_compression, which
+# trimesh cannot read and which most three.ws avatars ship as. Pinned by release
+# tag and checksum so the image never picks up a binary we did not audit.
+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 ca-certificates curl unzip \
+ && 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 python:3.11-slim
+COPY --from=gltfpack /usr/local/bin/gltfpack /usr/local/bin/gltfpack
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
@@ -15,6 +30,7 @@ RUN pip install -r /app/requirements.txt
WORKDIR /app
COPY worker_security.py /app/worker_security.py
+COPY gltf_meshopt.py /app/gltf_meshopt.py
COPY segment_core.py /app/segment_core.py
COPY main.py /app/main.py
@@ -23,7 +39,8 @@ COPY main.py /app/main.py
# segmentation that stops being reproducible, fails the image instead of
# reaching production.
COPY test_segment_core.py /app/test_segment_core.py
-RUN python3 test_segment_core.py
+COPY test_gltf_meshopt.py /app/test_gltf_meshopt.py
+RUN python3 test_segment_core.py && python3 test_gltf_meshopt.py
EXPOSE 8080
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "1"]
diff --git a/workers/segment/gltf_meshopt.py b/workers/segment/gltf_meshopt.py
new file mode 100644
index 000000000..10f7ba4ad
--- /dev/null
+++ b/workers/segment/gltf_meshopt.py
@@ -0,0 +1,107 @@
+"""EXT_meshopt_compression decoding for caller-supplied glTF input.
+
+Vendored byte-identical into every worker that loads a mesh a caller handed it,
+exactly like worker_security.py: each worker's Docker build context is its own
+directory, so `../` is unreachable. `npm run check:vendored` fails if the copies
+drift apart.
+
+Why it exists: trimesh has no decoder for EXT_meshopt_compression. A compressed
+asset stores its geometry in compressed buffer views and declares a second,
+empty "fallback" buffer that only exists once something decodes into it, so
+trimesh dies on the bufferView lookup with a bare `IndexError: list index out of
+range`. Meshopt is what gltfpack emits and what most three.ws avatars ship as,
+so this was a hard failure on our own assets (verified 2026-08-13:
+/avatars/michelle.glb failed every stylize filter in production). gltfpack is
+the same project's CLI and decodes what it encoded, so the fix is to transcode
+the asset to plain glTF before any reader touches it.
+
+The binary is pinned by release tag and checksum in each worker's Dockerfile.
+Set GLTFPACK_BIN to run the path against your own copy locally.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import subprocess
+import tempfile
+from pathlib import Path
+from typing import Optional
+
+log = logging.getLogger("gltf-meshopt")
+
+MESHOPT_EXTENSION = "EXT_meshopt_compression"
+GLTFPACK_BIN = os.environ.get("GLTFPACK_BIN", "gltfpack")
+GLTFPACK_TIMEOUT_S = int(os.environ.get("GLTFPACK_TIMEOUT_S", "120"))
+
+
+def gltf_document(data: bytes, suffix: str = ".glb") -> Optional[dict]:
+ """The glTF JSON of a .glb/.gltf payload, or None when it is neither."""
+ if suffix == ".gltf":
+ try:
+ return json.loads(data)
+ except ValueError:
+ return None
+ if suffix != ".glb" or len(data) < 20 or data[:4] != b"glTF":
+ return None
+ chunk_length = int.from_bytes(data[12:16], "little")
+ if data[16:20] != b"JSON":
+ return None
+ try:
+ return json.loads(data[20:20 + chunk_length])
+ except ValueError:
+ return None
+
+
+def uses_meshopt(document: Optional[dict]) -> bool:
+ """True when the asset needs a meshopt decode before any reader can use it.
+
+ Checked against both extension lists: an asset that only *uses* the
+ extension still stores its geometry in the compressed views, and its
+ fallback buffer stays empty until something decodes into it.
+ """
+ if not document:
+ return False
+ declared = set(document.get("extensionsRequired") or []) | set(document.get("extensionsUsed") or [])
+ return MESHOPT_EXTENSION in declared
+
+
+def transcode_meshopt(data: bytes, suffix: str = ".glb") -> bytes:
+ """Rewrite a meshopt-compressed asset as a plain GLB with gltfpack.
+
+ `-noq` keeps the source quantization instead of re-quantizing on the way
+ out, so downstream geometry is derived from what the author shipped.
+ """
+ with tempfile.TemporaryDirectory() as tmpdir:
+ src = Path(tmpdir) / f"input{suffix}"
+ dst = Path(tmpdir) / "decoded.glb"
+ src.write_bytes(data)
+ try:
+ proc = subprocess.run(
+ [GLTFPACK_BIN, "-i", str(src), "-o", str(dst), "-noq"],
+ capture_output=True,
+ timeout=GLTFPACK_TIMEOUT_S,
+ )
+ except FileNotFoundError as exc:
+ raise ValueError(
+ f"input uses {MESHOPT_EXTENSION} and the gltfpack decoder is not installed"
+ ) from exc
+ except subprocess.TimeoutExpired as exc:
+ raise ValueError(f"{MESHOPT_EXTENSION} decode timed out") from exc
+ if proc.returncode != 0 or not dst.exists():
+ detail = (proc.stderr or b"").decode("utf-8", "replace").strip().splitlines()
+ raise ValueError(f"{MESHOPT_EXTENSION} decode failed: {detail[-1][:200] if detail else 'no output'}")
+ return dst.read_bytes()
+
+
+def decode_if_meshopt(data: bytes, suffix: str = ".glb") -> tuple[bytes, str]:
+ """Return (data, suffix) ready for trimesh, decoding meshopt when present.
+
+ A payload that is not compressed glTF is handed back untouched, so this is
+ safe to call on every input path.
+ """
+ if not uses_meshopt(gltf_document(data, suffix)):
+ return data, suffix
+ log.info("input declares %s; decoding with gltfpack before load", MESHOPT_EXTENSION)
+ return transcode_meshopt(data, suffix), ".glb"
diff --git a/workers/segment/main.py b/workers/segment/main.py
index 904f01a9b..8b4ac1819 100644
--- a/workers/segment/main.py
+++ b/workers/segment/main.py
@@ -55,6 +55,7 @@ from google.cloud import storage
from google.cloud.storage.retry import DEFAULT_RETRY
from pydantic import BaseModel, Field, field_validator
+from gltf_meshopt import decode_if_meshopt
from worker_security import (
UnsafeUrlError,
fetch_remote_bytes,
@@ -178,7 +179,13 @@ def _fetch_mesh(url: str) -> tuple[bytes, str]:
suffix = Path(url.split("?")[0]).suffix.lower()
if suffix not in SUPPORTED_INPUT_FORMATS:
suffix = ".glb"
- return data, suffix
+ # A meshopt-compressed asset is transcoded here, before segment_core loads
+ # it: trimesh cannot read one, and it is the format most three.ws avatars
+ # ship as. Anything else passes through untouched.
+ try:
+ return decode_if_meshopt(data, suffix)
+ except ValueError as exc:
+ raise seg.SegmentInputError(str(exc)) from exc
def _run_segmentation(
diff --git a/workers/segment/test_gltf_meshopt.py b/workers/segment/test_gltf_meshopt.py
new file mode 100644
index 000000000..2d2e9d502
--- /dev/null
+++ b/workers/segment/test_gltf_meshopt.py
@@ -0,0 +1,141 @@
+"""Tests for gltf_meshopt.py, the shared EXT_meshopt_compression decoder.
+
+Vendored byte-identical into every worker that ships gltf_meshopt.py, exactly
+like the module itself, and run as a Docker build gate in each of them:
+
+ python3 test_gltf_meshopt.py
+
+The round-trip section needs the `gltfpack` binary (present in every worker
+image, pinned in the Dockerfile). Without it the suite still runs and pins the
+readable failure a caller gets instead, so a laptop run stays green.
+"""
+
+from __future__ import annotations
+
+import io
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+import trimesh # noqa: E402
+
+import gltf_meshopt # noqa: E402
+
+PASS = 0
+
+
+def check(name: str, condition: bool, detail: str = "") -> None:
+ global PASS
+ if not condition:
+ print(f"FAIL {name} {detail}")
+ sys.exit(1)
+ PASS += 1
+ print(f"ok {name}")
+
+
+plain_glb = trimesh.Scene({"a": trimesh.creation.icosphere(subdivisions=2)}).export(file_type="glb")
+
+# ── document parsing ────────────────────────────────────────────────────────────
+
+doc = gltf_meshopt.gltf_document(plain_glb, ".glb")
+check("a glb's json chunk parses", isinstance(doc, dict) and "asset" in doc, str(type(doc)))
+check(
+ "a gltf json payload parses",
+ isinstance(gltf_meshopt.gltf_document(b'{"asset":{"version":"2.0"}}', ".gltf"), dict),
+)
+for payload, suffix, label in (
+ (b"ply\nformat ascii 1.0\n", ".ply", "a ply"),
+ (b"not json at all", ".gltf", "malformed gltf json"),
+ (b"glTF" + b"\x00" * 4, ".glb", "a truncated glb"),
+ (b"solid mesh\n", ".stl", "an stl"),
+):
+ check(f"{label} yields no gltf document", gltf_meshopt.gltf_document(payload, suffix) is None)
+
+# ── extension detection ─────────────────────────────────────────────────────────
+
+check("a plain glb needs no decode", not gltf_meshopt.uses_meshopt(doc))
+check("an empty document needs no decode", not gltf_meshopt.uses_meshopt(None))
+for declared in ("extensionsRequired", "extensionsUsed"):
+ check(
+ f"{declared} announcing {gltf_meshopt.MESHOPT_EXTENSION} needs a decode",
+ gltf_meshopt.uses_meshopt({declared: [gltf_meshopt.MESHOPT_EXTENSION]}),
+ )
+check(
+ "an unrelated extension needs no decode",
+ not gltf_meshopt.uses_meshopt({"extensionsUsed": ["KHR_materials_unlit"]}),
+)
+check(
+ "an uncompressed payload passes through decode_if_meshopt untouched",
+ gltf_meshopt.decode_if_meshopt(plain_glb, ".glb") == (plain_glb, ".glb"),
+)
+
+# ── the real decode ─────────────────────────────────────────────────────────────
+
+if shutil.which(gltf_meshopt.GLTFPACK_BIN):
+ with tempfile.TemporaryDirectory() as packdir:
+ raw = Path(packdir) / "raw.glb"
+ packed = Path(packdir) / "packed.glb"
+ raw.write_bytes(plain_glb)
+ subprocess.run(
+ [gltf_meshopt.GLTFPACK_BIN, "-i", str(raw), "-o", str(packed), "-cc"],
+ capture_output=True,
+ check=True,
+ timeout=gltf_meshopt.GLTFPACK_TIMEOUT_S,
+ )
+ packed_bytes = packed.read_bytes()
+
+ check(
+ "a gltfpack-compressed glb is detected",
+ gltf_meshopt.uses_meshopt(gltf_meshopt.gltf_document(packed_bytes, ".glb")),
+ )
+
+ # The bug this module exists for: trimesh dies on the compressed asset's
+ # fallback buffer, which is why every worker loading one failed.
+ try:
+ trimesh.load(io.BytesIO(packed_bytes), file_type="glb", force="mesh", process=False)
+ raw_load_failed = False
+ except Exception: # noqa: BLE001: the exact trimesh error is not the contract
+ raw_load_failed = True
+ check("trimesh alone cannot read a meshopt glb", raw_load_failed)
+
+ decoded, suffix = gltf_meshopt.decode_if_meshopt(packed_bytes, ".glb")
+ check("the decode returns a glb", suffix == ".glb" and decoded[:4] == b"glTF", suffix)
+ check("the decode is not a passthrough", decoded != packed_bytes)
+ check(
+ "the decoded asset no longer declares the extension",
+ not gltf_meshopt.uses_meshopt(gltf_meshopt.gltf_document(decoded, ".glb")),
+ )
+
+ mesh = trimesh.load(io.BytesIO(decoded), file_type="glb", force="mesh", process=False)
+ check(
+ "the decoded asset loads as real geometry",
+ len(mesh.faces) > 0 and len(mesh.vertices) > 0,
+ f"faces={len(mesh.faces)}",
+ )
+ source = trimesh.load(io.BytesIO(plain_glb), file_type="glb", force="mesh", process=False)
+ check(
+ "the decoded geometry matches the source face count",
+ len(mesh.faces) == len(source.faces),
+ f"{len(mesh.faces)} vs {len(source.faces)}",
+ )
+else:
+ original_bin = gltf_meshopt.GLTFPACK_BIN
+ try:
+ gltf_meshopt.GLTFPACK_BIN = "gltfpack-not-installed"
+ gltf_meshopt.transcode_meshopt(plain_glb, ".glb")
+ check("a missing gltfpack is a readable error", False, "no ValueError raised")
+ except ValueError as exc:
+ check(
+ "a missing gltfpack is a readable error",
+ gltf_meshopt.MESHOPT_EXTENSION in str(exc),
+ str(exc),
+ )
+ finally:
+ gltf_meshopt.GLTFPACK_BIN = original_bin
+
+print(f"\n{PASS} checks passed")
diff --git a/workers/segment/test_segment_core.py b/workers/segment/test_segment_core.py
index 4e7de6b67..aecc1569c 100644
--- a/workers/segment/test_segment_core.py
+++ b/workers/segment/test_segment_core.py
@@ -265,4 +265,51 @@ check("a zero-span axis is safe", isinstance(seg._region_name(np.array([0.5, 0.0
check("duplicate regions get numbered", seg._unique_names(["top", "top"]) == ["top-1", "top-2"])
check("a unique region keeps its name", seg._unique_names(["top", "core"]) == ["top", "core"])
+# ── meshopt-compressed input ─────────────────────────────────────────────────
+# Callers segment avatar URLs, and most three.ws avatars are saved with
+# EXT_meshopt_compression, which trimesh cannot read: every segmentation of one
+# failed until main._fetch_mesh started transcoding. gltf_meshopt.py owns the
+# decode (and has its own suite); this pins that load_concatenated takes what it
+# produces.
+
+import shutil # noqa: E402
+import subprocess # noqa: E402
+import tempfile # noqa: E402
+from pathlib import Path # noqa: E402
+
+import gltf_meshopt # noqa: E402
+
+_source = trimesh.creation.icosphere(subdivisions=2)
+_plain_glb = trimesh.Scene({"a": _source}).export(file_type="glb")
+
+if shutil.which(gltf_meshopt.GLTFPACK_BIN):
+ with tempfile.TemporaryDirectory() as _packdir:
+ _raw = Path(_packdir) / "raw.glb"
+ _packed = Path(_packdir) / "packed.glb"
+ _raw.write_bytes(_plain_glb)
+ subprocess.run(
+ [gltf_meshopt.GLTFPACK_BIN, "-i", str(_raw), "-o", str(_packed), "-cc"],
+ capture_output=True,
+ check=True,
+ timeout=gltf_meshopt.GLTFPACK_TIMEOUT_S,
+ )
+ _packed_bytes = _packed.read_bytes()
+
+ try:
+ seg.load_concatenated(_packed_bytes, ".glb")
+ _raw_failed = False
+ except Exception: # noqa: BLE001: the exact trimesh error is not the contract
+ _raw_failed = True
+ check("a compressed glb is unreadable without the decode", _raw_failed)
+
+ _decoded, _suffix = gltf_meshopt.decode_if_meshopt(_packed_bytes, ".glb")
+ _mesh = seg.load_concatenated(_decoded, _suffix)
+ check(
+ "the segmenter loads a decoded meshopt glb",
+ len(_mesh.faces) == len(_source.faces),
+ f"{len(_mesh.faces)} vs {len(_source.faces)}",
+ )
+else:
+ print("skip meshopt decode section (no gltfpack binary)")
+
print(f"\nOK {PASS} checks passed")
diff --git a/workers/stylize/Dockerfile b/workers/stylize/Dockerfile
index 38d857a86..f1ccb7d4f 100644
--- a/workers/stylize/Dockerfile
+++ b/workers/stylize/Dockerfile
@@ -34,17 +34,19 @@ WORKDIR /app
# vendored into this directory exactly like worker_security.py: the build
# context is workers/stylize, so ../ is unreachable. Keep the copy byte-identical.
COPY worker_security.py /app/worker_security.py
+COPY gltf_meshopt.py /app/gltf_meshopt.py
COPY oin.py /app/oin.py
COPY oin_upload.py /app/oin_upload.py
COPY main.py /app/main.py
COPY test_stylize.py /app/test_stylize.py
+COPY test_gltf_meshopt.py /app/test_gltf_meshopt.py
# Build-time guard: the four filters, the color sampler, the export round-trip,
# the memory caps, the SSRF gate, and the upload retry policy must pass their
# unit suite or the image does not ship. This is also the only place open3d's
# decimation path (used by voronoi + lowpoly) and the gltfpack meshopt decode are
# exercised; the local run falls back to trimesh and skips the meshopt case.
-RUN python /app/test_stylize.py
+RUN python /app/test_stylize.py && python /app/test_gltf_meshopt.py
EXPOSE 8080
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "1"]
diff --git a/workers/stylize/gltf_meshopt.py b/workers/stylize/gltf_meshopt.py
new file mode 100644
index 000000000..10f7ba4ad
--- /dev/null
+++ b/workers/stylize/gltf_meshopt.py
@@ -0,0 +1,107 @@
+"""EXT_meshopt_compression decoding for caller-supplied glTF input.
+
+Vendored byte-identical into every worker that loads a mesh a caller handed it,
+exactly like worker_security.py: each worker's Docker build context is its own
+directory, so `../` is unreachable. `npm run check:vendored` fails if the copies
+drift apart.
+
+Why it exists: trimesh has no decoder for EXT_meshopt_compression. A compressed
+asset stores its geometry in compressed buffer views and declares a second,
+empty "fallback" buffer that only exists once something decodes into it, so
+trimesh dies on the bufferView lookup with a bare `IndexError: list index out of
+range`. Meshopt is what gltfpack emits and what most three.ws avatars ship as,
+so this was a hard failure on our own assets (verified 2026-08-13:
+/avatars/michelle.glb failed every stylize filter in production). gltfpack is
+the same project's CLI and decodes what it encoded, so the fix is to transcode
+the asset to plain glTF before any reader touches it.
+
+The binary is pinned by release tag and checksum in each worker's Dockerfile.
+Set GLTFPACK_BIN to run the path against your own copy locally.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import subprocess
+import tempfile
+from pathlib import Path
+from typing import Optional
+
+log = logging.getLogger("gltf-meshopt")
+
+MESHOPT_EXTENSION = "EXT_meshopt_compression"
+GLTFPACK_BIN = os.environ.get("GLTFPACK_BIN", "gltfpack")
+GLTFPACK_TIMEOUT_S = int(os.environ.get("GLTFPACK_TIMEOUT_S", "120"))
+
+
+def gltf_document(data: bytes, suffix: str = ".glb") -> Optional[dict]:
+ """The glTF JSON of a .glb/.gltf payload, or None when it is neither."""
+ if suffix == ".gltf":
+ try:
+ return json.loads(data)
+ except ValueError:
+ return None
+ if suffix != ".glb" or len(data) < 20 or data[:4] != b"glTF":
+ return None
+ chunk_length = int.from_bytes(data[12:16], "little")
+ if data[16:20] != b"JSON":
+ return None
+ try:
+ return json.loads(data[20:20 + chunk_length])
+ except ValueError:
+ return None
+
+
+def uses_meshopt(document: Optional[dict]) -> bool:
+ """True when the asset needs a meshopt decode before any reader can use it.
+
+ Checked against both extension lists: an asset that only *uses* the
+ extension still stores its geometry in the compressed views, and its
+ fallback buffer stays empty until something decodes into it.
+ """
+ if not document:
+ return False
+ declared = set(document.get("extensionsRequired") or []) | set(document.get("extensionsUsed") or [])
+ return MESHOPT_EXTENSION in declared
+
+
+def transcode_meshopt(data: bytes, suffix: str = ".glb") -> bytes:
+ """Rewrite a meshopt-compressed asset as a plain GLB with gltfpack.
+
+ `-noq` keeps the source quantization instead of re-quantizing on the way
+ out, so downstream geometry is derived from what the author shipped.
+ """
+ with tempfile.TemporaryDirectory() as tmpdir:
+ src = Path(tmpdir) / f"input{suffix}"
+ dst = Path(tmpdir) / "decoded.glb"
+ src.write_bytes(data)
+ try:
+ proc = subprocess.run(
+ [GLTFPACK_BIN, "-i", str(src), "-o", str(dst), "-noq"],
+ capture_output=True,
+ timeout=GLTFPACK_TIMEOUT_S,
+ )
+ except FileNotFoundError as exc:
+ raise ValueError(
+ f"input uses {MESHOPT_EXTENSION} and the gltfpack decoder is not installed"
+ ) from exc
+ except subprocess.TimeoutExpired as exc:
+ raise ValueError(f"{MESHOPT_EXTENSION} decode timed out") from exc
+ if proc.returncode != 0 or not dst.exists():
+ detail = (proc.stderr or b"").decode("utf-8", "replace").strip().splitlines()
+ raise ValueError(f"{MESHOPT_EXTENSION} decode failed: {detail[-1][:200] if detail else 'no output'}")
+ return dst.read_bytes()
+
+
+def decode_if_meshopt(data: bytes, suffix: str = ".glb") -> tuple[bytes, str]:
+ """Return (data, suffix) ready for trimesh, decoding meshopt when present.
+
+ A payload that is not compressed glTF is handed back untouched, so this is
+ safe to call on every input path.
+ """
+ if not uses_meshopt(gltf_document(data, suffix)):
+ return data, suffix
+ log.info("input declares %s; decoding with gltfpack before load", MESHOPT_EXTENSION)
+ return transcode_meshopt(data, suffix), ".glb"
diff --git a/workers/stylize/main.py b/workers/stylize/main.py
index 30ddecfd4..c2e1d701a 100644
--- a/workers/stylize/main.py
+++ b/workers/stylize/main.py
@@ -39,10 +39,8 @@ from __future__ import annotations
import asyncio
import io
-import json
import logging
import os
-import subprocess
import tempfile
import time
import uuid
@@ -56,6 +54,7 @@ from google.cloud.storage.retry import DEFAULT_RETRY
from pydantic import BaseModel, Field, field_validator
import oin
+from gltf_meshopt import decode_if_meshopt
from oin_upload import make_result_sink
from worker_security import (
UnsafeUrlError,
@@ -87,17 +86,6 @@ SUPPORTED_INPUT_FORMATS = {".glb", ".gltf", ".obj", ".stl", ".ply", ".fbx", ".of
SUPPORTED_OUTPUT_FORMATS = {"glb", "obj", "stl", "ply"}
MAX_MESH_BYTES = 128 * 1024 * 1024
-# trimesh has no EXT_meshopt_compression decoder, and a meshopt GLB's buffer 1 is
-# a fallback that only exists after decoding, so trimesh dies on the bufferView
-# lookup with a bare IndexError. Meshopt is what gltfpack emits and what most of
-# three.ws's own avatars ship as, so this was a hard failure on our own assets
-# (verified 2026-08-13: /avatars/michelle.glb failed every style in production).
-# gltfpack is the same project's CLI and decodes what it encoded: transcode the
-# input to plain glTF before trimesh ever sees it.
-MESHOPT_EXTENSION = "EXT_meshopt_compression"
-GLTFPACK_BIN = os.environ.get("GLTFPACK_BIN", "gltfpack")
-GLTFPACK_TIMEOUT_S = 120
-
# Hard safety caps so a hostile/huge input can never exhaust memory.
MAX_VOXELS = 60_000 # occupied surface cells rebuilt as cubes
MAX_LATTICE_EDGES = 6_000 # struts emitted for the voronoi shell
@@ -210,73 +198,13 @@ def _fetch_mesh(url: str) -> tuple[bytes, str]:
return data, suffix
-def _gltf_document(data: bytes, suffix: str) -> Optional[dict]:
- """The glTF JSON of a .glb/.gltf payload, or None when it is neither."""
- if suffix == ".gltf":
- try:
- return json.loads(data)
- except ValueError:
- return None
- if suffix != ".glb" or len(data) < 20 or data[:4] != b"glTF":
- return None
- chunk_length = int.from_bytes(data[12:16], "little")
- if data[16:20] != b"JSON":
- return None
- try:
- return json.loads(data[20:20 + chunk_length])
- except ValueError:
- return None
-
-
-def _uses_meshopt(document: Optional[dict]) -> bool:
- """True when the asset needs a meshopt decode before any reader can use it.
-
- Checked against both extension lists: a file that only *uses* the extension
- still stores its geometry in the compressed views, and its fallback buffer
- is empty until something decodes into it.
- """
- if not document:
- return False
- declared = set(document.get("extensionsRequired") or []) | set(document.get("extensionsUsed") or [])
- return MESHOPT_EXTENSION in declared
-
-
-def _transcode_meshopt(data: bytes, suffix: str) -> bytes:
- """Rewrite a meshopt-compressed asset as a plain GLB with gltfpack.
-
- `-noq` keeps the source quantization instead of re-quantizing on the way
- out, so the stylized result is derived from the geometry the author shipped.
- """
- with tempfile.TemporaryDirectory() as tmpdir:
- src = Path(tmpdir) / f"input{suffix}"
- dst = Path(tmpdir) / "decoded.glb"
- src.write_bytes(data)
- try:
- proc = subprocess.run(
- [GLTFPACK_BIN, "-i", str(src), "-o", str(dst), "-noq"],
- capture_output=True,
- timeout=GLTFPACK_TIMEOUT_S,
- )
- except FileNotFoundError as exc:
- raise ValueError(
- f"input uses {MESHOPT_EXTENSION} and the gltfpack decoder is not installed"
- ) from exc
- except subprocess.TimeoutExpired as exc:
- raise ValueError(f"{MESHOPT_EXTENSION} decode timed out") from exc
- if proc.returncode != 0 or not dst.exists():
- detail = (proc.stderr or b"").decode("utf-8", "replace").strip().splitlines()
- raise ValueError(f"{MESHOPT_EXTENSION} decode failed: {detail[-1][:200] if detail else 'no output'}")
- return dst.read_bytes()
-
-
def _load_single_mesh(data: bytes, suffix: str):
"""Load to a single concatenated Trimesh, keeping visual/color where present."""
import trimesh
- if _uses_meshopt(_gltf_document(data, suffix)):
- log.info("input declares %s; decoding with gltfpack before load", MESHOPT_EXTENSION)
- data = _transcode_meshopt(data, suffix)
- suffix = ".glb"
+ # A meshopt-compressed asset is transcoded first: trimesh cannot read one,
+ # and it is the format most three.ws avatars ship as.
+ data, suffix = decode_if_meshopt(data, suffix)
loaded = trimesh.load(io.BytesIO(data), file_type=suffix.lstrip("."), force="mesh", process=False)
if isinstance(loaded, trimesh.Scene):
diff --git a/workers/stylize/test_gltf_meshopt.py b/workers/stylize/test_gltf_meshopt.py
new file mode 100644
index 000000000..2d2e9d502
--- /dev/null
+++ b/workers/stylize/test_gltf_meshopt.py
@@ -0,0 +1,141 @@
+"""Tests for gltf_meshopt.py, the shared EXT_meshopt_compression decoder.
+
+Vendored byte-identical into every worker that ships gltf_meshopt.py, exactly
+like the module itself, and run as a Docker build gate in each of them:
+
+ python3 test_gltf_meshopt.py
+
+The round-trip section needs the `gltfpack` binary (present in every worker
+image, pinned in the Dockerfile). Without it the suite still runs and pins the
+readable failure a caller gets instead, so a laptop run stays green.
+"""
+
+from __future__ import annotations
+
+import io
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+import trimesh # noqa: E402
+
+import gltf_meshopt # noqa: E402
+
+PASS = 0
+
+
+def check(name: str, condition: bool, detail: str = "") -> None:
+ global PASS
+ if not condition:
+ print(f"FAIL {name} {detail}")
+ sys.exit(1)
+ PASS += 1
+ print(f"ok {name}")
+
+
+plain_glb = trimesh.Scene({"a": trimesh.creation.icosphere(subdivisions=2)}).export(file_type="glb")
+
+# ── document parsing ────────────────────────────────────────────────────────────
+
+doc = gltf_meshopt.gltf_document(plain_glb, ".glb")
+check("a glb's json chunk parses", isinstance(doc, dict) and "asset" in doc, str(type(doc)))
+check(
+ "a gltf json payload parses",
+ isinstance(gltf_meshopt.gltf_document(b'{"asset":{"version":"2.0"}}', ".gltf"), dict),
+)
+for payload, suffix, label in (
+ (b"ply\nformat ascii 1.0\n", ".ply", "a ply"),
+ (b"not json at all", ".gltf", "malformed gltf json"),
+ (b"glTF" + b"\x00" * 4, ".glb", "a truncated glb"),
+ (b"solid mesh\n", ".stl", "an stl"),
+):
+ check(f"{label} yields no gltf document", gltf_meshopt.gltf_document(payload, suffix) is None)
+
+# ── extension detection ─────────────────────────────────────────────────────────
+
+check("a plain glb needs no decode", not gltf_meshopt.uses_meshopt(doc))
+check("an empty document needs no decode", not gltf_meshopt.uses_meshopt(None))
+for declared in ("extensionsRequired", "extensionsUsed"):
+ check(
+ f"{declared} announcing {gltf_meshopt.MESHOPT_EXTENSION} needs a decode",
+ gltf_meshopt.uses_meshopt({declared: [gltf_meshopt.MESHOPT_EXTENSION]}),
+ )
+check(
+ "an unrelated extension needs no decode",
+ not gltf_meshopt.uses_meshopt({"extensionsUsed": ["KHR_materials_unlit"]}),
+)
+check(
+ "an uncompressed payload passes through decode_if_meshopt untouched",
+ gltf_meshopt.decode_if_meshopt(plain_glb, ".glb") == (plain_glb, ".glb"),
+)
+
+# ── the real decode ─────────────────────────────────────────────────────────────
+
+if shutil.which(gltf_meshopt.GLTFPACK_BIN):
+ with tempfile.TemporaryDirectory() as packdir:
+ raw = Path(packdir) / "raw.glb"
+ packed = Path(packdir) / "packed.glb"
+ raw.write_bytes(plain_glb)
+ subprocess.run(
+ [gltf_meshopt.GLTFPACK_BIN, "-i", str(raw), "-o", str(packed), "-cc"],
+ capture_output=True,
+ check=True,
+ timeout=gltf_meshopt.GLTFPACK_TIMEOUT_S,
+ )
+ packed_bytes = packed.read_bytes()
+
+ check(
+ "a gltfpack-compressed glb is detected",
+ gltf_meshopt.uses_meshopt(gltf_meshopt.gltf_document(packed_bytes, ".glb")),
+ )
+
+ # The bug this module exists for: trimesh dies on the compressed asset's
+ # fallback buffer, which is why every worker loading one failed.
+ try:
+ trimesh.load(io.BytesIO(packed_bytes), file_type="glb", force="mesh", process=False)
+ raw_load_failed = False
+ except Exception: # noqa: BLE001: the exact trimesh error is not the contract
+ raw_load_failed = True
+ check("trimesh alone cannot read a meshopt glb", raw_load_failed)
+
+ decoded, suffix = gltf_meshopt.decode_if_meshopt(packed_bytes, ".glb")
+ check("the decode returns a glb", suffix == ".glb" and decoded[:4] == b"glTF", suffix)
+ check("the decode is not a passthrough", decoded != packed_bytes)
+ check(
+ "the decoded asset no longer declares the extension",
+ not gltf_meshopt.uses_meshopt(gltf_meshopt.gltf_document(decoded, ".glb")),
+ )
+
+ mesh = trimesh.load(io.BytesIO(decoded), file_type="glb", force="mesh", process=False)
+ check(
+ "the decoded asset loads as real geometry",
+ len(mesh.faces) > 0 and len(mesh.vertices) > 0,
+ f"faces={len(mesh.faces)}",
+ )
+ source = trimesh.load(io.BytesIO(plain_glb), file_type="glb", force="mesh", process=False)
+ check(
+ "the decoded geometry matches the source face count",
+ len(mesh.faces) == len(source.faces),
+ f"{len(mesh.faces)} vs {len(source.faces)}",
+ )
+else:
+ original_bin = gltf_meshopt.GLTFPACK_BIN
+ try:
+ gltf_meshopt.GLTFPACK_BIN = "gltfpack-not-installed"
+ gltf_meshopt.transcode_meshopt(plain_glb, ".glb")
+ check("a missing gltfpack is a readable error", False, "no ValueError raised")
+ except ValueError as exc:
+ check(
+ "a missing gltfpack is a readable error",
+ gltf_meshopt.MESHOPT_EXTENSION in str(exc),
+ str(exc),
+ )
+ finally:
+ gltf_meshopt.GLTFPACK_BIN = original_bin
+
+print(f"\n{PASS} checks passed")
diff --git a/workers/stylize/test_stylize.py b/workers/stylize/test_stylize.py
index a4e0fae8c..d5bbb5bab 100644
--- a/workers/stylize/test_stylize.py
+++ b/workers/stylize/test_stylize.py
@@ -209,22 +209,28 @@ import subprocess # noqa: E402
import tempfile # noqa: E402
from pathlib import Path # noqa: E402
+import gltf_meshopt # noqa: E402
+
plain_glb = trimesh.Scene({"a": source_mesh()}).export(file_type="glb")
check(
"a plain glb is not sent through the decoder",
- not main._uses_meshopt(main._gltf_document(plain_glb, ".glb")),
+ not gltf_meshopt.uses_meshopt(gltf_meshopt.gltf_document(plain_glb, ".glb")),
+)
+check(
+ "a plain glb passes through decode_if_meshopt untouched",
+ gltf_meshopt.decode_if_meshopt(plain_glb, ".glb") == (plain_glb, ".glb"),
)
check(
"a non-gltf payload has no gltf document",
- main._gltf_document(b"ply\nformat ascii 1.0\n", ".ply") is None,
+ gltf_meshopt.gltf_document(b"ply\nformat ascii 1.0\n", ".ply") is None,
)
for declared in ("extensionsRequired", "extensionsUsed"):
check(
- f"{declared}: {main.MESHOPT_EXTENSION} is detected",
- main._uses_meshopt({declared: [main.MESHOPT_EXTENSION]}),
+ f"{declared}: {gltf_meshopt.MESHOPT_EXTENSION} is detected",
+ gltf_meshopt.uses_meshopt({declared: [gltf_meshopt.MESHOPT_EXTENSION]}),
)
-if shutil.which(main.GLTFPACK_BIN):
+if shutil.which(gltf_meshopt.GLTFPACK_BIN):
# Round-trip through the real encoder: compress, then prove the loader gets
# usable geometry back out of a file trimesh cannot read on its own.
with tempfile.TemporaryDirectory() as packdir:
@@ -232,16 +238,16 @@ if shutil.which(main.GLTFPACK_BIN):
packed = Path(packdir) / "packed.glb"
raw.write_bytes(plain_glb)
subprocess.run(
- [main.GLTFPACK_BIN, "-i", str(raw), "-o", str(packed), "-cc"],
+ [gltf_meshopt.GLTFPACK_BIN, "-i", str(raw), "-o", str(packed), "-cc"],
capture_output=True,
check=True,
- timeout=main.GLTFPACK_TIMEOUT_S,
+ timeout=gltf_meshopt.GLTFPACK_TIMEOUT_S,
)
packed_bytes = packed.read_bytes()
check(
"a meshopt glb is detected as needing a decode",
- main._uses_meshopt(main._gltf_document(packed_bytes, ".glb")),
+ gltf_meshopt.uses_meshopt(gltf_meshopt.gltf_document(packed_bytes, ".glb")),
)
try:
trimesh.load(io.BytesIO(packed_bytes), file_type="glb", force="mesh", process=False)
@@ -262,12 +268,12 @@ else:
# No gltfpack locally: pin the failure contract instead, so a caller is told
# what the input needs rather than getting a bare loader crash.
try:
- main._transcode_meshopt(plain_glb, ".glb")
+ gltf_meshopt.transcode_meshopt(plain_glb, ".glb")
check("a missing gltfpack is reported as a readable error", False, "no ValueError raised")
except ValueError as exc:
check(
"a missing gltfpack is reported as a readable error",
- main.MESHOPT_EXTENSION in str(exc),
+ gltf_meshopt.MESHOPT_EXTENSION in str(exc),
str(exc),
)
diff --git a/workers/texture/Dockerfile b/workers/texture/Dockerfile
index cb8b5bdb6..cd2b42161 100644
--- a/workers/texture/Dockerfile
+++ b/workers/texture/Dockerfile
@@ -1,4 +1,19 @@
+# gltfpack (zeux/meshoptimizer, MIT) decodes EXT_meshopt_compression, which
+# trimesh cannot read and which most three.ws avatars ship as. Pinned by release
+# tag and checksum so the image never picks up a binary we did not audit.
+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 ca-certificates curl unzip \
+ && 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.1.1-cudnn8-runtime-ubuntu22.04
+COPY --from=gltfpack /usr/local/bin/gltfpack /usr/local/bin/gltfpack
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
@@ -51,10 +66,18 @@ print('ControlNet cached')"
WORKDIR /app
COPY worker_security.py /app/worker_security.py
+COPY gltf_meshopt.py /app/gltf_meshopt.py
COPY texture_projection.py /app/texture_projection.py
COPY test_texture_projection.py /app/test_texture_projection.py
+COPY test_gltf_meshopt.py /app/test_gltf_meshopt.py
COPY stage_weights.py /app/stage_weights.py
COPY main.py /app/main.py
+# Core-path gate: the UV rasterizer and back-projection that decide where a
+# generated pixel lands, and the meshopt decode every caller mesh passes
+# through. Both are CPU-only, so a regression fails the image instead of
+# reaching a user mid-retexture.
+RUN python3 /app/test_texture_projection.py && python3 /app/test_gltf_meshopt.py
+
EXPOSE 8080
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "1"]
diff --git a/workers/texture/gltf_meshopt.py b/workers/texture/gltf_meshopt.py
new file mode 100644
index 000000000..10f7ba4ad
--- /dev/null
+++ b/workers/texture/gltf_meshopt.py
@@ -0,0 +1,107 @@
+"""EXT_meshopt_compression decoding for caller-supplied glTF input.
+
+Vendored byte-identical into every worker that loads a mesh a caller handed it,
+exactly like worker_security.py: each worker's Docker build context is its own
+directory, so `../` is unreachable. `npm run check:vendored` fails if the copies
+drift apart.
+
+Why it exists: trimesh has no decoder for EXT_meshopt_compression. A compressed
+asset stores its geometry in compressed buffer views and declares a second,
+empty "fallback" buffer that only exists once something decodes into it, so
+trimesh dies on the bufferView lookup with a bare `IndexError: list index out of
+range`. Meshopt is what gltfpack emits and what most three.ws avatars ship as,
+so this was a hard failure on our own assets (verified 2026-08-13:
+/avatars/michelle.glb failed every stylize filter in production). gltfpack is
+the same project's CLI and decodes what it encoded, so the fix is to transcode
+the asset to plain glTF before any reader touches it.
+
+The binary is pinned by release tag and checksum in each worker's Dockerfile.
+Set GLTFPACK_BIN to run the path against your own copy locally.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import subprocess
+import tempfile
+from pathlib import Path
+from typing import Optional
+
+log = logging.getLogger("gltf-meshopt")
+
+MESHOPT_EXTENSION = "EXT_meshopt_compression"
+GLTFPACK_BIN = os.environ.get("GLTFPACK_BIN", "gltfpack")
+GLTFPACK_TIMEOUT_S = int(os.environ.get("GLTFPACK_TIMEOUT_S", "120"))
+
+
+def gltf_document(data: bytes, suffix: str = ".glb") -> Optional[dict]:
+ """The glTF JSON of a .glb/.gltf payload, or None when it is neither."""
+ if suffix == ".gltf":
+ try:
+ return json.loads(data)
+ except ValueError:
+ return None
+ if suffix != ".glb" or len(data) < 20 or data[:4] != b"glTF":
+ return None
+ chunk_length = int.from_bytes(data[12:16], "little")
+ if data[16:20] != b"JSON":
+ return None
+ try:
+ return json.loads(data[20:20 + chunk_length])
+ except ValueError:
+ return None
+
+
+def uses_meshopt(document: Optional[dict]) -> bool:
+ """True when the asset needs a meshopt decode before any reader can use it.
+
+ Checked against both extension lists: an asset that only *uses* the
+ extension still stores its geometry in the compressed views, and its
+ fallback buffer stays empty until something decodes into it.
+ """
+ if not document:
+ return False
+ declared = set(document.get("extensionsRequired") or []) | set(document.get("extensionsUsed") or [])
+ return MESHOPT_EXTENSION in declared
+
+
+def transcode_meshopt(data: bytes, suffix: str = ".glb") -> bytes:
+ """Rewrite a meshopt-compressed asset as a plain GLB with gltfpack.
+
+ `-noq` keeps the source quantization instead of re-quantizing on the way
+ out, so downstream geometry is derived from what the author shipped.
+ """
+ with tempfile.TemporaryDirectory() as tmpdir:
+ src = Path(tmpdir) / f"input{suffix}"
+ dst = Path(tmpdir) / "decoded.glb"
+ src.write_bytes(data)
+ try:
+ proc = subprocess.run(
+ [GLTFPACK_BIN, "-i", str(src), "-o", str(dst), "-noq"],
+ capture_output=True,
+ timeout=GLTFPACK_TIMEOUT_S,
+ )
+ except FileNotFoundError as exc:
+ raise ValueError(
+ f"input uses {MESHOPT_EXTENSION} and the gltfpack decoder is not installed"
+ ) from exc
+ except subprocess.TimeoutExpired as exc:
+ raise ValueError(f"{MESHOPT_EXTENSION} decode timed out") from exc
+ if proc.returncode != 0 or not dst.exists():
+ detail = (proc.stderr or b"").decode("utf-8", "replace").strip().splitlines()
+ raise ValueError(f"{MESHOPT_EXTENSION} decode failed: {detail[-1][:200] if detail else 'no output'}")
+ return dst.read_bytes()
+
+
+def decode_if_meshopt(data: bytes, suffix: str = ".glb") -> tuple[bytes, str]:
+ """Return (data, suffix) ready for trimesh, decoding meshopt when present.
+
+ A payload that is not compressed glTF is handed back untouched, so this is
+ safe to call on every input path.
+ """
+ if not uses_meshopt(gltf_document(data, suffix)):
+ return data, suffix
+ log.info("input declares %s; decoding with gltfpack before load", MESHOPT_EXTENSION)
+ return transcode_meshopt(data, suffix), ".glb"
diff --git a/workers/texture/main.py b/workers/texture/main.py
index f43bf1ffb..797095370 100644
--- a/workers/texture/main.py
+++ b/workers/texture/main.py
@@ -107,6 +107,7 @@ from PIL import Image, ImageFilter
from pydantic import BaseModel, Field, field_validator
import texture_projection as tp
+from gltf_meshopt import decode_if_meshopt
from worker_security import (
fetch_remote_bytes,
require_api_key,
@@ -371,6 +372,9 @@ def _load_mesh(url: str):
import trimesh
data = fetch_remote_bytes(url, timeout=60, max_bytes=128 * 1024 * 1024)
suffix = Path(url.split("?")[0]).suffix.lower() or ".glb"
+ # A meshopt-compressed asset is transcoded first: trimesh cannot read one,
+ # and it is the format most three.ws avatars ship as.
+ data, suffix = decode_if_meshopt(data, suffix)
mesh = trimesh.load(io.BytesIO(data), file_type=suffix.lstrip("."), force="mesh", process=True)
if isinstance(mesh, trimesh.Scene):
meshes = [g for g in mesh.geometry.values() if isinstance(g, trimesh.Trimesh)]
@@ -600,6 +604,7 @@ def _load_textured_mesh(url: str):
data = fetch_remote_bytes(url, timeout=60, max_bytes=128 * 1024 * 1024)
suffix = Path(url.split("?")[0]).suffix.lower() or ".glb"
+ data, suffix = decode_if_meshopt(data, suffix)
loaded = trimesh.load(
io.BytesIO(data), file_type=suffix.lstrip("."), process=False
)
diff --git a/workers/texture/test_gltf_meshopt.py b/workers/texture/test_gltf_meshopt.py
new file mode 100644
index 000000000..2d2e9d502
--- /dev/null
+++ b/workers/texture/test_gltf_meshopt.py
@@ -0,0 +1,141 @@
+"""Tests for gltf_meshopt.py, the shared EXT_meshopt_compression decoder.
+
+Vendored byte-identical into every worker that ships gltf_meshopt.py, exactly
+like the module itself, and run as a Docker build gate in each of them:
+
+ python3 test_gltf_meshopt.py
+
+The round-trip section needs the `gltfpack` binary (present in every worker
+image, pinned in the Dockerfile). Without it the suite still runs and pins the
+readable failure a caller gets instead, so a laptop run stays green.
+"""
+
+from __future__ import annotations
+
+import io
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+import trimesh # noqa: E402
+
+import gltf_meshopt # noqa: E402
+
+PASS = 0
+
+
+def check(name: str, condition: bool, detail: str = "") -> None:
+ global PASS
+ if not condition:
+ print(f"FAIL {name} {detail}")
+ sys.exit(1)
+ PASS += 1
+ print(f"ok {name}")
+
+
+plain_glb = trimesh.Scene({"a": trimesh.creation.icosphere(subdivisions=2)}).export(file_type="glb")
+
+# ── document parsing ────────────────────────────────────────────────────────────
+
+doc = gltf_meshopt.gltf_document(plain_glb, ".glb")
+check("a glb's json chunk parses", isinstance(doc, dict) and "asset" in doc, str(type(doc)))
+check(
+ "a gltf json payload parses",
+ isinstance(gltf_meshopt.gltf_document(b'{"asset":{"version":"2.0"}}', ".gltf"), dict),
+)
+for payload, suffix, label in (
+ (b"ply\nformat ascii 1.0\n", ".ply", "a ply"),
+ (b"not json at all", ".gltf", "malformed gltf json"),
+ (b"glTF" + b"\x00" * 4, ".glb", "a truncated glb"),
+ (b"solid mesh\n", ".stl", "an stl"),
+):
+ check(f"{label} yields no gltf document", gltf_meshopt.gltf_document(payload, suffix) is None)
+
+# ── extension detection ─────────────────────────────────────────────────────────
+
+check("a plain glb needs no decode", not gltf_meshopt.uses_meshopt(doc))
+check("an empty document needs no decode", not gltf_meshopt.uses_meshopt(None))
+for declared in ("extensionsRequired", "extensionsUsed"):
+ check(
+ f"{declared} announcing {gltf_meshopt.MESHOPT_EXTENSION} needs a decode",
+ gltf_meshopt.uses_meshopt({declared: [gltf_meshopt.MESHOPT_EXTENSION]}),
+ )
+check(
+ "an unrelated extension needs no decode",
+ not gltf_meshopt.uses_meshopt({"extensionsUsed": ["KHR_materials_unlit"]}),
+)
+check(
+ "an uncompressed payload passes through decode_if_meshopt untouched",
+ gltf_meshopt.decode_if_meshopt(plain_glb, ".glb") == (plain_glb, ".glb"),
+)
+
+# ── the real decode ─────────────────────────────────────────────────────────────
+
+if shutil.which(gltf_meshopt.GLTFPACK_BIN):
+ with tempfile.TemporaryDirectory() as packdir:
+ raw = Path(packdir) / "raw.glb"
+ packed = Path(packdir) / "packed.glb"
+ raw.write_bytes(plain_glb)
+ subprocess.run(
+ [gltf_meshopt.GLTFPACK_BIN, "-i", str(raw), "-o", str(packed), "-cc"],
+ capture_output=True,
+ check=True,
+ timeout=gltf_meshopt.GLTFPACK_TIMEOUT_S,
+ )
+ packed_bytes = packed.read_bytes()
+
+ check(
+ "a gltfpack-compressed glb is detected",
+ gltf_meshopt.uses_meshopt(gltf_meshopt.gltf_document(packed_bytes, ".glb")),
+ )
+
+ # The bug this module exists for: trimesh dies on the compressed asset's
+ # fallback buffer, which is why every worker loading one failed.
+ try:
+ trimesh.load(io.BytesIO(packed_bytes), file_type="glb", force="mesh", process=False)
+ raw_load_failed = False
+ except Exception: # noqa: BLE001: the exact trimesh error is not the contract
+ raw_load_failed = True
+ check("trimesh alone cannot read a meshopt glb", raw_load_failed)
+
+ decoded, suffix = gltf_meshopt.decode_if_meshopt(packed_bytes, ".glb")
+ check("the decode returns a glb", suffix == ".glb" and decoded[:4] == b"glTF", suffix)
+ check("the decode is not a passthrough", decoded != packed_bytes)
+ check(
+ "the decoded asset no longer declares the extension",
+ not gltf_meshopt.uses_meshopt(gltf_meshopt.gltf_document(decoded, ".glb")),
+ )
+
+ mesh = trimesh.load(io.BytesIO(decoded), file_type="glb", force="mesh", process=False)
+ check(
+ "the decoded asset loads as real geometry",
+ len(mesh.faces) > 0 and len(mesh.vertices) > 0,
+ f"faces={len(mesh.faces)}",
+ )
+ source = trimesh.load(io.BytesIO(plain_glb), file_type="glb", force="mesh", process=False)
+ check(
+ "the decoded geometry matches the source face count",
+ len(mesh.faces) == len(source.faces),
+ f"{len(mesh.faces)} vs {len(source.faces)}",
+ )
+else:
+ original_bin = gltf_meshopt.GLTFPACK_BIN
+ try:
+ gltf_meshopt.GLTFPACK_BIN = "gltfpack-not-installed"
+ gltf_meshopt.transcode_meshopt(plain_glb, ".glb")
+ check("a missing gltfpack is a readable error", False, "no ValueError raised")
+ except ValueError as exc:
+ check(
+ "a missing gltfpack is a readable error",
+ gltf_meshopt.MESHOPT_EXTENSION in str(exc),
+ str(exc),
+ )
+ finally:
+ gltf_meshopt.GLTFPACK_BIN = original_bin
+
+print(f"\n{PASS} checks passed")