fix: run local redis-server sidecar instead of fragile Upstash provisioning
Browse filesDiagnosed via Space run logs: Celery worker crash-looped every ~9s
("broker_connection_retry_on_startup=False ... Shutting down") because the
Upstash start-redis provisioning did not succeed from the Space network, so
the broker fell back to localhost with nothing listening and the container
never became READY.
- Dockerfile(s): install redis-server; entrypoint starts a volatile local
sidecar (port 6379, 120mb LRU) and wires cache/broker/result to
redis://127.0.0.1:6379/{0,1,2} after a PING gate
- Space secrets still win (REDIS_URL/CELERY_BROKER_URL/CELERY_RESULT_BACKEND)
- Upstash free-tier provisioning kept only as last-resort fallback
- Celery: retry broker connect on startup (survive sidecar cold start)
- Entrypoint supervisor: restart sidecar/worker if they die; skip worker
entirely when no broker exists
Co-Authored-By: Claude Code <noreply@anthropic.com>
- Dockerfile +2 -1
- Dockerfile.hf +1 -0
- app/tasks/celery_tasks.py +4 -3
- entrypoint.py +111 -28
|
@@ -6,13 +6,14 @@ WORKDIR /app
|
|
| 6 |
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 7 |
curl \
|
| 8 |
build-essential \
|
|
|
|
| 9 |
&& rm -rf /var/lib/apt/lists/*
|
| 10 |
|
| 11 |
# Install Python dependencies
|
| 12 |
COPY requirements.txt .
|
| 13 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 14 |
|
| 15 |
-
# Copy app source + container entrypoint (
|
| 16 |
COPY app/ ./app/
|
| 17 |
COPY entrypoint.py .
|
| 18 |
|
|
|
|
| 6 |
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 7 |
curl \
|
| 8 |
build-essential \
|
| 9 |
+
redis-server \
|
| 10 |
&& rm -rf /var/lib/apt/lists/*
|
| 11 |
|
| 12 |
# Install Python dependencies
|
| 13 |
COPY requirements.txt .
|
| 14 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 15 |
|
| 16 |
+
# Copy app source + container entrypoint (local Redis sidecar, supervises worker)
|
| 17 |
COPY app/ ./app/
|
| 18 |
COPY entrypoint.py .
|
| 19 |
|
|
@@ -6,6 +6,7 @@ WORKDIR /app
|
|
| 6 |
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 7 |
curl \
|
| 8 |
build-essential \
|
|
|
|
| 9 |
&& rm -rf /var/lib/apt/lists/*
|
| 10 |
|
| 11 |
# Install Python dependencies
|
|
|
|
| 6 |
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 7 |
curl \
|
| 8 |
build-essential \
|
| 9 |
+
redis-server \
|
| 10 |
&& rm -rf /var/lib/apt/lists/*
|
| 11 |
|
| 12 |
# Install Python dependencies
|
|
@@ -19,9 +19,10 @@ celery_app.conf.update(
|
|
| 19 |
worker_concurrency=10,
|
| 20 |
task_soft_time_limit=300,
|
| 21 |
task_time_limit=600,
|
| 22 |
-
#
|
| 23 |
-
|
| 24 |
-
|
|
|
|
| 25 |
task_publish_retry=False,
|
| 26 |
task_publish_retry_policy={"max_retries": 1},
|
| 27 |
result_backend_transport_options={
|
|
|
|
| 19 |
worker_concurrency=10,
|
| 20 |
task_soft_time_limit=300,
|
| 21 |
task_time_limit=600,
|
| 22 |
+
# Survive a broker that is still coming up (local sidecar cold start):
|
| 23 |
+
# retry the connection at startup instead of exiting and crash-looping.
|
| 24 |
+
broker_connection_max_retries=None,
|
| 25 |
+
broker_connection_retry_on_startup=True,
|
| 26 |
task_publish_retry=False,
|
| 27 |
task_publish_retry_policy={"max_retries": 1},
|
| 28 |
result_backend_transport_options={
|
|
@@ -4,18 +4,20 @@ Container entrypoint for BRIDGE Modul-X on Hugging Face Spaces.
|
|
| 4 |
|
| 5 |
Responsibilities
|
| 6 |
----------------
|
| 7 |
-
1. Ensure Redis
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
| 16 |
- Celery worker (bulk validation queue)
|
| 17 |
- uvicorn (FastAPI web app on $PORT / 7860)
|
| 18 |
-
|
| 19 |
container exits and the platform restarts it.
|
| 20 |
"""
|
| 21 |
import os
|
|
@@ -28,6 +30,8 @@ import uuid
|
|
| 28 |
# Fixed namespace so the per-store Idempotency-Keys are deterministic.
|
| 29 |
_NS = uuid.UUID("7c9e6679-7425-40de-944b-e07fc1f90ae7")
|
| 30 |
|
|
|
|
|
|
|
| 31 |
|
| 32 |
def _stable_db_id(store: str) -> str:
|
| 33 |
"""Deterministic UUIDv4-FORM id (Upstash rejects non-v4 idempotency keys):
|
|
@@ -38,39 +42,109 @@ def _stable_db_id(store: str) -> str:
|
|
| 38 |
return str(uuid.UUID(bytes=bytes(b)))
|
| 39 |
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
| 43 |
from app.utils.upstash_free import create_database
|
| 44 |
|
| 45 |
-
# First try the stable key (re-fetch after restart); if Upstash rejects
|
| 46 |
-
# it (expired DB), fall back to one fresh random key.
|
| 47 |
for attempt, db_id in enumerate([_stable_db_id(store), ""]):
|
| 48 |
try:
|
| 49 |
db = create_database(db_id=db_id)
|
| 50 |
print(
|
| 51 |
-
f"[ENTRYPOINT] {store}:
|
| 52 |
f"(expires {db.expires}) - claim to keep it: {db.console_url}",
|
| 53 |
flush=True,
|
| 54 |
)
|
| 55 |
return db.connection_string(0)
|
| 56 |
except Exception as exc:
|
| 57 |
-
print(f"[ENTRYPOINT] {store}:
|
| 58 |
return None
|
| 59 |
|
| 60 |
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
url = os.environ.get(env_name, "").strip()
|
| 63 |
if url and "localhost" not in url and "127.0.0.1" not in url:
|
| 64 |
return url
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
|
| 69 |
def main():
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
result_url = _resolve("CELERY_RESULT_BACKEND", "celery-result") or broker_url
|
| 73 |
|
|
|
|
| 74 |
if cache_url:
|
| 75 |
os.environ["REDIS_URL"] = cache_url
|
| 76 |
if broker_url:
|
|
@@ -81,8 +155,6 @@ def main():
|
|
| 81 |
print("[ENTRYPOINT] WARNING: no Redis reachable - bulk jobs use the synchronous fallback", flush=True)
|
| 82 |
|
| 83 |
port = os.environ.get("PORT", "7860")
|
| 84 |
-
children = {}
|
| 85 |
-
state = {"stopping": False}
|
| 86 |
|
| 87 |
def spawn(kind):
|
| 88 |
if kind == "worker":
|
|
@@ -91,6 +163,12 @@ def main():
|
|
| 91 |
"-A", "app.tasks.celery_tasks:celery_app", "worker",
|
| 92 |
"--loglevel=info", "--concurrency=4",
|
| 93 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
else:
|
| 95 |
cmd = [
|
| 96 |
sys.executable, "-m", "uvicorn", "app.main:app",
|
|
@@ -112,16 +190,21 @@ def main():
|
|
| 112 |
signal.signal(signal.SIGTERM, on_signal)
|
| 113 |
signal.signal(signal.SIGINT, on_signal)
|
| 114 |
|
| 115 |
-
|
|
|
|
| 116 |
web = spawn("web")
|
| 117 |
|
| 118 |
while not state["stopping"]:
|
| 119 |
if web.poll() is not None:
|
| 120 |
print(f"[ENTRYPOINT] web exited ({web.returncode}) - shutting down", flush=True)
|
| 121 |
break
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
time.sleep(5)
|
| 126 |
if not state["stopping"]:
|
| 127 |
spawn("worker")
|
|
|
|
| 4 |
|
| 5 |
Responsibilities
|
| 6 |
----------------
|
| 7 |
+
1. Ensure Redis for cache + Celery broker/results, in priority order:
|
| 8 |
+
a. Space secrets win: REDIS_URL / CELERY_BROKER_URL / CELERY_RESULT_BACKEND
|
| 9 |
+
(any non-localhost URL).
|
| 10 |
+
b. Otherwise run a local redis-server sidecar on 127.0.0.1:6379
|
| 11 |
+
(installed in the image; volatile memory, no persistence). This is the
|
| 12 |
+
default production path — no external dependency, no expiry.
|
| 13 |
+
c. If the sidecar binary is unavailable, fall back to Upstash free-tier
|
| 14 |
+
provisioning (deterministic idempotency keys; DBs expire in ~3 days
|
| 15 |
+
unless claimed at the console URL printed here).
|
| 16 |
+
2. Supervise child processes:
|
| 17 |
+
- redis-server (sidecar mode only)
|
| 18 |
- Celery worker (bulk validation queue)
|
| 19 |
- uvicorn (FastAPI web app on $PORT / 7860)
|
| 20 |
+
Sidecar/worker are restarted if they die; if the web process dies the
|
| 21 |
container exits and the platform restarts it.
|
| 22 |
"""
|
| 23 |
import os
|
|
|
|
| 30 |
# Fixed namespace so the per-store Idempotency-Keys are deterministic.
|
| 31 |
_NS = uuid.UUID("7c9e6679-7425-40de-944b-e07fc1f90ae7")
|
| 32 |
|
| 33 |
+
SIDECAR_PORT = 6379
|
| 34 |
+
|
| 35 |
|
| 36 |
def _stable_db_id(store: str) -> str:
|
| 37 |
"""Deterministic UUIDv4-FORM id (Upstash rejects non-v4 idempotency keys):
|
|
|
|
| 42 |
return str(uuid.UUID(bytes=bytes(b)))
|
| 43 |
|
| 44 |
|
| 45 |
+
# --------------------------------------------------------------------------- #
|
| 46 |
+
# Upstash free-tier fallback (only used when no local redis-server exists)
|
| 47 |
+
# --------------------------------------------------------------------------- #
|
| 48 |
+
def _provision_upstash(store: str):
|
| 49 |
from app.utils.upstash_free import create_database
|
| 50 |
|
|
|
|
|
|
|
| 51 |
for attempt, db_id in enumerate([_stable_db_id(store), ""]):
|
| 52 |
try:
|
| 53 |
db = create_database(db_id=db_id)
|
| 54 |
print(
|
| 55 |
+
f"[ENTRYPOINT] upstash {store}: db {db.db_id} ok "
|
| 56 |
f"(expires {db.expires}) - claim to keep it: {db.console_url}",
|
| 57 |
flush=True,
|
| 58 |
)
|
| 59 |
return db.connection_string(0)
|
| 60 |
except Exception as exc:
|
| 61 |
+
print(f"[ENTRYPOINT] upstash {store}: failed (try {attempt}): {exc}", flush=True)
|
| 62 |
return None
|
| 63 |
|
| 64 |
|
| 65 |
+
# --------------------------------------------------------------------------- #
|
| 66 |
+
# Redis resolution
|
| 67 |
+
# --------------------------------------------------------------------------- #
|
| 68 |
+
def _secret_url(env_name: str):
|
| 69 |
+
"""An externally-provided (Space secret) URL wins over any fallback."""
|
| 70 |
url = os.environ.get(env_name, "").strip()
|
| 71 |
if url and "localhost" not in url and "127.0.0.1" not in url:
|
| 72 |
return url
|
| 73 |
+
return None
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _wait_for_redis(url: str, seconds: int = 30) -> bool:
|
| 77 |
+
import redis as _redis
|
| 78 |
+
|
| 79 |
+
deadline = time.monotonic() + seconds
|
| 80 |
+
while time.monotonic() < deadline:
|
| 81 |
+
try:
|
| 82 |
+
client = _redis.Redis.from_url(url, socket_connect_timeout=2, socket_timeout=2)
|
| 83 |
+
if client.ping():
|
| 84 |
+
client.close()
|
| 85 |
+
return True
|
| 86 |
+
except Exception:
|
| 87 |
+
time.sleep(0.5)
|
| 88 |
+
return False
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _resolve_redis(children: dict):
|
| 92 |
+
"""Return (cache, broker, result) URLs and populate `children` with a
|
| 93 |
+
redis-server sidecar process when one is started."""
|
| 94 |
+
cache = _secret_url("REDIS_URL")
|
| 95 |
+
broker = _secret_url("CELERY_BROKER_URL")
|
| 96 |
+
result = _secret_url("CELERY_RESULT_BACKEND")
|
| 97 |
+
if cache or broker or result:
|
| 98 |
+
print("[ENTRYPOINT] using Redis from Space secrets", flush=True)
|
| 99 |
+
cache = cache or broker or result
|
| 100 |
+
broker = broker or cache
|
| 101 |
+
result = result or broker
|
| 102 |
+
return cache, broker, result
|
| 103 |
+
|
| 104 |
+
# Local sidecar: same image, same container, always reachable.
|
| 105 |
+
try:
|
| 106 |
+
proc = subprocess.Popen(
|
| 107 |
+
[
|
| 108 |
+
"redis-server",
|
| 109 |
+
"--port", str(SIDECAR_PORT),
|
| 110 |
+
"--bind", "127.0.0.1",
|
| 111 |
+
"--save", "",
|
| 112 |
+
"--appendonly", "no",
|
| 113 |
+
"--maxmemory", "120mb",
|
| 114 |
+
"--maxmemory-policy", "allkeys-lru",
|
| 115 |
+
],
|
| 116 |
+
env=os.environ,
|
| 117 |
+
)
|
| 118 |
+
children["redis"] = proc
|
| 119 |
+
print(f"[ENTRYPOINT] redis-server sidecar started (pid {proc.pid})", flush=True)
|
| 120 |
+
except FileNotFoundError:
|
| 121 |
+
print("[ENTRYPOINT] redis-server binary missing - using Upstash fallback", flush=True)
|
| 122 |
+
except Exception as exc:
|
| 123 |
+
print(f"[ENTRYPOINT] sidecar spawn failed ({exc}) - using Upstash fallback", flush=True)
|
| 124 |
+
|
| 125 |
+
if "redis" in children:
|
| 126 |
+
base = f"redis://127.0.0.1:{SIDECAR_PORT}"
|
| 127 |
+
if _wait_for_redis(f"{base}/0"):
|
| 128 |
+
print("[ENTRYPOINT] sidecar PONG ok", flush=True)
|
| 129 |
+
# Separate logical DBs for cache / broker / results.
|
| 130 |
+
return f"{base}/0", f"{base}/1", f"{base}/2"
|
| 131 |
+
print("[ENTRYPOINT] sidecar never answered PING - falling back", flush=True)
|
| 132 |
+
try:
|
| 133 |
+
children.pop("redis").terminate()
|
| 134 |
+
except Exception:
|
| 135 |
+
pass
|
| 136 |
+
|
| 137 |
+
cache = _provision_upstash("cache")
|
| 138 |
+
broker = _provision_upstash("celery-broker") or cache
|
| 139 |
+
result = _provision_upstash("celery-result") or broker
|
| 140 |
+
return cache, broker, result
|
| 141 |
|
| 142 |
|
| 143 |
def main():
|
| 144 |
+
children = {}
|
| 145 |
+
state = {"stopping": False}
|
|
|
|
| 146 |
|
| 147 |
+
cache_url, broker_url, result_url = _resolve_redis(children)
|
| 148 |
if cache_url:
|
| 149 |
os.environ["REDIS_URL"] = cache_url
|
| 150 |
if broker_url:
|
|
|
|
| 155 |
print("[ENTRYPOINT] WARNING: no Redis reachable - bulk jobs use the synchronous fallback", flush=True)
|
| 156 |
|
| 157 |
port = os.environ.get("PORT", "7860")
|
|
|
|
|
|
|
| 158 |
|
| 159 |
def spawn(kind):
|
| 160 |
if kind == "worker":
|
|
|
|
| 163 |
"-A", "app.tasks.celery_tasks:celery_app", "worker",
|
| 164 |
"--loglevel=info", "--concurrency=4",
|
| 165 |
]
|
| 166 |
+
elif kind == "redis":
|
| 167 |
+
cmd = [
|
| 168 |
+
"redis-server", "--port", str(SIDECAR_PORT), "--bind", "127.0.0.1",
|
| 169 |
+
"--save", "", "--appendonly", "no",
|
| 170 |
+
"--maxmemory", "120mb", "--maxmemory-policy", "allkeys-lru",
|
| 171 |
+
]
|
| 172 |
else:
|
| 173 |
cmd = [
|
| 174 |
sys.executable, "-m", "uvicorn", "app.main:app",
|
|
|
|
| 190 |
signal.signal(signal.SIGTERM, on_signal)
|
| 191 |
signal.signal(signal.SIGINT, on_signal)
|
| 192 |
|
| 193 |
+
if broker_url:
|
| 194 |
+
spawn("worker")
|
| 195 |
web = spawn("web")
|
| 196 |
|
| 197 |
while not state["stopping"]:
|
| 198 |
if web.poll() is not None:
|
| 199 |
print(f"[ENTRYPOINT] web exited ({web.returncode}) - shutting down", flush=True)
|
| 200 |
break
|
| 201 |
+
if "redis" in children and children["redis"].poll() is not None:
|
| 202 |
+
print("[ENTRYPOINT] redis sidecar exited - restarting in 2s", flush=True)
|
| 203 |
+
time.sleep(2)
|
| 204 |
+
if not state["stopping"]:
|
| 205 |
+
spawn("redis")
|
| 206 |
+
if broker_url and children["worker"].poll() is not None:
|
| 207 |
+
print(f"[ENTRYPOINT] worker exited ({children['worker'].returncode}) - restarting in 5s", flush=True)
|
| 208 |
time.sleep(5)
|
| 209 |
if not state["stopping"]:
|
| 210 |
spawn("worker")
|