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(segment): time out abandoned jobs and retry uploads that lose the connection

nirholas1288bb84c8e9
diff --git a/workers/segment/main.py b/workers/segment/main.py
index ce27fa7f0..904f01a9b 100644
--- a/workers/segment/main.py
+++ b/workers/segment/main.py
@@ -52,6 +52,7 @@ from typing import Optional
from fastapi import FastAPI, HTTPException, Header, BackgroundTasks
from google.cloud import storage
+from google.cloud.storage.retry import DEFAULT_RETRY
from pydantic import BaseModel, Field, field_validator
from worker_security import (
@@ -70,6 +71,14 @@ log = logging.getLogger("segment")
API_KEY = os.environ["API_KEY"]
GCS_BUCKET = os.environ["GCS_BUCKET"]
MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "2"))
+# Wall-clock ceiling for one segmentation. Before the 2026-08-11 merge-pass
+# rewrite, pathological meshes ran for 2.9 to 4 HOURS while the caller had long
+# since given up, pinning a slot and pushing the instance into OOM. A job past
+# this budget is abandoned by definition, so we fail it and free the slot.
+JOB_TIMEOUT_S = float(os.environ.get("JOB_TIMEOUT_S", "600"))
+# How long a finished task stays in this instance's memory. The durable copy in
+# GCS outlives it, so eviction only costs a read on a late poll.
+TASK_TTL_S = float(os.environ.get("TASK_TTL_S", "3600"))
_bucket: Optional[storage.Bucket] = None
_sem: Optional[asyncio.Semaphore] = None
@@ -78,6 +87,14 @@ _tasks: dict[str, dict] = {}
SUPPORTED_INPUT_FORMATS = {".glb", ".gltf", ".obj", ".stl", ".ply", ".fbx", ".off", ".dae"}
VALID_METHODS = {"auto", "connected", "crease"}
MAX_MESH_BYTES = 128 * 1024 * 1024
+TERMINAL_STATUSES = ("done", "failed")
+
+# Uploads are retried on transient transport faults. The default policy treats
+# an upload as non-idempotent and does NOT retry it, so a single
+# `SSLEOFError: UNEXPECTED_EOF_WHILE_READING` from storage.googleapis.com used
+# to discard a completed segmentation outright (observed 2026-08-05, -08, -10).
+# Every blob here is named after a fresh uuid, so a replayed write is safe.
+UPLOAD_RETRY = DEFAULT_RETRY.with_timeout(120.0)
@asynccontextmanager
@@ -100,11 +117,64 @@ def _require_api_key(authorization: str) -> None:
raise HTTPException(status_code=401, detail=str(exc)) from exc
+def _task_blob_name(task_id: str) -> str:
+ return f"segment/{task_id}.task.json"
+
+
+def _persist_task(task: dict) -> None:
+ """Mirror a task record to GCS so any instance can answer for it.
+
+ Task state used to live only in the submitting instance's memory, so a poll
+ routed to a sibling instance (min 1 / max 3) or arriving after a restart got
+ a bare 404 and the caller reported a phantom failure. Persistence is
+ best-effort: losing the mirror must never fail an otherwise good job, it
+ only costs the durable answer.
+ """
+ if _bucket is None:
+ return
+ try:
+ blob = _bucket.blob(_task_blob_name(task["task_id"]))
+ blob.upload_from_string(
+ json.dumps(task), content_type="application/json", retry=UPLOAD_RETRY
+ )
+ except Exception:
+ log.warning(
+ "[%s] could not persist task record", task.get("task_id"), exc_info=True
+ )
+
+
+def _load_task(task_id: str) -> Optional[dict]:
+ """Read a task record this instance never saw (or has since evicted)."""
+ if _bucket is None:
+ return None
+ try:
+ blob = _bucket.blob(_task_blob_name(task_id))
+ raw = blob.download_as_bytes(retry=DEFAULT_RETRY)
+ except Exception:
+ return None
+ try:
+ record = json.loads(raw)
+ except ValueError:
+ return None
+ return record if isinstance(record, dict) else None
+
+
+def _evict_stale_tasks(now: float) -> None:
+ """Drop finished tasks past their TTL; the GCS copy still answers polls."""
+ for task_id, task in list(_tasks.items()):
+ if task.get("status") not in TERMINAL_STATUSES:
+ continue
+ if now - float(task.get("finished_at", now)) > TASK_TTL_S:
+ _tasks.pop(task_id, None)
+
+
def _fetch_mesh(url: str) -> tuple[bytes, str]:
+ import segment_core as seg
+
try:
data = fetch_remote_bytes(url, timeout=60, max_bytes=MAX_MESH_BYTES)
except UnsafeUrlError as exc:
- raise ValueError(f"refused to fetch mesh: {exc}") from exc
+ raise seg.SegmentInputError(f"refused to fetch mesh: {exc}") from exc
suffix = Path(url.split("?")[0]).suffix.lower()
if suffix not in SUPPORTED_INPUT_FORMATS:
suffix = ".glb"
@@ -122,14 +192,19 @@ def _run_segmentation(
"""Fetch, segment, and return (glb_bytes, manifest). Runs in a thread."""
import segment_core as seg
+ started = time.monotonic()
data, suffix = _fetch_mesh(mesh_url)
mesh = seg.load_concatenated(data, suffix)
+ # The fetch is on the same clock: a slow download must not buy the
+ # segmenter extra time beyond the job's overall budget.
+ remaining = JOB_TIMEOUT_S - (time.monotonic() - started)
result = seg.segment(
mesh,
method=method,
max_parts=max_parts,
min_part_faces=min_part_faces,
crease_angle_deg=crease_angle,
+ time_budget_s=max(remaining, 1.0),
)
parts = result.parts
@@ -145,7 +220,9 @@ def _run_segmentation(
)
if match is None:
available = ", ".join(f"part_{p.index:02d} ({p.name})" for p in parts)
- raise ValueError(f"part '{only_part}' not found. Available: {available}")
+ raise seg.SegmentInputError(
+ f"part '{only_part}' not found. Available: {available}"
+ )
parts = [match]
scene = seg.build_scene(parts)
@@ -176,6 +253,7 @@ async def _process(
_tasks[task_id]["status"] = "running"
loop = asyncio.get_event_loop()
t0 = time.time()
+ await loop.run_in_executor(None, _persist_task, dict(_tasks[task_id]))
try:
glb_bytes, manifest = await loop.run_in_executor(
None,
@@ -196,13 +274,15 @@ async def _process(
await loop.run_in_executor(
None,
lambda: glb_blob.upload_from_string(
- glb_bytes, content_type="model/gltf-binary"
+ glb_bytes, content_type="model/gltf-binary", retry=UPLOAD_RETRY
),
)
await loop.run_in_executor(
None,
lambda: manifest_blob.upload_from_string(
- json.dumps(manifest), content_type="application/json"
+ json.dumps(manifest),
+ content_type="application/json",
+ retry=UPLOAD_RETRY,
),
)
@@ -221,19 +301,34 @@ async def _process(
"warnings": manifest.get("warnings", []),
"bytes": len(glb_bytes),
"elapsed_ms": int(elapsed * 1000),
+ "finished_at": time.time(),
})
log.info(
- "[%s] done in %.2fs — %d parts, %d bytes → %s",
+ "[%s] done in %.2fs, %d parts, %d bytes -> %s",
task_id, elapsed, manifest["part_count"], len(glb_bytes), result_url,
)
except Exception as exc:
+ import segment_core as seg
+
+ if isinstance(exc, (seg.SegmentInputError, seg.SegmentTimeout)):
+ # Ours, and written for the caller: a bad part id or a blown
+ # time budget is fixable from the client side, so say what
+ # happened instead of burying it behind a correlation id.
+ message = str(exc)
+ log.warning("[%s] segment rejected: %s", task_id, message)
+ else:
+ message = safe_error(exc, context=f"[{task_id}] segment")
_tasks[task_id].update({
"status": "failed",
- "error": safe_error(exc, context=f"[{task_id}] segment"),
+ "error": message,
"elapsed_ms": int((time.time() - t0) * 1000),
+ "finished_at": time.time(),
})
+ await loop.run_in_executor(None, _persist_task, dict(_tasks[task_id]))
+ _evict_stale_tasks(time.time())
+
class SegmentRequest(BaseModel):
mesh: str = Field(..., description="https URL to input mesh (GLB/OBJ/FBX/STL/PLY)")
@@ -265,6 +360,11 @@ async def segment_mesh(
"status": "queued",
"method": body.method,
}
+ # Persist before returning the id: a caller can poll immediately, and that
+ # poll may land on a sibling instance that has never heard of this job.
+ await asyncio.get_event_loop().run_in_executor(
+ None, _persist_task, dict(_tasks[task_id])
+ )
background_tasks.add_task(
_process,
task_id,
@@ -282,6 +382,12 @@ async def segment_mesh(
async def get_task(task_id: str, authorization: str = Header(...)) -> dict:
_require_api_key(authorization)
task = _tasks.get(task_id)
+ if task is None:
+ # Not ours: either a sibling instance is running it, or this instance
+ # restarted. The durable record answers either way.
+ task = await asyncio.get_event_loop().run_in_executor(
+ None, _load_task, task_id
+ )
if task is None:
raise HTTPException(status_code=404, detail="task not found")
return task