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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(economy): the sweep can no longer starve x402 settlement
nirholas4481374b3d33
diff --git a/api/_lib/economy-master.js b/api/_lib/economy-master.jsindex 168b4746b..9e7a02075 100644--- a/api/_lib/economy-master.js+++ b/api/_lib/economy-master.js@@ -19,7 +19,9 @@//// Guards — enforced on every sweep; the first two are on-chain reads, so they// hold even with no database:-// • RESERVE FLOOR — never spend the master below ECONOMY_MASTER_RESERVE_SOL.+// • RESERVE FLOOR — never spend the master below ECONOMY_MASTER_RESERVE_SOL,+// raised to the x402 settle floor + headroom whenever the+// master doubles as the sponsor wallet (sweepFloorSol).// • PER-ENGINE CAP — bring an engine up to its refillTo only, and never move// more than ECONOMY_MASTER_PER_TOPUP_MAX_SOL to one engine// in a single sweep.@@ -52,6 +54,33 @@ function num(envName, dflt) {// not sit fully locked behind a 1 SOL floor sized for a much larger treasury./** Never spend the master below this — its own working reserve + rent + fees. */export const RESERVE_SOL = num('ECONOMY_MASTER_RESERVE_SOL', 0.02);++// The master is ALSO the x402 sponsor fee wallet (X402_FEE_PAYER_SOLANA points+// at it in production), and the self-facilitator fail-closes every settle the+// moment that wallet dips under its own floor. Spending the master down to+// RESERVE_SOL therefore parked it AT or BELOW the settle floor on every sweep:+// the 2026-07-27 ledger shows a sweep taking the master 0.05408 to 0.02000 and+// settlement dying seconds later, which is why funding it only ever bought a+// few hours. The sweep now keeps the sponsor floor plus working headroom on top+// of its own reserve, so topping up engines can never starve settlement.+// Headroom default is deliberately generous relative to the floor: a sweep is+// worth delaying, a settlement outage is not.+const SPONSOR_FLOOR_SOL = num('X402_SPONSOR_SOL_FLOOR_LAMPORTS', 20_000_000) / 1e9;+const SPONSOR_HEADROOM_SOL = num('ECONOMY_MASTER_SPONSOR_HEADROOM_SOL', 0.03);++/**+ * The balance the sweep must leave untouched: the master's own reserve, and,+ * when the master doubles as the x402 sponsor, the settle floor plus headroom.+ * Exported so the cron can report it and tests can pin the relationship.+ */+export function sweepFloorSol() {+ const masterIsSponsor =+ !!process.env.X402_FEE_PAYER_SOLANA &&+ !!ECONOMY_MASTER_ADDRESS &&+ process.env.X402_FEE_PAYER_SOLANA === ECONOMY_MASTER_ADDRESS;+ if (!masterIsSponsor) return RESERVE_SOL;+ return Math.max(RESERVE_SOL, round(SPONSOR_FLOOR_SOL + SPONSOR_HEADROOM_SOL));+}/** Most SOL the master will move to any single engine in one sweep. */export const PER_TOPUP_MAX_SOL = num('ECONOMY_MASTER_PER_TOPUP_MAX_SOL', 0.5);/** Most SOL the master will move across all engines in one sweep. */@@ -95,7 +124,7 @@ export async function loadEconomyMaster() {* @returns {{ plan: Array<{name:string,pubkey:string,sol:number}>, skipped: Array<{name:string,reason:string}>, totalSol:number, spendableSol:number }}*/export function planTopUps(masterSol, targets) {- const spendableSol = Math.max(0, round(masterSol - RESERVE_SOL));+ const spendableSol = Math.max(0, round(masterSol - sweepFloorSol()));const runCap = Math.min(RUN_CAP_SOL, spendableSol);// Neediest first, so a tight run cap protects the most-drained engines.const ordered = [...targets].sort(@@ -210,6 +239,7 @@ export async function sweepTopUps({ connection, targets, network = 'mainnet', drmaster: master.publicKey.toBase58(),masterSol: round(masterSol),reserveSol: RESERVE_SOL,+ sweepFloorSol: sweepFloorSol(),spendableSol,plan,funded: [],@@ -243,6 +273,7 @@ export async function sweepTopUps({ connection, targets, network = 'mainnet', drmaster: master.publicKey.toBase58(),masterSol: round(masterSol),reserveSol: RESERVE_SOL,+ sweepFloorSol: sweepFloorSol(),spendableSol,funded,failed,diff --git a/tests/economy-master-sponsor-floor.test.js b/tests/economy-master-sponsor-floor.test.jsnew file mode 100644index 000000000..08863925e--- /dev/null+++ b/tests/economy-master-sponsor-floor.test.js@@ -0,0 +1,99 @@+// The sweep must never starve x402 settlement.+//+// In production the economy master IS the x402 sponsor fee wallet+// (X402_FEE_PAYER_SOLANA points at ECONOMY_MASTER_ADDRESS). The self-facilitator+// fail-closes every settle the moment that wallet dips below its own floor+// (X402_SPONSOR_SOL_FLOOR_LAMPORTS, 0.02 SOL), so a sweep that spent the master+// down to RESERVE_SOL parked it AT the settle floor and killed payments seconds+// later. The 2026-07-27 ledger caught it exactly: a transfer to+// pump-x402-launcher took the master 0.05408 -> 0.02000, and every settle after+// it returned fee_wallet_below_floor. Funding the wallet only ever bought hours.+//+// Rule under test: when the master doubles as the sponsor, the sweep floor is+// the settle floor plus working headroom, not the master's bare reserve. When+// it does not (a separate sponsor wallet, or no x402 config), nothing changes.++import { describe, it, expect, beforeEach, afterEach } from 'vitest';++const MASTER = 'WwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW';+const OTHER = 'X4o2UuVNMxnrgkzVy97kPF5gmS6CLRCVJGB48VastML';++const target = (name, currentSol, refillToSol) => ({ name, pubkey: `pk-${name}`, currentSol, refillToSol });++let saved;+beforeEach(() => {+ saved = {+ fee: process.env.X402_FEE_PAYER_SOLANA,+ floor: process.env.X402_SPONSOR_SOL_FLOOR_LAMPORTS,+ headroom: process.env.ECONOMY_MASTER_SPONSOR_HEADROOM_SOL,+ };+});+afterEach(() => {+ for (const [k, v] of [+ ['X402_FEE_PAYER_SOLANA', saved.fee],+ ['X402_SPONSOR_SOL_FLOOR_LAMPORTS', saved.floor],+ ['ECONOMY_MASTER_SPONSOR_HEADROOM_SOL', saved.headroom],+ ]) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+});++describe('sweepFloorSol', () => {+ it('reserves the settle floor plus headroom when the master is the sponsor', async () => {+ const { sweepFloorSol, RESERVE_SOL } = await import('../api/_lib/economy-master.js');+ process.env.X402_FEE_PAYER_SOLANA = MASTER;+ process.env.X402_SPONSOR_SOL_FLOOR_LAMPORTS = '20000000'; // 0.02 SOL+ process.env.ECONOMY_MASTER_SPONSOR_HEADROOM_SOL = '0.03';++ expect(sweepFloorSol()).toBeCloseTo(0.05, 6);+ // Strictly above the settle floor: that gap is the whole point.+ expect(sweepFloorSol()).toBeGreaterThan(0.02);+ expect(sweepFloorSol()).toBeGreaterThanOrEqual(RESERVE_SOL);+ });++ it('falls back to the plain reserve when a separate wallet sponsors', async () => {+ const { sweepFloorSol, RESERVE_SOL } = await import('../api/_lib/economy-master.js');+ process.env.X402_FEE_PAYER_SOLANA = OTHER;++ expect(sweepFloorSol()).toBe(RESERVE_SOL);+ });++ it('falls back to the plain reserve when x402 is not configured', async () => {+ const { sweepFloorSol, RESERVE_SOL } = await import('../api/_lib/economy-master.js');+ delete process.env.X402_FEE_PAYER_SOLANA;++ expect(sweepFloorSol()).toBe(RESERVE_SOL);+ });+});++describe('planTopUps respects the sponsor floor', () => {+ it('does not plan the transfer that killed settlement on 2026-07-27', async () => {+ const { planTopUps } = await import('../api/_lib/economy-master.js');+ process.env.X402_FEE_PAYER_SOLANA = MASTER;+ process.env.X402_SPONSOR_SOL_FLOOR_LAMPORTS = '20000000';+ process.env.ECONOMY_MASTER_SPONSOR_HEADROOM_SOL = '0.03';++ // The exact production state: master at 0.05408, one hungry engine.+ const { plan, spendableSol } = planTopUps(0.05408, [target('pump-x402-launcher', 0.001, 0.15)]);++ // Spendable is now 0.00408 (below the dust threshold), not 0.03408.+ expect(spendableSol).toBeCloseTo(0.00408, 5);+ expect(plan).toEqual([]);+ });++ it('still funds engines from the surplus above the sponsor floor', async () => {+ const { planTopUps } = await import('../api/_lib/economy-master.js');+ process.env.X402_FEE_PAYER_SOLANA = MASTER;+ process.env.X402_SPONSOR_SOL_FLOOR_LAMPORTS = '20000000';+ process.env.ECONOMY_MASTER_SPONSOR_HEADROOM_SOL = '0.03';++ const { plan, totalSol, spendableSol } = planTopUps(0.5, [target('pump-cron-relayer', 0.001, 0.15)]);++ expect(spendableSol).toBeCloseTo(0.45, 6);+ expect(plan).toHaveLength(1);+ expect(totalSol).toBeGreaterThan(0);+ // And what it leaves behind still clears the settle floor.+ expect(0.5 - totalSol).toBeGreaterThan(0.02);+ });+});diff --git a/workers/garment-forge/Dockerfile b/workers/garment-forge/Dockerfileindex 323c394b9..e0f55253b 100644--- a/workers/garment-forge/Dockerfile+++ b/workers/garment-forge/Dockerfile@@ -15,8 +15,10 @@ COPY worker_security.py /app/worker_security.pyCOPY canonical_bones.py /app/canonical_bones.pyCOPY garment_glb.py /app/garment_glb.pyCOPY pipeline.py /app/pipeline.py+COPY job_queue.py /app/job_queue.pyCOPY main.py /app/main.pyCOPY test_garment_glb.py /app/test_garment_glb.py+COPY test_job_queue.py /app/test_job_queue.py# The canonical reference body (public/avatars/parametric-base.glb), staged# into assets/ by cloudbuild.yaml so the repo does not carry a second copy.@@ -26,5 +28,10 @@ COPY assets/ /app/assets/# validate) must pass its unit suite or the image does not ship.RUN python /app/test_garment_glb.py+# Build-time guard: the durable job-queue policy (who may claim a job, and what+# happens to one whose instance was reclaimed) must pass its unit suite. A+# regression here silently drops submitted work.+RUN python /app/test_job_queue.py+EXPOSE 8080CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "1"]diff --git a/workers/garment-forge/job_queue.py b/workers/garment-forge/job_queue.pynew file mode 100644index 000000000..0bc8523d0--- /dev/null+++ b/workers/garment-forge/job_queue.py@@ -0,0 +1,85 @@+"""Durable job-queue policy: who may run a job, and what to do with one whose+instance vanished. Pure functions over the job record, no GCS and no FastAPI,+so the rules are unit-testable without any cloud dependency (test_job_queue.py,+also a Docker build gate).++Why this exists+---------------+garment-forge is a scale-to-zero Cloud Run service with MAX_CONCURRENT jobs per+instance. Submitting a batch used to hand every job to that instance's FastAPI+background queue: the jobs past the concurrency limit sat on a semaphore in+memory, and when Cloud Run reclaimed the instance (idle scale-down or a+revision rollout) they disappeared, leaving their durable records stuck at+"queued" until a watchdog buried them. That is exactly what happened to 12 of+22 pieces in the 2026-07-26 catalog batch.++The rule that fixes it: a job's RECORD is the queue, and work is CLAIMED at+execution time by a live instance holding a concurrency slot. Anything not+claimed, or claimed by an instance that then died, is recoverable by any other+instance (POST /sweep, or the drain that runs when a slot frees).+"""++from __future__ import annotations++from datetime import datetime, timezone++# Statuses that mean "this job still owes work".+PENDING_STATUSES = ("queued", "running")+++def _age_seconds(job: dict, now: datetime) -> float | None:+ """Seconds since the record last advanced, or None if it carries no+ parseable timestamp (which we treat as 'infinitely stale': a record we+ cannot date must not be able to pin a job forever)."""+ try:+ updated = datetime.fromisoformat(job.get("updated_at", ""))+ except ValueError:+ return None+ if updated.tzinfo is None:+ updated = updated.replace(tzinfo=timezone.utc)+ return (now - updated).total_seconds()+++def claimable(job: dict, now: datetime, stale_s: float, max_attempts: int) -> bool:+ """True when a live instance may take ownership of this job.++ Claimable: a queued job (nobody owns it), or a running job whose owner has+ not advanced a stage within `stale_s` (its instance is gone). Never+ claimable: terminal jobs, and jobs that already burned `max_attempts`.+ """+ if job.get("status") not in PENDING_STATUSES:+ return False+ if int(job.get("attempts", 0)) >= max_attempts:+ return False+ if job.get("status") == "queued":+ return True+ age = _age_seconds(job, now)+ return age is None or age > stale_s+++def claim_fields(job: dict, owner: str, now: datetime) -> dict:+ """The mutation that takes ownership: mark running, count the attempt, and+ stamp the owner so logs attribute a job to a specific instance."""+ return {+ "status": "running",+ "stage": "claimed",+ "attempts": int(job.get("attempts", 0)) + 1,+ "owner": owner,+ "updated_at": now.isoformat(),+ }+++def stale_action(job: dict, now: datetime, stale_s: float,+ max_attempts: int) -> str | None:+ """What the read-path watchdog should do with this record.++ Returns "requeue" (lost its instance but has attempts left, so hand it+ back to the queue), "fail" (out of attempts: terminal, stop polling), or+ None (healthy or already terminal, leave it alone).+ """+ if job.get("status") not in PENDING_STATUSES:+ return None+ age = _age_seconds(job, now)+ if age is not None and age <= stale_s:+ return None+ return "requeue" if int(job.get("attempts", 0)) < max_attempts else "fail"diff --git a/workers/garment-forge/main.py b/workers/garment-forge/main.pyindex 3d5df2a0f..590ea0183 100644--- a/workers/garment-forge/main.py+++ b/workers/garment-forge/main.py@@ -59,6 +59,7 @@ from google.cloud import storagefrom pydantic import BaseModel, Fieldimport garment_glb+import job_queueimport pipelinefrom canonical_bones import GARMENT_SLOTSfrom worker_security import require_api_key, safe_error@@ -118,20 +119,7 @@ def _job_blob(job_id: str):# an instance that then died) stays recoverable, and POST /sweep re-drives it.def _claimable(job: dict, now: datetime) -> bool:- """A queued job nobody owns, or a running job whose owner went silent past- the stale window (its instance is gone)."""- status = job.get("status")- if status not in ("queued", "running"):- return False- if int(job.get("attempts", 0)) >= MAX_ATTEMPTS:- return False- if status == "queued":- return True- try:- updated = datetime.fromisoformat(job.get("updated_at", ""))- except ValueError:- return True- return (now - updated).total_seconds() > JOB_STALE_S+ return job_queue.claimable(job, now, JOB_STALE_S, MAX_ATTEMPTS)def _try_claim(job_id: str) -> Optional[dict]:@@ -145,15 +133,10 @@ def _try_claim(job_id: str) -> Optional[dict]:job = json.loads(blob.download_as_bytes())except NotFound:return None- if not _claimable(job, datetime.now(timezone.utc)):+ now = datetime.now(timezone.utc)+ if not _claimable(job, now):return None- job.update(- status="running",- stage="claimed",- attempts=int(job.get("attempts", 0)) + 1,- owner=INSTANCE_ID,- updated_at=datetime.now(timezone.utc).isoformat(),- )+ job.update(job_queue.claim_fields(job, INSTANCE_ID, now))try:blob.upload_from_string(json.dumps(job), content_type="application/json",if_generation_match=generation)@@ -398,26 +381,21 @@ async def _fail_if_stale(job: dict) -> dict:the job goes back to `queued` for the next sweep to re-drive; only a jobthat has burned MAX_ATTEMPTS is declared terminally failed, so a pollernever watches a zombie and a recoverable job is never buried."""- if job.get("status") not in ("queued", "running"):- return job- try:- updated = datetime.fromisoformat(job.get("updated_at", ""))- except ValueError:- return job- age = (datetime.now(timezone.utc) - updated).total_seconds()- if age <= JOB_STALE_S:+ action = job_queue.stale_action(job, datetime.now(timezone.utc),+ JOB_STALE_S, MAX_ATTEMPTS)+ if action is None:return jobattempts = int(job.get("attempts", 0))- if attempts < MAX_ATTEMPTS:- log.warning("[%s] stale for %.0fs at stage %s (attempt %d/%d); requeueing",- job.get("job_id"), age, job.get("stage"), attempts, MAX_ATTEMPTS)+ if action == "requeue":+ log.warning("[%s] lost its instance at stage %s (attempt %d/%d); requeueing",+ job.get("job_id"), job.get("stage"), attempts, MAX_ATTEMPTS)return await _update_job(job["job_id"], status="queued", stage="queued")- log.error("[%s] stale for %.0fs at stage %s after %d attempts; marking failed",- job.get("job_id"), age, job.get("stage"), attempts)+ log.error("[%s] stale at stage %s after %d attempts; marking failed",+ job.get("job_id"), job.get("stage"), attempts)return await _update_job(job["job_id"], status="failed",- error=f"job stalled at stage '{job.get('stage')}' "- f"(no progress for {int(age)}s) after {attempts} attempts. "+ error=f"job stalled at stage '{job.get('stage')}' after {attempts} "+ "attempts (each owning instance was reclaimed). ""Retry the generation.",)diff --git a/workers/garment-forge/test_job_queue.py b/workers/garment-forge/test_job_queue.pynew file mode 100644index 000000000..439f3df02--- /dev/null+++ b/workers/garment-forge/test_job_queue.py@@ -0,0 +1,125 @@+"""Unit tests for the durable job-queue policy (job_queue.py): pure dict rules,+no GCS, no FastAPI. Runs locally and as a Docker build gate:++ python3 workers/garment-forge/test_job_queue.py++These pin the behaviour that fixes the 2026-07-26 batch loss, where 12 of 22+jobs died in a reclaimed instance's in-memory queue while their durable records+sat at "queued" until a watchdog buried them.+"""++from __future__ import annotations++import sys+from datetime import datetime, timedelta, timezone++from job_queue import claim_fields, claimable, stale_action++STALE_S = 2700.0+MAX_ATTEMPTS = 3+NOW = datetime(2026, 7, 27, 12, 0, 0, tzinfo=timezone.utc)++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}")+++def job(**fields) -> dict:+ base = {+ "job_id": "j1",+ "status": "queued",+ "stage": "queued",+ "attempts": 0,+ "updated_at": NOW.isoformat(),+ }+ base.update(fields)+ return base+++def aged(seconds: float, **fields) -> dict:+ return job(updated_at=(NOW - timedelta(seconds=seconds)).isoformat(), **fields)+++# ── claimable ───────────────────────────────────────────────────────────────++# The core of the fix: a job left queued by a reclaimed instance is claimable+# by ANY live instance, immediately, without waiting out the stale window.+check("fresh queued job is claimable",+ claimable(job(), NOW, STALE_S, MAX_ATTEMPTS))+check("old queued job is claimable",+ claimable(aged(9999), NOW, STALE_S, MAX_ATTEMPTS))++# A job actively advancing on another instance must never be stolen: that+# would run the same pipeline twice and publish duplicate catalog entries.+check("running job inside the stale window is NOT claimable",+ not claimable(job(status="running", stage="mesh"), NOW, STALE_S, MAX_ATTEMPTS))+check("running job just under the window is NOT claimable",+ not claimable(aged(STALE_S - 1, status="running", stage="mesh"),+ NOW, STALE_S, MAX_ATTEMPTS))+check("running job past the window IS claimable (its instance is gone)",+ claimable(aged(STALE_S + 1, status="running", stage="mesh"),+ NOW, STALE_S, MAX_ATTEMPTS))++# Terminal jobs are never re-run: a published garment must not be republished.+for terminal in ("done", "failed"):+ check(f"{terminal} job is not claimable",+ not claimable(job(status=terminal), NOW, STALE_S, MAX_ATTEMPTS))++# Runaway protection: a job that keeps killing its instance stops consuming+# capacity instead of looping forever.+check("job at max attempts is not claimable",+ not claimable(job(attempts=MAX_ATTEMPTS), NOW, STALE_S, MAX_ATTEMPTS))+check("job one below max attempts is still claimable",+ claimable(job(attempts=MAX_ATTEMPTS - 1), NOW, STALE_S, MAX_ATTEMPTS))++# An undateable record must not pin a job forever.+check("running job with unparseable timestamp is claimable",+ claimable(job(status="running", updated_at="not-a-date"),+ NOW, STALE_S, MAX_ATTEMPTS))++# Records written before this feature shipped carry no `attempts` key.+check("legacy record without attempts is claimable",+ claimable({"job_id": "old", "status": "queued", "updated_at": NOW.isoformat()},+ NOW, STALE_S, MAX_ATTEMPTS))++# ── claim_fields ────────────────────────────────────────────────────────────++fields = claim_fields(job(attempts=1), "rev-7:abc", NOW)+check("claim marks running", fields["status"] == "running", str(fields))+check("claim counts the attempt", fields["attempts"] == 2, str(fields))+check("claim records the owner", fields["owner"] == "rev-7:abc", str(fields))+check("claim stamps the time", fields["updated_at"] == NOW.isoformat(), str(fields))+check("claim of a legacy record starts attempts at 1",+ claim_fields({"job_id": "old"}, "o", NOW)["attempts"] == 1)++# ── stale_action ────────────────────────────────────────────────────────────++check("healthy running job needs no action",+ stale_action(job(status="running"), NOW, STALE_S, MAX_ATTEMPTS) is None)+check("done job needs no action",+ stale_action(job(status="done"), NOW, STALE_S, MAX_ATTEMPTS) is None)+# The behaviour change: losing an instance requeues rather than buries.+check("stale job with attempts left is requeued, not failed",+ stale_action(aged(STALE_S + 1, status="running", attempts=1),+ NOW, STALE_S, MAX_ATTEMPTS) == "requeue")+check("stale job out of attempts fails terminally",+ stale_action(aged(STALE_S + 1, status="running", attempts=MAX_ATTEMPTS),+ NOW, STALE_S, MAX_ATTEMPTS) == "fail")+check("a queued job that never got picked up is requeued (harmless no-op)",+ stale_action(aged(STALE_S + 1), NOW, STALE_S, MAX_ATTEMPTS) == "requeue")++# Naive timestamps (no tzinfo) must not raise; they are read as UTC.+check("naive timestamp is treated as UTC, not a crash",+ stale_action({"job_id": "n", "status": "running", "attempts": 0,+ "updated_at": (NOW - timedelta(seconds=STALE_S + 1))+ .replace(tzinfo=None).isoformat()},+ NOW, STALE_S, MAX_ATTEMPTS) == "requeue")++print(f"\nall {PASS} checks passed")