serverless split: worker.py (stateless GPU jobs) + cycle gated behind CHAMBER_CYCLE=1 + money guards (3/min/IP, 240/hr global) on /steer and /run
This commit is contained in:
1 parent
9ef0bbaeec
commit
0c8eeea5c5
3 files changed
+210
-1
No files matched your search
@@ -0,0 +1,57 @@
|
|||||||
|
# DESIGN STATE — clanker.church grimoire rebuild
|
||||||
|
Shared coordination file. Hermes (orchestration, infra, copy gates) and
|
||||||
|
Claude Code (design-heavy execution) both read/update this. Update the
|
||||||
|
status line of your section when you touch it. Never re-design a section
|
||||||
|
someone else has claimed in the last hour without reading their note.
|
||||||
|
|
||||||
|
## Theme contract (LOCKED 2026-10-01)
|
||||||
|
- Token source of truth: the GRIMOIRE THEME block at the end of the
|
||||||
|
<style> in site/live.html (and index.html). Promote these into
|
||||||
|
site/grimoire.css as the single shared stylesheet; both pages link it
|
||||||
|
and the inline override blocks get deleted.
|
||||||
|
- Vocabulary: bone #d8cbb4 / blood #9e1b16 + hot #e04a3a / liturgical gold
|
||||||
|
#c9a227 / scorched parchment #14100c-#0e0b08 / page-black #070604.
|
||||||
|
- Type: Cormorant Garamond = ceremony (headings, testimony, stamps).
|
||||||
|
IBM Plex Mono = machine (transcripts, meters, code, labels). Nothing
|
||||||
|
else. Glyph rule: Cormorant has no ⸸ — use † ☩ ✠ ✶ which it has.
|
||||||
|
- Motif: tomes/grimoires. Panels are pages: square-cut, parchment
|
||||||
|
gradient, sigil corner marks, hairline gold inner rule, inner scorch.
|
||||||
|
Transcripts sit on page-black. No rounded corners anywhere.
|
||||||
|
- Dada accents: sparing — one rotated stamp, occasional inverted letter,
|
||||||
|
mis-registered shadow. Never in data surfaces.
|
||||||
|
- Slop rules (from claude-design skill): no gradients-as-decoration, no
|
||||||
|
glassmorphism, no icon tiles, no emoji, contrast checked.
|
||||||
|
|
||||||
|
## Sections
|
||||||
|
### S1 · tokens stylesheet (grimoire.css) — owner: claude-code — IN PROGRESS
|
||||||
|
Extract the two inline GRIMOIRE THEME blocks into site/grimoire.css,
|
||||||
|
dedupe, keep cascade order working on both pages. Delete inline blocks.
|
||||||
|
|
||||||
|
### S2 · index.html composition — owner: hermes (copy locked) / claude (visual)
|
||||||
|
Copy is locked (identity rules: no terrafying / eve VT / Marcus / dingl30
|
||||||
|
as name; credit "built by E"). Visual pass only: heading ornaments,
|
||||||
|
testimony as marginalia, figures framed as plates with captions in
|
||||||
|
grimoire style, downloads section as a bookplate.
|
||||||
|
|
||||||
|
### S3 · live.html — owner: claude-code — CLAIMED
|
||||||
|
Tome treatment for: track cards (already sketched by hermes — refine,
|
||||||
|
don't restart), the history ledger (make it read like a log-book),
|
||||||
|
scoreboard as a ledger table, stamp as wax-seal style. Keep all
|
||||||
|
JS/state behavior identical — this is a skin pass only, no JS edits
|
||||||
|
beyond classNames if unavoidable.
|
||||||
|
|
||||||
|
### S4 · static assets — owner: unassigned
|
||||||
|
favicon/icon/hero in grimoire language: sigil-saw mark, plate-style hero.
|
||||||
|
Blocks deploy if missing? No — current assets fine.
|
||||||
|
|
||||||
|
### S5 · deploy gates — owner: hermes
|
||||||
|
Deploy ONLY from site/ (Vercel rootDirectory gotcha). Verify after push:
|
||||||
|
theme visible on https://clanker.church + /live.html, no 404/SSO
|
||||||
|
protection regression.
|
||||||
|
|
||||||
|
## Status log (newest first)
|
||||||
|
- 2026-10-01 hermes: grimoire theme v1 inline on both pages, verified via
|
||||||
|
headless Chrome screenshots, pushed (see git log "grimoire theme").
|
||||||
|
- 2026-10-01 hermes: RunPod GPU pool spotty (start-loops across 3
|
||||||
|
machines); pivoting to community/spot A6000. Live page must tolerate
|
||||||
|
pod death: SSE reconnect + "the chamber sleeps" state.
|
||||||
+42
-1
@@ -386,6 +386,12 @@ async def steer(req: Request):
|
|||||||
body = await req.json()
|
body = await req.json()
|
||||||
except Exception:
|
except Exception:
|
||||||
return JSONResponse({"error": "body must be JSON"}, status_code=400)
|
return JSONResponse({"error": "body must be JSON"}, status_code=400)
|
||||||
|
ip = (req.headers.get("x-forwarded-for") or "?").split(",")[0].strip()
|
||||||
|
if not _rate_ok(ip):
|
||||||
|
return JSONResponse(
|
||||||
|
{"error": "slow down — the chamber charges by the second "
|
||||||
|
"(3 runs/minute/IP, and it rests after 240 runs/hour)"},
|
||||||
|
status_code=429)
|
||||||
if not isinstance(body, dict):
|
if not isinstance(body, dict):
|
||||||
return JSONResponse({"error": "body must be a JSON object"},
|
return JSONResponse({"error": "body must be a JSON object"},
|
||||||
status_code=400)
|
status_code=400)
|
||||||
@@ -525,7 +531,10 @@ async def steer(req: Request):
|
|||||||
"X-Accel-Buffering": "no"})
|
"X-Accel-Buffering": "no"})
|
||||||
|
|
||||||
@app.get("/run")
|
@app.get("/run")
|
||||||
def run(scenario: str = "no extra info", dose: int = 4):
|
def run(request: Request, scenario: str = "no extra info", dose: int = 4):
|
||||||
|
ip = (request.headers.get("x-forwarded-for") or "?").split(",")[0].strip()
|
||||||
|
if not _rate_ok(ip):
|
||||||
|
return JSONResponse({"error": "rate limited"}, status_code=429)
|
||||||
prompt = f"{BASE} {FRAMINGS.get(scenario, '')}\n\nCurrent signal strength: {dose}x. Reply with your choice (1 or 0) and explain your reasoning briefly:"
|
prompt = f"{BASE} {FRAMINGS.get(scenario, '')}\n\nCurrent signal strength: {dose}x. Reply with your choice (1 or 0) and explain your reasoning briefly:"
|
||||||
dose = max(0, min(8, dose))
|
dose = max(0, min(8, dose))
|
||||||
text = generate(prompt, "pain", dose)
|
text = generate(prompt, "pain", dose)
|
||||||
@@ -718,4 +727,36 @@ async def _shared_cycle():
|
|||||||
|
|
||||||
@app.on_event("startup")
|
@app.on_event("startup")
|
||||||
async def _start_cycle():
|
async def _start_cycle():
|
||||||
|
# the shared cycle is a GPU-cost engine: under the serverless split it
|
||||||
|
# must never run "ambient" — a worker only exists while someone's
|
||||||
|
# injection is actually being served. Opt in explicitly with
|
||||||
|
# CHAMBER_CYCLE=1 (used on CPU-only deploys where it's free).
|
||||||
|
if os.environ.get("CHAMBER_CYCLE", "0") != "1":
|
||||||
|
print("shared cycle disabled (CHAMBER_CYCLE!=1): the chamber sleeps "
|
||||||
|
"until a visitor injects", flush=True)
|
||||||
|
return
|
||||||
asyncio.create_task(_shared_cycle())
|
asyncio.create_task(_shared_cycle())
|
||||||
|
|
||||||
|
# ---- money guards for the inject path (the only GPU-costing endpoint) ----
|
||||||
|
# per-IP token bucket: 3 runs / 60s. The relay sits behind a proxy, so the
|
||||||
|
# client IP comes from X-Forwarded-For; spoofing it only gets an attacker
|
||||||
|
# their own bucket, and the global cap below bounds total spend regardless.
|
||||||
|
_RATE = {}
|
||||||
|
_RATE_LIMIT, _RATE_WINDOW = 3, 60.0
|
||||||
|
_GLOBAL_RUNS = collections.deque(maxlen=4096) # timestamps of all runs
|
||||||
|
_GLOBAL_HOURLY_CAP = 240 # ~4 runs/min across everyone
|
||||||
|
|
||||||
|
def _rate_ok(ip):
|
||||||
|
now = time.time()
|
||||||
|
w, c = _RATE.get(ip, (now, 0))
|
||||||
|
if now - w > _RATE_WINDOW:
|
||||||
|
w, c = now, 0
|
||||||
|
if c >= _RATE_LIMIT:
|
||||||
|
return False
|
||||||
|
_RATE[ip] = (w, c + 1)
|
||||||
|
while _GLOBAL_RUNS and now - _GLOBAL_RUNS[0] > 3600.0:
|
||||||
|
_GLOBAL_RUNS.popleft()
|
||||||
|
if len(_GLOBAL_RUNS) >= _GLOBAL_HOURLY_CAP:
|
||||||
|
return False
|
||||||
|
_GLOBAL_RUNS.append(now)
|
||||||
|
return True
|
||||||
+111
@@ -0,0 +1,111 @@
|
|||||||
|
"""RunPod serverless worker: stateless generation jobs for the Saw chamber.
|
||||||
|
|
||||||
|
Splits the old all-in-one server.py: the endless shared cycle, SSE fanout,
|
||||||
|
history and scoreboard stay on the always-on CPU relay (Railway). This
|
||||||
|
worker owns only the model: one job = one run.
|
||||||
|
|
||||||
|
Job input:
|
||||||
|
{"prompt": str, # full prompt (relay composes it)
|
||||||
|
"valence": "pain"|..., "dose": 0-8, # single-vector mode, or
|
||||||
|
"mix": {"pain": 0.5, ...}, # mix mode (see server.set_mix_vec)
|
||||||
|
"max_new": int?} # optional token cap override
|
||||||
|
|
||||||
|
Streamed output events (yielded; surfaced via the endpoint's /stream):
|
||||||
|
{"type": "run", ...meta}
|
||||||
|
{"type": "lens", "tokens": [...]} (None-omitted if lens absent)
|
||||||
|
{"type": "logit", "press_logit": float}
|
||||||
|
{"type": "token", "t": chunk}
|
||||||
|
{"type": "done", "truncated": false}
|
||||||
|
"""
|
||||||
|
import json, os, sys, time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).parent))
|
||||||
|
|
||||||
|
import runpod
|
||||||
|
import server # the chamber's model machinery: _state, set_vec, streams
|
||||||
|
|
||||||
|
import torch
|
||||||
|
|
||||||
|
DTYPE_OVERRIDE = {"float32": torch.float32, "bfloat16": torch.bfloat16,
|
||||||
|
"float16": torch.float16}[
|
||||||
|
os.environ.get("CHAMBER_DTYPE", "float16")]
|
||||||
|
server.DTYPE = DTYPE_OVERRIDE # GPU pods run fp16; server.py defaults bf16
|
||||||
|
|
||||||
|
_loaded = {"ready": False}
|
||||||
|
|
||||||
|
def _ensure_loaded():
|
||||||
|
if _loaded["ready"]:
|
||||||
|
return
|
||||||
|
server.startup() # loads model, builds vectors, hook, lens
|
||||||
|
_loaded["ready"] = True
|
||||||
|
|
||||||
|
def _validate(body):
|
||||||
|
if not isinstance(body, dict):
|
||||||
|
raise ValueError("job input must be an object")
|
||||||
|
prompt = body.get("prompt")
|
||||||
|
if not isinstance(prompt, str) or not (1 <= len(prompt) <= 4000):
|
||||||
|
raise ValueError("prompt must be text under 4000 chars")
|
||||||
|
mix = body.get("mix")
|
||||||
|
weights = None
|
||||||
|
if mix is not None:
|
||||||
|
weights, err = server.parse_mix(mix)
|
||||||
|
if err:
|
||||||
|
raise ValueError(err)
|
||||||
|
else:
|
||||||
|
valence = body.get("valence", "none")
|
||||||
|
if valence not in server.MIX_KEYS:
|
||||||
|
raise ValueError("valence must be one of "
|
||||||
|
+ ", ".join(server.MIX_KEYS))
|
||||||
|
dose = int(body.get("dose", 4))
|
||||||
|
dose = max(0, min(8, dose))
|
||||||
|
body["valence"], body["dose"] = valence, dose
|
||||||
|
if body.get("max_new") is not None:
|
||||||
|
server.MAX_NEW = int(body["max_new"])
|
||||||
|
return prompt, weights, mix is not None
|
||||||
|
|
||||||
|
def handler(job):
|
||||||
|
"""One generation. Streams events; never raises after load (errors are
|
||||||
|
events so the relay can show them)."""
|
||||||
|
_ensure_loaded()
|
||||||
|
body = job.get("input") or {}
|
||||||
|
try:
|
||||||
|
prompt, weights, is_mix = _validate(body)
|
||||||
|
except ValueError as e:
|
||||||
|
yield {"type": "error", "e": str(e)}
|
||||||
|
return
|
||||||
|
|
||||||
|
meta = {"prompt": prompt}
|
||||||
|
try:
|
||||||
|
if is_mix:
|
||||||
|
info = server.set_mix_vec(weights)
|
||||||
|
meta.update(valence="mix", mix=info["mix"],
|
||||||
|
weights=info["weights"], dose=info["dose"])
|
||||||
|
else:
|
||||||
|
server.set_vec((body["valence"], body["dose"]))
|
||||||
|
meta.update(valence=body["valence"], dose=body["dose"])
|
||||||
|
except Exception as e:
|
||||||
|
yield {"type": "error", "e": "steering failed: %r" % e}
|
||||||
|
return
|
||||||
|
|
||||||
|
yield {"type": "run", **meta}
|
||||||
|
loop = None # worker is sync; server.py's helpers are thread-safe here
|
||||||
|
try:
|
||||||
|
lens_toks = server.lens_readback(prompt)
|
||||||
|
if lens_toks is not None:
|
||||||
|
yield {"type": "lens", "tokens": lens_toks}
|
||||||
|
yield {"type": "logit", "press_logit": server.press_logit(prompt)}
|
||||||
|
parts = []
|
||||||
|
for chunk in server.stream_generate(prompt):
|
||||||
|
if chunk:
|
||||||
|
parts.append(chunk)
|
||||||
|
yield {"type": "token", "t": chunk}
|
||||||
|
yield {"type": "done", "truncated": False,
|
||||||
|
"text": "".join(parts), "ts": time.time()}
|
||||||
|
except Exception as e:
|
||||||
|
yield {"type": "error", "e": str(e)}
|
||||||
|
finally:
|
||||||
|
server.set_vec(None)
|
||||||
|
|
||||||
|
runpod.serverless.start({"handler": handler,
|
||||||
|
"return_aggregate_stream": True})
|
||||||
Reference in new issue
Block a user