"""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, field import hashlib import json import math import os from pathlib import Path, PurePosixPath import sqlite3 import stat import time import uuid from .scheduling import normalize_scheduling, guarded_eligibility, eligibility from .reference_profiles import DEFAULT_PROFILE, get_profile from .dialogue import KEYS as DIALOGUE_TASKS TASK_TYPES = frozenset({*DIALOGUE_TASKS, "image.generate", "image.reference.generate", "video.generate", "video.people.analyze", "video.replace", "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 runtime_policy_file: Path | None = None max_gpu_jobs: int = 4 cpu_threads_per_job: int = 2 memory_headroom_gib: float = 16 reference_generation_enabled: bool = False # 仅供受认证API访问的运维PoC;允许提交但不宣称产品能力可用。 reference_generation_poc_enabled: bool = False reference_generation_profile: str = DEFAULT_PROFILE video_edit_enabled: bool = False video_edit_poc_enabled: bool = False video_edit_profile: str = "wan-animate-replace-v1" video_edit_max_seconds: int = 120 video_edit_max_people: int = 12 video_edit_max_pixels: int = 399360 video_edit_python: str = "/workspace/envs/wan-animate/bin/python" video_generation_v2_enabled: bool = False video_generation_enabled: bool = False video_generation_poc_enabled: bool = False video_generation_python: str = '/workspace/envs/fl2va/bin/python' reference_max_images: int = 3 memory_estimates_gib: dict = field(default_factory=lambda: { "image.generate": 88, "image.reference.generate": 112, "video.generate": 64, "defect.generate": 24, "audio.transcribe": 12}) video_generation_tp2_enabled: bool = False video_generation_tp2_poc_enabled: bool = False video_generation_tp2_python: str = '/workspace/envs/fl2va-tp2/bin/python' # 旧部署保持288;只有受控配置显式设置时才降低TP2预留。 video_generation_tp2_memory_gib: float = 288 # 原生音视频必须独立认证,旧静音开关不会启用新能力。 native_dialogue_enabled: bool = False native_dialogue_tp2_enabled: bool = False def __post_init__(self): self.workspace_root = Path(self.workspace_root).resolve() self.app_root = Path(self.app_root).resolve() if type(self.native_dialogue_enabled) is not bool or type(self.native_dialogue_tp2_enabled) is not bool: raise ValueError('Native audio/video certification switches must be booleans') if any(type(v) is not bool for v in (self.video_generation_tp2_enabled, self.video_generation_tp2_poc_enabled)): raise ValueError('TP2 certification switches must be booleans') if not (PurePosixPath(self.video_generation_tp2_python).is_absolute() or Path(self.video_generation_tp2_python).is_absolute()): raise ValueError('TP2 Python requires an absolute path') value = self.video_generation_tp2_memory_gib if (isinstance(value, bool) or not isinstance(value, (float, int)) or not math.isfinite(value) or value < 144): raise ValueError('TP2 memory reservation must be finite and at least 144 GiB') if type(self.video_generation_v2_enabled) is not bool or type(self.video_generation_enabled) is not bool or type(self.video_generation_poc_enabled) is not bool: raise ValueError('Video generation certification switches must be booleans') if not (PurePosixPath(self.video_generation_python).is_absolute() or Path(self.video_generation_python).is_absolute()): raise ValueError('Video generation Python requires an absolute path') self.runtime_policy_file = Path(self.runtime_policy_file or self.app_root / "config" / "runtime-policy.json").resolve() try: self.app_root.relative_to(self.workspace_root) self.runtime_policy_file.relative_to(self.workspace_root) except ValueError as exc: raise ValueError("APP_ROOT must be below WORKSPACE_ROOT") from exc for name, maximum in (("max_gpu_jobs", 4), ("cpu_threads_per_job", 64)): value = getattr(self, name) if type(value) is not int or not 1 <= value <= maximum: raise ValueError(name + " must be a positive bounded integer") from .video_edit.profiles import validate_settings validate_settings(self) profile = get_profile(self.reference_generation_profile) if (type(self.reference_max_images) is not int or not 1 <= self.reference_max_images <= profile.max_images): raise ValueError("reference_max_images exceeds the explicit model profile") if type(self.reference_generation_enabled) is not bool or type(self.reference_generation_poc_enabled) is not bool: raise ValueError("reference certification and PoC switches must be booleans") # 兼容旧四任务settings.json,同时为新任务保留独立保守预算。 if isinstance(self.memory_estimates_gib, dict): self.memory_estimates_gib = dict(self.memory_estimates_gib) self.memory_estimates_gib.setdefault("image.reference.generate", profile.memory_gib) for task in DIALOGUE_TASKS: self.memory_estimates_gib[task] = max(self.memory_estimates_gib.get(task, 0), 32) self.memory_estimates_gib.setdefault("video.people.analyze", 32) self.memory_estimates_gib.setdefault("video.replace", 160) if not isinstance(self.memory_estimates_gib, dict) or set(self.memory_estimates_gib) != TASK_TYPES: raise ValueError("memory_estimates_gib must cover every task type") for value in [self.memory_headroom_gib, *self.memory_estimates_gib.values()]: if isinstance(value, bool) or not isinstance(value, (float, int)) or not math.isfinite(value) or value <= 0: raise ValueError("Memory reservations must be positive finite GiB") self.memory_estimates_gib["image.reference.generate"] = max( self.memory_estimates_gib["image.reference.generate"], profile.memory_gib) self.memory_estimates_gib["video.people.analyze"] = max(self.memory_estimates_gib["video.people.analyze"], 32) self.memory_estimates_gib["video.replace"] = max(self.memory_estimates_gib["video.replace"], 160) tp2_allowed = self.video_generation_tp2_enabled or self.video_generation_tp2_poc_enabled or self.native_dialogue_tp2_enabled if tp2_allowed and self.memory_headroom_gib < 16: raise ValueError("TP2 requires at least 16 GiB host memory headroom") if tp2_allowed or self.native_dialogue_enabled or self.video_generation_v2_enabled or self.video_generation_enabled or self.video_generation_poc_enabled: self.memory_estimates_gib['video.generate'] = max(self.memory_estimates_gib['video.generate'], 288) 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" @property def runner_markers(self): return self.state_dir / "active-runners" def active_markers(self): return ([self.runner_marker] if self.runner_marker.exists() or self.runner_marker.is_symlink() else []) + ( list(self.runner_markers.iterdir()) if self.runner_markers.exists() else []) @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)), max_gpu_jobs=data.get("max_gpu_jobs", 4), cpu_threads_per_job=data.get("cpu_threads_per_job", 2), memory_headroom_gib=data.get("memory_headroom_gib", 16), reference_generation_enabled=data.get("reference_generation_enabled", False), reference_generation_poc_enabled=data.get("reference_generation_poc_enabled", False), reference_generation_profile=data.get("reference_generation_profile", DEFAULT_PROFILE), video_generation_v2_enabled=data.get('video_generation_v2_enabled', False), video_generation_enabled=data.get('video_generation_enabled', False), video_generation_poc_enabled=data.get('video_generation_poc_enabled', False), video_generation_python=data.get('video_generation_python', '/workspace/envs/fl2va/bin/python'), native_dialogue_enabled=data.get('native_dialogue_enabled', False), native_dialogue_tp2_enabled=data.get('native_dialogue_tp2_enabled', False), **{name: data.get(name, getattr(cls, name)) for name in ("video_generation_tp2_enabled", "video_generation_tp2_poc_enabled", "video_generation_tp2_python", "video_generation_tp2_memory_gib", "video_edit_enabled", "video_edit_poc_enabled", "video_edit_profile", "video_edit_max_seconds", "video_edit_max_people", "video_edit_max_pixels", "video_edit_python")}, reference_max_images=data.get("reference_max_images", 3), memory_estimates_gib=data.get("memory_estimates_gib", { "image.generate": 88, "video.generate": 64, "defect.generate": 24, "audio.transcribe": 12}), 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), runtime_policy_file=os.environ.get("RUNTIME_POLICY_FILE") or None) 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) if task_type == 'video.generate': from .video_profiles import H3_PROFILES, LEGACY_PROFILE, normalize_h3 profile = parameters.get('profile') if profile not in (None, *H3_PROFILES, LEGACY_PROFILE): raise ValueError('Unknown video generation profile') if profile in H3_PROFILES: # 仅验证,不把新默认值写进原包;同键重试的hash必须保持一致。 normalize_h3(result[0], result[1], workspace) if task_type in {*DIALOGUE_TASKS, "image.reference.generate", "video.people.analyze", "video.replace"}: # 与实际runner使用同一严格多图协议,避免队列持久化无法执行的请求。 from .runner import validate_request as validate_runner_request normalized = validate_runner_request({"task_type": task_type, "input": result[0], "parameters": result[1], "output_dir": str(Path(workspace).resolve() / "outputs" / "validation")}, workspace=Path(workspace)) result = normalized["input"], normalized["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, *, policy_file=None): self.path = Path(path) self.policy_file = Path(policy_file) if policy_file is not None else None 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); """) # API and worker may initialize together. Serialize schema changes # and inspect columns again while holding the migration transaction. connection.execute("BEGIN IMMEDIATE") try: version = connection.execute("PRAGMA user_version").fetchone()[0] if version > 3: raise RuntimeError("Unsupported queue schema version") 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.execute("DROP INDEX IF EXISTS one_running_job") # A table with the legacy index name makes old binaries fail explicitly # before they can recreate the singleton constraint, even with zero jobs. connection.execute("CREATE TABLE IF NOT EXISTS one_running_job (schema_version INTEGER NOT NULL CHECK(schema_version=2))") connection.execute("CREATE UNIQUE INDEX IF NOT EXISTS one_running_gpu ON jobs(lower(COALESCE(gpu_uuid,'legacy-unbound'))) WHERE state='running'") if version < 3: connection.execute("""CREATE TABLE gpu_lease_members ( gpu_uuid TEXT COLLATE NOCASE PRIMARY KEY NOT NULL, job_id TEXT NOT NULL REFERENCES jobs(id), attempt_count INTEGER NOT NULL, rank INTEGER NOT NULL CHECK(rank IN (0,1)), UNIQUE(job_id,attempt_count,rank))""") connection.execute("""INSERT INTO gpu_lease_members SELECT gpu_uuid,id,attempt_count,0 FROM jobs WHERE state='running' AND gpu_uuid IS NOT NULL""") connection.execute("PRAGMA user_version=3") 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, connection=None): if row is None: return None job = dict(row) job["gpu_uuids"] = [job["gpu_uuid"]] if job["gpu_uuid"] else [] if job["state"] == "running" and connection is not None: job["gpu_uuids"] = [member[0] for member in connection.execute( "SELECT gpu_uuid FROM gpu_lease_members WHERE job_id=? AND attempt_count=? ORDER BY rank", (job["id"], job["attempt_count"]))] 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 dialogue_submission_key(self,job_id): # 供worker核验短期小样授权,幂等键不暴露在HTTP快照中。 with self._connection() as connection: row=connection.execute("SELECT idempotency_key FROM jobs WHERE id=?", (job_id,)).fetchone() return row[0] if row else None def submit(self, task_type, inputs, parameters, timeout_seconds=3600, *, idempotency_key=None, scheduling=None, recover_only=False): 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") job = self._decode(row, connection) connection.commit() return job # 恢复与创建共用同一完整fingerprint和事务;只读返回已有任务,绝不插入新任务。 if recover_only: connection.commit() return None 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: connection.execute("BEGIN") return self._decode(connection.execute("SELECT * FROM jobs WHERE id=?", (job_id,)).fetchone(), connection) def active_gpu_uuids(self): with self._connection() as connection: return {row[0] for row in connection.execute("SELECT gpu_uuid FROM gpu_lease_members")} def running(self): with self._connection() as connection: connection.execute("BEGIN") return [self._decode(row, connection) 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, is_eligible=None): rows = connection.execute("""SELECT * FROM jobs WHERE state='queued' AND admission_paused=0 AND cancel_requested=0 ORDER BY queue_seq""") # 仅在已满足窗口/手动控制的任务中按原queue_seq选择;被暂时关闭的 # 模型保留位置与固定参数,但不能堵住后续仍可运行的旧模型任务。 for row in rows: if self._job_eligibility(connection, row, now)["eligible"] and ( is_eligible is None or is_eligible(self._decode(row))): return row return None def peek_next(self, *, now=None, is_eligible=None): with self._connection() as connection: # 选队也会持久化clock证据;先取得写事务,避免WAL读快照在 # monitor/API并发提交后无法升级为写事务而中断dispatcher。 connection.execute("BEGIN IMMEDIATE") try: job = self._decode(self._select_next(connection, time.time() if now is None else now, is_eligible)) connection.commit() return job except BaseException: connection.rollback() raise def waiting_summary(self, *, now=None): now = time.time() if now is None else now with self._connection() as connection: connection.execute("BEGIN IMMEDIATE") try: count = connection.execute("SELECT COUNT(*) FROM jobs WHERE state='queued'").fetchone()[0] policy = None for row in connection.execute("SELECT * FROM jobs WHERE state='queued' ORDER BY queue_seq"): current = self._job_eligibility(connection, row, now) if policy is None or current["eligible"]: policy = current if current["eligible"]: break if policy is None: # 空队列的状态展示不能替全天任务推进共享clock水位。 policy = eligibility("batch", now, policy_file=self.policy_file) connection.commit() except BaseException: connection.rollback() raise return {"queued": count, **policy} def _job_eligibility(self, connection, row, now): scheduling = json.loads(row["scheduling_json"]) if row["scheduling_json"] is not None else {} return self._batch_eligibility(connection, now, gpu_window_enabled=scheduling.get("gpu_window_enabled")) def _batch_eligibility(self, connection, now, *, gpu_window_enabled=None): max_seen = self._state(connection, "clock_max_seen", "0") closed_through = self._state(connection, "closed_window_through", "") result, watermark, closed = guarded_eligibility(now, max_seen, closed_through, policy_file=self.policy_file, gpu_window_enabled=gpu_window_enabled) # 显式全天任务不推进或清除共享clock证据,生产任务仍继承回拨保护。 if watermark != max_seen: self._set_state(connection, "clock_max_seen", watermark) if closed != closed_through: 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"} else: result = self._job_eligibility(connection, row, time.time() if now is None else now) connection.commit() return result except BaseException: connection.rollback() raise def claim_next(self, *, gpu_uuid=None, gpu_uuids=None, now=None, max_gpu_jobs=4, expected_job_id=None, is_eligible=None): if gpu_uuids is None: members = [] if gpu_uuid is None else [gpu_uuid] else: if not isinstance(gpu_uuids, (list, tuple)) or len(gpu_uuids) not in (1, 2): raise ValueError("A GPU lease must name one or two members") members = list(gpu_uuids) if any(not isinstance(m, str) or not m.strip() or m != m.strip() or "," in m for m in members): raise ValueError("Invalid GPU lease member") if len({m.lower() for m in members}) != len(members): raise ValueError("GPU lease members must be distinct") if gpu_uuids is not None and gpu_uuid is not None and ( not isinstance(gpu_uuid, str) or gpu_uuid.lower() != members[0].lower()): raise ValueError("Primary GPU must equal rank zero") gpu_uuid = members[0] if members else None with self._connection() as connection: connection.execute("BEGIN IMMEDIATE") try: if (connection.execute("SELECT COUNT(*) FROM jobs WHERE state='running'").fetchone()[0] >= max_gpu_jobs or connection.execute("SELECT 1 FROM jobs WHERE state='running' AND lower(COALESCE(gpu_uuid,'legacy-unbound'))=lower(?)", (gpu_uuid or 'legacy-unbound',)).fetchone()): connection.commit() return None if any(connection.execute("SELECT 1 FROM gpu_lease_members WHERE gpu_uuid=?", (member,)).fetchone() for member in members): connection.commit() return None now = time.time() if now is None else now row = self._select_next(connection, now, is_eligible) if row is None or (expected_job_id is not None and row["id"] != expected_job_id): connection.commit() return None connection.execute("""UPDATE jobs SET state='running',stage='launching',started_at=?, updated_at=?,attempt_count=attempt_count+1,gpu_uuid=?,runner_pid=NULL,runner_start=NULL,runner_pgid=NULL WHERE id=?""", (now, now, gpu_uuid, row["id"])) connection.executemany("""INSERT INTO gpu_lease_members(gpu_uuid,job_id,attempt_count,rank) VALUES(?,?,?,?)""", [(member, row["id"], row["attempt_count"] + 1, rank) for rank, member in enumerate(members)]) 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) 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, connection) 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) 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.execute("DELETE FROM gpu_lease_members WHERE job_id=? AND attempt_count=?", (job_id, row['attempt_count'])) connection.commit() except BaseException: connection.rollback() raise return self.get(job_id) def set_runner(self, job_id, pid, start, pgid, *, attempt_count=None): 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' AND ((? IS NULL AND attempt_count=1) OR attempt_count=?)""", (pid, start, pgid, time.time(), job_id, attempt_count, attempt_count)).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, *, attempt_count=None): """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,attempt_count FROM jobs WHERE id=?", (job_id,)).fetchone() if row is None or row["state"] != "running" or (row["attempt_count"] != (1 if attempt_count is None else attempt_count)): 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.execute("DELETE FROM gpu_lease_members WHERE job_id=? AND attempt_count=?", (job_id, row['attempt_count'])) connection.commit() except BaseException: connection.rollback() raise return self.get(job_id) def finish(self, job_id, state, *, result=None, error=None, attempt_count=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,attempt_count FROM jobs WHERE id=?", (job_id,)).fetchone() if row is None or row["state"] != "running" or (row["attempt_count"] != (1 if attempt_count is None else attempt_count)): 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.execute("DELETE FROM gpu_lease_members WHERE job_id=? AND attempt_count=?", (job_id, row['attempt_count'])) 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, settings.runner_markers): 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, policy_file=settings.runtime_policy_file)