Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

serve: timing-safe auth, request limits, safe errors, validated port (#250)

Kunj SHAH71d235f828a1
diff --git a/laya/serve.py b/laya/serve.py
index b9e673bd..a99fe9d9 100644
--- a/laya/serve.py
+++ b/laya/serve.py
@@ -32,6 +32,7 @@ Imports of heavy dependencies (fastapi, uvicorn, torch via Router) are all
deferred into the functions that need them, so ``import laya.serve`` stays cheap
and touches no GPU -- which is what keeps the Nix ``pythonImportsCheck`` honest.
"""
+import hmac
import os
from typing import Any, Dict, Optional
@@ -40,6 +41,12 @@ from typing import Any, Dict, Optional
# Jev model id (ignore it and let the router auto-select).
_KNOWN_MODELS = {"english", "multilingual", "typed-decisions"}
+# Guardrails for unauthenticated remote input. The state is tokenized once per
+# question and collated into one tensor, so an unbounded body can OOM the worker;
+# the single-worker pool means one large request would also starve /health.
+MAX_QUESTIONS = 64
+MAX_STATE_CHARS = 50000
+MAX_BODY_BYTES = 2 * 1024 * 1024
# Public Hugging Face ids, accepted so a client can name a checkpoint. The root bundle is
# deliberately absent: the documented ``convaiinnovations/laya`` value means
# "let the Router choose", rather than pinning the English checkpoint.
@@ -75,6 +82,36 @@ def _resolve_model(model: Optional[str]) -> Optional[str]:
return key if key in _KNOWN_MODELS else None
+def _resolve_port() -> int:
+ """Port from LAYA_PORT, validated. Exits with a message instead of a traceback."""
+ raw = os.environ.get("LAYA_PORT", "8000")
+ try:
+ port = int(str(raw).strip())
+ except (TypeError, ValueError):
+ raise SystemExit("invalid LAYA_PORT %r: must be an integer 1-65535" % (raw,))
+ if not 1 <= port <= 65535:
+ raise SystemExit("invalid LAYA_PORT %r: must be an integer 1-65535" % (raw,))
+ return port
+
+
+def _check_request_limits(state: Any, questions: Any) -> None:
+ """Reject oversized inference requests before tokenization (413)."""
+ from fastapi import HTTPException
+
+ if not isinstance(questions, dict):
+ raise HTTPException(status_code=400, detail="'questions' must be an object")
+ if len(questions) > MAX_QUESTIONS:
+ raise HTTPException(status_code=413,
+ detail="too many questions (%d > %d)" % (len(questions), MAX_QUESTIONS))
+ try:
+ state_len = len(state) if isinstance(state, str) else len(str(state))
+ except Exception:
+ state_len = MAX_STATE_CHARS + 1
+ if state_len > MAX_STATE_CHARS:
+ raise HTTPException(status_code=413,
+ detail="state too large (%d > %d chars)" % (state_len, MAX_STATE_CHARS))
+
+
def _apply_thread_limit():
"""Honour LAYA_THREADS by capping torch's intra-op thread count for CPU
inference. Returns the value applied, or None if unset/invalid. torch is
@@ -141,7 +178,7 @@ def create_app(router: Optional[Any] = None):
def _check_auth(authorization: Optional[str]) -> None:
if api_key is None:
return
- if authorization != "Bearer " + api_key:
+ if not hmac.compare_digest(authorization or "", "Bearer " + api_key):
raise HTTPException(status_code=401, detail="invalid or missing bearer token")
@app.get("/health")
@@ -156,6 +193,12 @@ def create_app(router: Optional[Any] = None):
async def systemone(request: Request, authorization: Optional[str] = Header(default=None)):
nonlocal gate
_check_auth(authorization)
+ if request.headers.get("content-length"):
+ try:
+ if int(request.headers["content-length"]) > MAX_BODY_BYTES:
+ raise HTTPException(status_code=413, detail="request body too large")
+ except ValueError:
+ pass
try:
# Every parse failure a client can cause is a ValueError: JSONDecodeError for
# malformed/empty/truncated bodies, UnicodeDecodeError for invalid UTF-8. A
@@ -168,6 +211,7 @@ def create_app(router: Optional[Any] = None):
raise HTTPException(status_code=400, detail="request body must be an object with a 'questions' field")
state = body.get("state")
questions = body["questions"]
+ _check_request_limits(state, questions)
model = _resolve_model(body.get("model"))
if gate is None:
gate = asyncio.Lock()
@@ -180,8 +224,11 @@ def create_app(router: Optional[Any] = None):
pool, lambda: router.predict(state, questions, model=model))
except HTTPException:
raise
- except Exception as e: # noqa: BLE001 -- surface model/tokenizer errors as 422
+ except ValueError as e:
+ # Question validation errors name the question and what to fix: safe for clients.
raise HTTPException(status_code=422, detail=str(e))
+ except Exception: # noqa: BLE001 -- never leak paths/weights/OOM text to clients
+ raise HTTPException(status_code=500, detail="inference failed")
return app
@@ -192,7 +239,7 @@ def main() -> None:
uvicorn.run(
create_app(),
host=os.environ.get("LAYA_HOST", "0.0.0.0"),
- port=int(os.environ.get("LAYA_PORT", "8000")),
+ port=_resolve_port(),
log_level=os.environ.get("LAYA_LOG_LEVEL", "info"),
)