cmvr-visual/inference/llm_services/store.py

542 lines
27 KiB
Python

"""Persistent single-host queue and workspace-confined file helpers.
The runner is untrusted input-wise, but is managed code: it must not daemonize
or move children into another process group. No model libraries are imported.
"""
from contextlib import contextmanager
from dataclasses import dataclass
import hashlib
import json
import math
import os
from pathlib import Path
import sqlite3
import stat
import time
import uuid
from .scheduling import eligibility, normalize_scheduling, guarded_eligibility
TASK_TYPES = frozenset({"image.generate", "video.generate", "defect.generate", "audio.transcribe"})
TERMINAL_STATES = frozenset({"succeeded", "failed", "cancelled", "timed_out"})
class IdempotencyConflict(ValueError):
pass
def confined_path(path, root, *, must_exist=False, file_only=False):
"""Resolve every symlink and require the result to stay under root."""
root = Path(root).resolve(strict=True)
candidate = Path(path)
if not candidate.is_absolute():
candidate = root / candidate
try:
resolved = candidate.resolve(strict=must_exist)
resolved.relative_to(root)
except (OSError, RuntimeError, ValueError) as exc:
raise ValueError("Path is unavailable or outside the permitted workspace") from exc
if file_only and not resolved.is_file():
raise ValueError("Input/output path must be an existing regular file")
return resolved
def open_confined_file(path, root):
"""Open, then validate the actual Linux fd to avoid symlink-swap downloads."""
resolved = confined_path(path, root, must_exist=True, file_only=True)
fd = os.open(resolved, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
try:
if not stat.S_ISREG(os.fstat(fd).st_mode):
raise ValueError("Only regular files may be read")
if os.name == "posix":
# Fail closed if /proc is unavailable in the production Linux sandbox.
actual = Path(os.readlink(f"/proc/self/fd/{fd}"))
confined_path(actual, root, must_exist=True, file_only=True)
elif not os.path.samefile(resolved, path):
raise ValueError("File changed while opening")
return os.fdopen(fd, "rb")
except BaseException:
os.close(fd)
raise
def atomic_json(path, value):
path = Path(path)
temporary = path.with_name(path.name + "." + uuid.uuid4().hex + ".tmp")
try:
with temporary.open("x", encoding="utf-8") as handle:
json.dump(value, handle, ensure_ascii=False, allow_nan=False)
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary, path)
if os.name == "posix":
fd = os.open(path.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
try:
os.fsync(fd)
finally:
os.close(fd)
finally:
temporary.unlink(missing_ok=True)
@dataclass
class Settings:
app_root: Path
workspace_root: Path
runner_python: str = "/workspace/envs/vllm/bin/python"
poll_seconds: float = .2
terminate_grace_seconds: float = 5.0
kill_wait_seconds: float = 10.0
def __post_init__(self):
self.workspace_root = Path(self.workspace_root).resolve()
self.app_root = Path(self.app_root).resolve()
try:
self.app_root.relative_to(self.workspace_root)
except ValueError as exc:
raise ValueError("APP_ROOT must be below WORKSPACE_ROOT") from exc
for field in ("poll_seconds", "terminate_grace_seconds", "kill_wait_seconds"):
value = float(getattr(self, field))
if not math.isfinite(value) or value <= 0:
raise ValueError(field + " must be positive and finite")
setattr(self, field, value)
@property
def state_dir(self):
return self.app_root / "state"
@property
def db_path(self):
return self.state_dir / "jobs.sqlite3"
@property
def jobs_dir(self):
return self.app_root / "jobs"
@property
def outputs_dir(self):
return self.workspace_root / "outputs" / "llm-services"
@property
def key_file(self):
return self.app_root / "config" / "api_key"
@property
def worker_lock(self):
return self.state_dir / "worker.lock"
@property
def runner_marker(self):
return self.state_dir / "active-runner.json"
@classmethod
def from_env(cls):
root = Path(os.environ.get("APP_ROOT", "/workspace/projects/llm-services"))
workspace = Path(os.environ.get("WORKSPACE_ROOT", "/workspace"))
data = {}
for candidate in (root / "config" / "settings.json", root / "settings.json"):
if candidate.exists():
with open_confined_file(candidate, workspace) as handle:
data = json.load(handle)
if not isinstance(data, dict):
raise ValueError("settings.json must be an object")
break
return cls(root, workspace,
runner_python=os.environ.get("LLM_RUNNER_PYTHON", data.get("runner_python", cls.runner_python)),
poll_seconds=data.get("poll_seconds", .2),
terminate_grace_seconds=data.get("terminate_grace_seconds", 5),
kill_wait_seconds=data.get("kill_wait_seconds", 10))
def validate_request(task_type, inputs, parameters, workspace):
if task_type not in TASK_TYPES:
raise ValueError("Unsupported task_type")
if not isinstance(inputs, dict) or not isinstance(parameters, dict):
raise ValueError("input and parameters must be JSON objects")
path_names = {"path", "file", "image", "audio", "video", "control_image"}
def walk(value, key="", depth=0):
if depth > 20:
raise ValueError("Request nesting is too deep")
is_path = key in path_names or key.endswith(("_path", "_file", "_paths", "_files"))
if is_path and value is not None:
if isinstance(value, list):
return [str(confined_path(item, workspace, must_exist=True, file_only=True))
for item in value]
if not isinstance(value, str) or not value:
raise ValueError("File inputs must be nonempty paths")
return str(confined_path(value, workspace, must_exist=True, file_only=True))
if isinstance(value, dict):
return {str(k): walk(v, str(k), depth + 1) for k, v in value.items()}
if isinstance(value, list):
return [walk(v, "", depth + 1) for v in value]
return value
result = walk(inputs), walk(parameters)
# Reject NaN, Infinity and non-JSON objects before anything reaches SQLite.
json.dumps(result, allow_nan=False)
return result
class Store:
def __init__(self, path):
self.path = Path(path)
self.path.parent.mkdir(parents=True, exist_ok=True)
with self._connection() as connection:
connection.executescript("""
CREATE TABLE IF NOT EXISTS jobs (
queue_seq INTEGER PRIMARY KEY AUTOINCREMENT,
id TEXT NOT NULL UNIQUE,
task_type TEXT NOT NULL,
input_json TEXT NOT NULL,
parameters_json TEXT NOT NULL,
timeout_seconds REAL NOT NULL,
state TEXT NOT NULL,
stage TEXT NOT NULL DEFAULT 'queued',
cancel_requested INTEGER NOT NULL DEFAULT 0,
idempotency_key TEXT UNIQUE,
request_hash TEXT NOT NULL,
created_at REAL NOT NULL,
updated_at REAL NOT NULL,
started_at REAL,
finished_at REAL,
runner_pid INTEGER,
runner_start TEXT,
runner_pgid INTEGER,
error TEXT,
result_json TEXT
);
CREATE INDEX IF NOT EXISTS jobs_state_queue ON jobs(state, queue_seq);
CREATE UNIQUE INDEX IF NOT EXISTS one_running_job ON jobs(state) WHERE state='running';
""")
# API and worker may initialize together. Serialize schema changes
# and inspect columns again while holding the migration transaction.
connection.execute("BEGIN IMMEDIATE")
try:
columns = {row["name"] for row in connection.execute("PRAGMA table_info(jobs)")}
additions = {"attempt_count": "INTEGER NOT NULL DEFAULT 0",
"preemptions": "INTEGER NOT NULL DEFAULT 0", "gpu_uuid": "TEXT",
"last_preempted_at": "REAL", "last_preempted_reason": "TEXT",
"scheduling_json": "TEXT", "execution_mode": "TEXT NOT NULL DEFAULT 'interactive'",
"principal_id": "TEXT NOT NULL DEFAULT 'legacy'", "batch_id": "TEXT",
"admission_paused": "INTEGER NOT NULL DEFAULT 0",
"control_version": "INTEGER NOT NULL DEFAULT 0"}
for name, definition in additions.items():
if name not in columns:
connection.execute(f"ALTER TABLE jobs ADD COLUMN {name} {definition}")
connection.execute("CREATE TABLE IF NOT EXISTS scheduler_state (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
connection.execute("CREATE TABLE IF NOT EXISTS control_commands (id TEXT PRIMARY KEY, job_id TEXT NOT NULL, request_hash TEXT NOT NULL)")
connection.execute("CREATE INDEX IF NOT EXISTS jobs_admission ON jobs(state,admission_paused,execution_mode,queue_seq)")
connection.commit()
except BaseException:
connection.rollback()
raise
@contextmanager
def _connection(self):
connection = sqlite3.connect(self.path, timeout=10, isolation_level=None)
connection.row_factory = sqlite3.Row
try:
connection.execute("PRAGMA journal_mode=WAL")
connection.execute("PRAGMA synchronous=FULL")
connection.execute("PRAGMA busy_timeout=10000")
yield connection
finally:
connection.close()
@staticmethod
def _decode(row):
if row is None:
return None
job = dict(row)
job["input"] = json.loads(job.pop("input_json"))
job["parameters"] = json.loads(job.pop("parameters_json"))
result = job.pop("result_json")
job["result"] = json.loads(result) if result is not None else None
job["cancel_requested"] = bool(job["cancel_requested"])
job["scheduling"] = json.loads(job.pop("scheduling_json")) if job["scheduling_json"] is not None else None
job.pop("scheduling_json", None)
job["admission_paused"] = bool(job["admission_paused"])
job["execution_id"] = f"{job['id']}:{job['attempt_count']}" if job["attempt_count"] else None
job.pop("request_hash", None)
job.pop("idempotency_key", None)
return job
def submit(self, task_type, inputs, parameters, timeout_seconds=3600, *, idempotency_key=None, scheduling=None):
if task_type not in TASK_TYPES:
raise ValueError("Unsupported task_type")
timeout_seconds = float(timeout_seconds)
if not math.isfinite(timeout_seconds) or not 0 < timeout_seconds <= 86400:
raise ValueError("timeout_seconds must be between 0 and 86400")
if idempotency_key is not None and not 0 < len(idempotency_key) <= 128:
raise ValueError("Idempotency-Key must contain 1 to 128 characters")
scheduling = normalize_scheduling(scheduling)
values = [task_type, inputs, parameters, timeout_seconds]
if scheduling is not None:
values.append({"schema_version": 2, "scheduling": scheduling})
payload = json.dumps(values, sort_keys=True,
separators=(",", ":"), ensure_ascii=False, allow_nan=False)
fingerprint = hashlib.sha256(payload.encode()).hexdigest()
now, job_id = time.time(), uuid.uuid4().hex
with self._connection() as connection:
connection.execute("BEGIN IMMEDIATE")
try:
if idempotency_key:
row = connection.execute("SELECT * FROM jobs WHERE idempotency_key=?",
(idempotency_key,)).fetchone()
if row:
if row["request_hash"] != fingerprint:
raise IdempotencyConflict("Idempotency-Key was used with different parameters")
connection.commit()
return self._decode(row)
connection.execute("""INSERT INTO jobs
(id,task_type,input_json,parameters_json,timeout_seconds,state,
idempotency_key,request_hash,created_at,updated_at,scheduling_json,execution_mode,principal_id,batch_id)
VALUES (?,?,?,?,?,'queued',?,?,?,?,?,?,?,?)""",
(job_id, task_type, json.dumps(inputs, allow_nan=False),
json.dumps(parameters, allow_nan=False), timeout_seconds,
idempotency_key, fingerprint, now, now,
json.dumps(scheduling, sort_keys=True) if scheduling is not None else None,
(scheduling or {}).get("execution_mode", "interactive"),
(scheduling or {}).get("principal_id", "legacy"), (scheduling or {}).get("batch_id")))
connection.commit()
except BaseException:
connection.rollback()
raise
return self.get(job_id)
def get(self, job_id):
with self._connection() as connection:
return self._decode(connection.execute("SELECT * FROM jobs WHERE id=?", (job_id,)).fetchone())
def running(self):
with self._connection() as connection:
return [self._decode(row) for row in connection.execute("SELECT * FROM jobs WHERE state='running'")]
@staticmethod
def _state(connection, key, default=""):
row = connection.execute("SELECT value FROM scheduler_state WHERE key=?", (key,)).fetchone()
return row["value"] if row else default
@staticmethod
def _set_state(connection, key, value):
connection.execute("INSERT INTO scheduler_state(key,value) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", (key, str(value)))
def _select_next(self, connection, now):
opened = self._batch_eligibility(connection, now)["eligible"]
streak = int(self._state(connection, "interactive_streak", "0"))
modes = ["batch", "interactive"] if opened and streak >= 4 else ["interactive", "batch"]
for mode in modes:
if mode == "batch" and not opened:
continue
principals = [row[0] for row in connection.execute("""SELECT DISTINCT principal_id FROM jobs
WHERE state='queued' AND admission_paused=0 AND execution_mode=? ORDER BY principal_id""", (mode,))]
if not principals:
continue
previous = self._state(connection, "last_principal_" + mode)
owner = next((p for p in principals if p > previous), principals[0])
groups = [row[0] for row in connection.execute("""SELECT DISTINCT COALESCE(batch_id,'') FROM jobs
WHERE state='queued' AND admission_paused=0 AND execution_mode=? AND principal_id=?
ORDER BY COALESCE(batch_id,'')""", (mode, owner))]
old_group = self._state(connection, "last_batch_" + mode + "_" + owner)
group = next((p for p in groups if p > old_group), groups[0])
return connection.execute("""SELECT * FROM jobs WHERE state='queued' AND admission_paused=0
AND execution_mode=? AND principal_id=? AND COALESCE(batch_id,'')=?
ORDER BY queue_seq LIMIT 1""", (mode, owner, group)).fetchone()
return None
def peek_next(self, *, now=None):
with self._connection() as connection:
return self._decode(self._select_next(connection, time.time() if now is None else now))
def waiting_summary(self, *, now=None):
now = time.time() if now is None else now
with self._connection() as connection:
count = connection.execute("SELECT COUNT(*) FROM jobs WHERE state='queued'").fetchone()[0]
policy = self._batch_eligibility(connection, now)
return {"queued": count, **policy}
def _batch_eligibility(self, connection, now):
result, watermark, closed = guarded_eligibility(now,
self._state(connection, "clock_max_seen", "0"),
self._state(connection, "closed_window_through", ""))
self._set_state(connection, "clock_max_seen", watermark)
self._set_state(connection, "closed_window_through", closed)
return result
def admission(self, job_id, *, now=None):
with self._connection() as connection:
connection.execute("BEGIN IMMEDIATE")
try:
row = connection.execute("SELECT * FROM jobs WHERE id=?", (job_id,)).fetchone()
if not row or row['cancel_requested']:
result = {"eligible": False, "reason": "cancelled"}
elif row['admission_paused']:
result = {"eligible": False, "reason": "manual_pause"}
elif row['execution_mode'] == 'batch':
result = self._batch_eligibility(connection, time.time() if now is None else now)
else:
result = {"eligible": True, "reason": None}
connection.commit()
return result
except BaseException:
connection.rollback()
raise
def claim_next(self, *, gpu_uuid=None, now=None):
with self._connection() as connection:
connection.execute("BEGIN IMMEDIATE")
try:
if connection.execute("SELECT 1 FROM jobs WHERE state='running' LIMIT 1").fetchone():
connection.commit()
return None
now = time.time() if now is None else now
row = self._select_next(connection, now)
if row is None:
connection.commit()
return None
connection.execute("""UPDATE jobs SET state='running',stage='launching',started_at=?,
updated_at=?,attempt_count=attempt_count+1,gpu_uuid=? WHERE id=?""",
(now, now, gpu_uuid, row["id"]))
self._set_state(connection, "last_principal_" + row["execution_mode"], row["principal_id"])
self._set_state(connection, "last_batch_" + row["execution_mode"] + "_" + row["principal_id"], row["batch_id"] or "")
streak = int(self._state(connection, "interactive_streak", "0"))
self._set_state(connection, "interactive_streak", streak + 1 if row["execution_mode"] == "interactive" else 0)
job = self._decode(connection.execute("SELECT * FROM jobs WHERE id=?", (row["id"],)).fetchone())
connection.commit()
return job
except BaseException:
connection.rollback()
raise
def control(self, job_id, desired_state, *, command_id, expected_execution_id=None, expected_version=None):
if desired_state not in {"run", "pause", "cancel"} or not isinstance(command_id, str) or not 1 <= len(command_id) <= 128:
raise ValueError("Invalid control command")
digest = hashlib.sha256(json.dumps([job_id, desired_state, expected_execution_id, expected_version]).encode()).hexdigest()
with self._connection() as connection:
connection.execute("BEGIN IMMEDIATE")
try:
old = connection.execute("SELECT * FROM control_commands WHERE id=?", (command_id,)).fetchone()
row = connection.execute("SELECT * FROM jobs WHERE id=?", (job_id,)).fetchone()
if row is None:
raise ValueError("Job not found")
if old:
if old["job_id"] != job_id or old["request_hash"] != digest:
raise IdempotencyConflict("Control key already used for a different command")
else:
decoded = self._decode(row)
if expected_execution_id is not None and decoded["execution_id"] != expected_execution_id:
raise IdempotencyConflict("Execution changed")
if expected_version is not None and row["control_version"] != expected_version:
raise IdempotencyConflict("Control version changed")
if row["state"] not in TERMINAL_STATES:
if desired_state == "cancel":
queued = row["state"] == "queued"
connection.execute("""UPDATE jobs SET cancel_requested=1, control_version=control_version+1,
state=?,stage=?,finished_at=?,updated_at=? WHERE id=?""",
("cancelled" if queued else row["state"], "cancelled" if queued else row["stage"],
time.time() if queued else row["finished_at"], time.time(), job_id))
else:
connection.execute("UPDATE jobs SET admission_paused=?,control_version=control_version+1,updated_at=? WHERE id=?",
(int(desired_state == "pause"), time.time(), job_id))
connection.execute("INSERT INTO control_commands(id,job_id,request_hash) VALUES (?,?,?)", (command_id, job_id, digest))
result = self._decode(connection.execute("SELECT * FROM jobs WHERE id=?", (job_id,)).fetchone())
connection.commit()
return result
except BaseException:
connection.rollback()
raise
def defer_unlaunched(self, job_id, attempt_count, reason):
"""A claim crossed the close boundary; no runner may exist yet."""
with self._connection() as connection:
connection.execute("BEGIN IMMEDIATE")
try:
row = connection.execute("SELECT * FROM jobs WHERE id=?", (job_id,)).fetchone()
if not row or row["state"] != "running" or row["runner_pid"] is not None or row["attempt_count"] != attempt_count:
raise RuntimeError("Only the current unlaunched claim may be deferred")
state = "cancelled" if row["cancel_requested"] else "queued"
connection.execute("UPDATE jobs SET state=?,stage=?,started_at=NULL,finished_at=?,updated_at=? WHERE id=?",
(state, "cancelled" if state == "cancelled" else reason,
time.time() if state == "cancelled" else None, time.time(), job_id))
connection.commit()
except BaseException:
connection.rollback()
raise
return self.get(job_id)
def set_runner(self, job_id, pid, start, pgid):
with self._connection() as connection:
count = connection.execute("""UPDATE jobs SET runner_pid=?,runner_start=?,runner_pgid=?,
stage='executing',updated_at=? WHERE id=? AND state='running'""",
(pid, start, pgid, time.time(), job_id)).rowcount
if count != 1:
raise RuntimeError("Job no longer owns the execution slot")
def cancel(self, job_id):
with self._connection() as connection:
now = time.time()
connection.execute("""UPDATE jobs SET cancel_requested=1,
state=CASE WHEN state='queued' THEN 'cancelled' ELSE state END,
stage=CASE WHEN state='queued' THEN 'cancelled' ELSE stage END,
finished_at=CASE WHEN state='queued' THEN ? ELSE finished_at END,
updated_at=? WHERE id=? AND state IN ('queued','running')""", (now, now, job_id))
return self.get(job_id)
def requeue_preempted(self, job_id, reason):
"""Worker-only: call after proving the entire runner process group gone.
Keep queue_seq/id so the interrupted request retains its original place.
A cancellation committed during cleanup wins this transaction.
"""
if not isinstance(reason, str) or not reason.strip():
raise ValueError("Preemption reason is required")
with self._connection() as connection:
connection.execute("BEGIN IMMEDIATE")
try:
row = connection.execute("SELECT state,cancel_requested FROM jobs WHERE id=?", (job_id,)).fetchone()
if row is None or row["state"] != "running":
raise RuntimeError("Only the running attempt may be requeued")
state = "cancelled" if row["cancel_requested"] else "queued"
now = time.time()
connection.execute("""UPDATE jobs SET state=?,stage=?,preemptions=preemptions+1,
last_preempted_at=?,last_preempted_reason=?,updated_at=?,
runner_pid=NULL,runner_start=NULL,runner_pgid=NULL,result_json=NULL,error=NULL,
started_at=CASE WHEN ?='queued' THEN NULL ELSE started_at END,
finished_at=CASE WHEN ?='cancelled' THEN ? ELSE NULL END
WHERE id=? AND state='running'""",
(state, state, now, reason[:2000], now, state, state, now, job_id))
connection.commit()
except BaseException:
connection.rollback()
raise
return self.get(job_id)
def finish(self, job_id, state, *, result=None, error=None):
if state not in TERMINAL_STATES:
raise ValueError("Invalid terminal state")
with self._connection() as connection:
connection.execute("BEGIN IMMEDIATE")
try:
row = connection.execute("SELECT state,cancel_requested FROM jobs WHERE id=?", (job_id,)).fetchone()
if row is None or row["state"] != "running":
raise RuntimeError("Cannot finish a job outside its running attempt")
if row["cancel_requested"]:
state, result, error = "cancelled", None, "Cancellation requested before completion"
now = time.time()
connection.execute("""UPDATE jobs SET state=?,stage=?,result_json=?,error=?,
finished_at=?,updated_at=? WHERE id=? AND state='running'""",
(state, state, json.dumps(result, allow_nan=False) if result is not None else None,
error, now, now, job_id))
connection.commit()
except BaseException:
connection.rollback()
raise
def initialize_store(settings):
settings.workspace_root.mkdir(parents=True, exist_ok=True)
for directory in (settings.app_root, settings.state_dir, settings.jobs_dir, settings.outputs_dir):
confined_path(directory, settings.workspace_root).mkdir(parents=True, exist_ok=True)
confined_path(settings.db_path, settings.workspace_root)
return Store(settings.db_path)