Files
hmandWorkBuddy e2c3d51a58
CloudLab CI/CD / 门禁 doctor (push) Failing after 6m40s
CloudLab CI/CD / 单元测试 (push) Skipped
CloudLab CI/CD / 归档完整性 (push) Skipped
CloudLab CI/CD / 构建站点与归档 (push) Skipped
CloudLab CI/CD / 部署到 lab.hdtime.space(rsync) (push) Skipped
CloudLab CI/CD / 构建镜像并推送 Gitea 容器仓库 (push) Skipped
CloudLab CI/CD / 容器部署到 lab.hdtime.space (push) Skipped
CloudLab CI/CD / 发布版本(Tag) (push) Skipped
feat(obs): 轻量实验观察记录纳入后端受管体系
用户关切:多人实验时数据要有管理机制,不能任意放置。
诊断发现后端已有完整管理(runs/artifacts/项目角色/配额/幂等/溯源/审计),
但各实验室的轻量操作记录走 localStorage,游离在外——这才是「任意放置」的来源。

后端(cloudlab-platform,已部署上线):
- 新增 observations 表:项目归属、操作者、module/title/detail/ref、sha256、时间戳
- 新增 /api/observations GET/POST/DELETE:viewer 可读、runner 可写、本人或 owner 可删
- 全量 audit;独立于 runs(不进 worker 队列、不占配额)
- deploy/update_api.py:带备份+重启+探活的后端部署脚本

前端:
- cl-observations.js:登录检测、后端写入、未登录本地暂存(500)、flush 批量归档
- CL.log 双写:同步写本地保即时性,异步归档到后端带归属
- records.html/records.js:「归档到项目」按钮显示待归档数并支持一键提交
- 12 页面加载新模块;遵守 shell.js 的 window.CL 守卫(用 window.CLObs)

关键调试:CSRF 头必须是 'ide'(server.py require_csrf 硬编码),
Bearer token 无效(认证用 cl_session Cookie,credentials:'same-origin' 自动携带)。

文档 docs/实验数据管理规范.md:两类数据归属、命名规范、何时进后端、审计回滚。

验证:
- tests/test_observations.py 2/2;线上端到端 POST→GET→DELETE→清零(测试数据已清理)
- ui_observations 11/11(未登录暂存/已登录后端写入/项目归属/归档按钮)
- UI 不变量 216/0;其它 UI 测试全绿

Co-Authored-By: WorkBuddy <noreply@workbuddy.ai>
2026-11-23 09:13:35 +08:00

881 lines
39 KiB
Python

#!/usr/bin/env python3
"""CloudLab platform common: paths, SQLite schema, auth helpers, seeding."""
import hashlib
import hmac
import json
import os
import re
import secrets
import sqlite3
import string
from datetime import datetime, timedelta, timezone
from pathlib import Path
VERSION = "3.0.0"
PLATFORM = Path(os.environ.get("CLOUDLAB_PLATFORM", str(Path(__file__).resolve().parent)))
DATA = Path(os.environ.get("CLOUDLAB_DATA", "/data"))
SITE = Path(os.environ.get("CLOUDLAB_SITE", "/opt/cloudlab/site"))
DB_PATH = Path(os.environ.get("CLOUDLAB_DB", str(DATA / "cloudlab.db")))
MAX_UPLOAD = int(os.environ.get("CLOUDLAB_MAX_UPLOAD", str(50 * 1024 * 1024)))
MAX_RUNS = max(1, int(os.environ.get("CLOUDLAB_MAX_RUNS", "2")))
MAX_RUNS_PER_USER = max(1, int(os.environ.get("CLOUDLAB_MAX_RUNS_PER_USER", "2")))
WORKER_HEARTBEAT_PREFIX = "worker:"
WORKER_HEARTBEAT_SUFFIX = ":heartbeat"
WORKER_ONLINE_SECONDS = 20
WORKER_RETENTION_SECONDS = 7 * 24 * 3600
# Batch runs older than this become eligible for normal-priority ordering, so a
# sustained normal backlog cannot starve them forever. 0 disables aging.
QUEUE_AGING_SECONDS = max(0, int(os.environ.get("CLOUDLAB_QUEUE_AGING_SECONDS", "600")))
# Global admission guard for the single SQLite queue. 0 disables the cap.
MAX_QUEUE_RUNS = max(0, int(os.environ.get("CLOUDLAB_MAX_QUEUE_RUNS", "1000")))
QUEUE_RETRY_AFTER = max(1, int(os.environ.get("CLOUDLAB_QUEUE_RETRY_AFTER", "30")))
APP_VERSION = VERSION
ROLE_ORDER = {"viewer": 1, "runner": 2, "editor": 3, "owner": 4}
def now_iso(dt=None):
dt = dt or datetime.now(timezone.utc)
return dt.astimezone(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
def parse_iso(s):
if not s:
return None
try:
return datetime.fromisoformat(s.replace("Z", "+00:00"))
except Exception:
return None
def queue_aging_cutoff(seconds=None):
"""ISO cutoff for batch aging; None means aging is disabled."""
seconds = QUEUE_AGING_SECONDS if seconds is None else max(0, int(seconds))
if seconds <= 0:
return None
return now_iso(datetime.now(timezone.utc) - timedelta(seconds=seconds))
def effective_priority(priority, created_at, cutoff):
"""Scheduling priority after aging; only promotes batch (0) to normal (1)."""
p = 1 if int(priority or 0) > 0 else 0
if p or not cutoff or not created_at:
return p
return 1 if str(created_at) <= str(cutoff) else 0
def json_load(s, default=None):
try:
return json.loads(s) if s else default
except Exception:
return default
def json_dump(obj):
return json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
def canonical_json(obj):
"""Canonical JSON for hashing: sorted keys, no whitespace, UTF-8 text."""
return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
def sha256_bytes(data):
return hashlib.sha256(data).hexdigest()
def sha256_text(text):
return sha256_bytes(str(text).encode("utf-8"))
def sha256_file(path, chunk_size=1024 * 1024):
h = hashlib.sha256()
with open(path, "rb") as fh:
while True:
chunk = fh.read(chunk_size)
if not chunk:
break
h.update(chunk)
return h.hexdigest()
def canonical_sha256(obj):
return sha256_text(canonical_json(obj))
PROVENANCE_SCHEMA = "cloudlab.provenance.v1"
QUALITY_TIERS = ("deterministic", "model", "lookup", "workflow", "heuristic")
VALIDATION_TYPES = ("reference", "numerical", "data", "workflow", "reference-only", "none")
def validate_model_card(card):
"""Validate the research-grade model card attached to an experiment."""
if not isinstance(card, dict):
raise ValueError("modelCard 必须是对象")
for key in ("schema", "tier", "tierLabel", "validated", "validationType", "validationScope",
"biologicalCalibration", "validationCases", "assumptions", "limitations",
"solver", "provenance", "disclaimer"):
if key not in card:
raise ValueError("modelCard 缺少字段: " + key)
if card["schema"] != "cloudlab.modelcard.v1":
raise ValueError("modelCard.schema 必须是 cloudlab.modelcard.v1")
if card["tier"] not in QUALITY_TIERS:
raise ValueError("modelCard.tier 非法: " + str(card["tier"]))
if card["validationType"] not in VALIDATION_TYPES:
raise ValueError("modelCard.validationType 非法: " + str(card["validationType"]))
if not isinstance(card["validated"], bool):
raise ValueError("modelCard.validated 必须是布尔值")
for key in ("validationCases", "assumptions", "limitations", "provenance"):
if not isinstance(card[key], list):
raise ValueError("modelCard." + key + " 必须是数组")
if card["validated"] and not card["validationCases"]:
raise ValueError("已验证的 modelCard 必须至少有一条 validationCases")
if not isinstance(card["solver"], dict):
raise ValueError("modelCard.solver 必须是对象")
if not str(card["validationScope"]).strip() or not str(card["disclaimer"]).strip():
raise ValueError("modelCard.validationScope / disclaimer 不能为空")
return card
def quality_summary(manifest):
"""Small public summary used by list endpoints and the IDE."""
card = (manifest or {}).get("modelCard") or {}
return {
"tier": card.get("tier", "unknown"),
"tierLabel": card.get("tierLabel", "未声明"),
"validated": bool(card.get("validated")),
"validationType": card.get("validationType", "none"),
"validationScope": card.get("validationScope", ""),
"biologicalCalibration": card.get("biologicalCalibration", "unknown"),
"limitations": card.get("limitations", []),
"disclaimer": card.get("disclaimer", ""),
}
def connect():
DATA.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(str(DB_PATH), timeout=30, isolation_level=None)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA foreign_keys=ON")
conn.execute("PRAGMA busy_timeout=30000")
return conn
SCHEMA = """
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user', disabled INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
token_hash TEXT PRIMARY KEY, user_id TEXT NOT NULL, created_at TEXT NOT NULL, expires_at TEXT NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS projects (
id TEXT PRIMARY KEY, name TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL,
max_active_runs INTEGER NOT NULL DEFAULT 10, max_running INTEGER NOT NULL DEFAULT 2
);
CREATE TABLE IF NOT EXISTS project_members (
project_id TEXT NOT NULL, user_id TEXT NOT NULL, role TEXT NOT NULL,
PRIMARY KEY(project_id, user_id),
FOREIGN KEY(project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS experiments (
id TEXT PRIMARY KEY, type TEXT NOT NULL, code TEXT NOT NULL, title TEXT NOT NULL,
version TEXT NOT NULL, manifest TEXT NOT NULL, updated_at TEXT NOT NULL, updated_by TEXT
);
CREATE TABLE IF NOT EXISTS uploads (
id TEXT PRIMARY KEY, user_id TEXT NOT NULL, name TEXT NOT NULL, path TEXT NOT NULL,
size INTEGER NOT NULL, sha256 TEXT NOT NULL, created_at TEXT NOT NULL
);
-- 轻量观察记录:各实验室的「记录元素观察 / 载入数据 / 稀释配制」等操作笔记。
-- 与 runs 分离:不进 worker 队列、不占运行配额,但同样带项目归属、审计与完整性哈希。
CREATE TABLE IF NOT EXISTS observations (
id TEXT PRIMARY KEY, project_id TEXT NOT NULL, user_id TEXT NOT NULL,
module TEXT NOT NULL, title TEXT NOT NULL, detail TEXT NOT NULL DEFAULT '',
ref TEXT NOT NULL DEFAULT '', sha256 TEXT NOT NULL, created_at TEXT NOT NULL,
FOREIGN KEY(project_id) REFERENCES projects(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS runs (
id TEXT PRIMARY KEY, project_id TEXT NOT NULL, experiment_id TEXT NOT NULL,
experiment_version TEXT NOT NULL, user_id TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'queued',
params TEXT NOT NULL DEFAULT '{}', inputs TEXT NOT NULL DEFAULT '{}', manifest TEXT NOT NULL,
provenance TEXT NOT NULL DEFAULT '{}',
note TEXT NOT NULL DEFAULT '', result TEXT, error TEXT, exit_code INTEGER,
cancel_requested INTEGER NOT NULL DEFAULT 0, timeout_sec INTEGER NOT NULL DEFAULT 600,
lease_owner TEXT, lease_expires_at TEXT, attempt INTEGER NOT NULL DEFAULT 0,
idempotency_key TEXT, requeued_from TEXT, reproduced_from TEXT,
priority INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL, started_at TEXT, finished_at TEXT
);
CREATE TABLE IF NOT EXISTS run_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT, run_id TEXT NOT NULL, ts TEXT NOT NULL,
stream TEXT NOT NULL DEFAULT 'stdout', line TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS run_events (
id INTEGER PRIMARY KEY AUTOINCREMENT, run_id TEXT NOT NULL, ts TEXT NOT NULL,
type TEXT NOT NULL, worker_id TEXT, detail TEXT
);
CREATE TABLE IF NOT EXISTS artifacts (
id TEXT PRIMARY KEY, run_id TEXT NOT NULL, name TEXT NOT NULL, path TEXT NOT NULL,
size INTEGER NOT NULL, sha256 TEXT NOT NULL, mime TEXT NOT NULL,
FOREIGN KEY(run_id) REFERENCES runs(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS audit (
id INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT NOT NULL, user_id TEXT, action TEXT NOT NULL,
target TEXT, detail TEXT
);
CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS workers (
id TEXT PRIMARY KEY, hostname TEXT NOT NULL, node TEXT NOT NULL DEFAULT '',
version TEXT NOT NULL DEFAULT '', capacity INTEGER NOT NULL DEFAULT 2,
status TEXT NOT NULL DEFAULT 'online', started_at TEXT, last_seen TEXT NOT NULL,
current_runs INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_runs_project ON runs(project_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_obs_project ON observations(project_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_runs_status ON runs(status);
CREATE INDEX IF NOT EXISTS idx_runs_queue ON runs(status, priority DESC, created_at);
CREATE INDEX IF NOT EXISTS idx_runs_status_project ON runs(status, project_id);
CREATE INDEX IF NOT EXISTS idx_logs_run ON run_logs(run_id, id);
CREATE INDEX IF NOT EXISTS idx_run_events_run ON run_events(run_id, id);
CREATE INDEX IF NOT EXISTS idx_artifacts_run ON artifacts(run_id);
"""
def migrate_db(conn):
"""Additive migrations for databases created before provenance/lease existed."""
cols = {row["name"] for row in conn.execute("PRAGMA table_info(runs)")}
if "provenance" not in cols:
conn.execute("ALTER TABLE runs ADD COLUMN provenance TEXT NOT NULL DEFAULT '{}'")
if "lease_owner" not in cols:
conn.execute("ALTER TABLE runs ADD COLUMN lease_owner TEXT")
if "lease_expires_at" not in cols:
conn.execute("ALTER TABLE runs ADD COLUMN lease_expires_at TEXT")
if "attempt" not in cols:
conn.execute("ALTER TABLE runs ADD COLUMN attempt INTEGER NOT NULL DEFAULT 0")
if "idempotency_key" not in cols:
conn.execute("ALTER TABLE runs ADD COLUMN idempotency_key TEXT")
if "requeued_from" not in cols:
conn.execute("ALTER TABLE runs ADD COLUMN requeued_from TEXT")
if "priority" not in cols:
conn.execute("ALTER TABLE runs ADD COLUMN priority INTEGER NOT NULL DEFAULT 1")
if "reproduced_from" not in cols:
conn.execute("ALTER TABLE runs ADD COLUMN reproduced_from TEXT")
pcols = {row["name"] for row in conn.execute("PRAGMA table_info(projects)")}
if "max_active_runs" not in pcols:
conn.execute("ALTER TABLE projects ADD COLUMN max_active_runs INTEGER NOT NULL DEFAULT 10")
if "max_running" not in pcols:
conn.execute("ALTER TABLE projects ADD COLUMN max_running INTEGER NOT NULL DEFAULT 2")
conn.execute("""CREATE UNIQUE INDEX IF NOT EXISTS idx_runs_idempotency
ON runs(user_id, idempotency_key)
WHERE idempotency_key IS NOT NULL""")
current_cols = {r["name"] for r in conn.execute("PRAGMA table_info(runs)")}
if {"status", "priority", "created_at"} <= current_cols:
conn.execute("CREATE INDEX IF NOT EXISTS idx_runs_queue ON runs(status, priority DESC, created_at)")
if {"status", "project_id"} <= current_cols:
conn.execute("CREATE INDEX IF NOT EXISTS idx_runs_status_project ON runs(status, project_id)")
def init_db():
DATA.mkdir(parents=True, exist_ok=True)
(DATA / "uploads").mkdir(parents=True, exist_ok=True)
(DATA / "runs").mkdir(parents=True, exist_ok=True)
(DATA / "artifacts").mkdir(parents=True, exist_ok=True)
conn = connect()
try:
conn.executescript(SCHEMA)
migrate_db(conn)
finally:
conn.close()
seed_admin()
seed_default_project()
seed_experiments()
def hash_password(password):
salt = secrets.token_hex(16)
digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), 200000).hex()
return "pbkdf2$" + salt + "$" + digest
def verify_password(password, stored):
try:
_, salt, digest = stored.split("$", 2)
got = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), 200000).hex()
return hmac.compare_digest(got, digest)
except Exception:
return False
def token_hash(token):
return hashlib.sha256(token.encode()).hexdigest()
def new_id(prefix):
return prefix + "-" + secrets.token_hex(6)
def seed_admin():
conn = connect()
try:
row = conn.execute("SELECT COUNT(*) AS n FROM users").fetchone()
if row["n"]:
return
password = "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(18))
uid = new_id("u")
conn.execute("INSERT INTO users(id,username,password_hash,role,created_at) VALUES(?,?,?,?,?)",
(uid, "admin", hash_password(password), "admin", now_iso()))
cred = DATA / "initial-admin.txt"
cred.write_text("CloudLab 初始管理员\n用户名: admin\n密码: " + password + "\n请登录后立即修改密码。\n", encoding="utf-8")
try:
os.chmod(cred, 0o600)
except Exception:
pass
print("[seed] created admin; password written to", cred, flush=True)
finally:
conn.close()
def seed_default_project():
conn = connect()
try:
if conn.execute("SELECT COUNT(*) AS n FROM projects").fetchone()["n"]:
return
pid = "proj-default"
conn.execute("INSERT INTO projects(id,name,description,created_at) VALUES(?,?,?,?)",
(pid, "默认实验室", "CloudLab 默认项目", now_iso()))
admin = conn.execute("SELECT id FROM users WHERE role='admin' ORDER BY created_at LIMIT 1").fetchone()
if admin:
conn.execute("INSERT OR IGNORE INTO project_members(project_id,user_id,role) VALUES(?,?,?)",
(pid, admin["id"], "owner"))
finally:
conn.close()
def validate_manifest(m):
if not isinstance(m, dict):
raise ValueError("manifest 必须是对象")
for key in ("id", "type", "code", "title", "op", "runtime", "inputs", "parameters", "outputs"):
if key not in m:
raise ValueError("缺少字段: " + key)
if not re.match(r"^[a-z0-9][a-z0-9-]{1,60}$", str(m["id"])):
raise ValueError("实验 id 只能是小写字母、数字和连字符")
if m["type"] not in ("bio", "chem", "data"):
raise ValueError("实验类型必须是 bio / chem / data")
rt = m["runtime"]
if not isinstance(rt, dict) or not rt.get("image"):
raise ValueError("runtime.image 必填")
for item in m["inputs"]:
if not item.get("id") or not item.get("type"):
raise ValueError("input 需要 id 和 type")
for item in m["parameters"]:
if not item.get("id"):
raise ValueError("parameter 需要 id")
if "modelCard" not in m:
raise ValueError("缺少 modelCard(科研可信度卡)")
validate_model_card(m["modelCard"])
return m
def version_tuple(value):
"""Parse x.y.z into a comparable tuple; unknown parts become 0."""
out = []
for part in str(value or "0").split(".")[:3]:
digits = "".join(ch for ch in part if ch.isdigit())
out.append(int(digits) if digits else 0)
while len(out) < 3:
out.append(0)
return tuple(out)
def seed_experiments():
conn = connect()
try:
for path in sorted((PLATFORM / "experiments").glob("*.json")):
try:
m = json.loads(path.read_text(encoding="utf-8"))
validate_manifest(m)
except Exception as exc:
print("[seed] skip", path.name, exc, flush=True)
continue
existing = conn.execute("SELECT version,manifest FROM experiments WHERE id=?", (m["id"],)).fetchone()
if existing:
old = json_load(existing["manifest"], {}) or {}
file_version = str(m.get("version", "1.0.0"))
db_version = str(existing["version"] or "0.0.0")
if version_tuple(file_version) > version_tuple(db_version):
# A shipped manifest with a higher version is a system upgrade.
# Full replacement is explicit; user edits use PUT and bump
# their own version above the shipped one, so they are kept.
conn.execute("UPDATE experiments SET type=?, code=?, title=?, version=?, manifest=?, updated_at=?, updated_by=? WHERE id=?",
(m["type"], m["code"], m["title"], file_version, json_dump(m), now_iso(), "system:upgrade", m["id"]))
print("[seed] upgraded experiment", m["id"], db_version, "->", file_version, flush=True)
elif m.get("modelCard") and old.get("modelCard") != m["modelCard"]:
# Same version: preserve user edits, merge only the quality card.
old["modelCard"] = m["modelCard"]
conn.execute("UPDATE experiments SET manifest=?,updated_at=? WHERE id=?",
(json_dump(old), now_iso(), m["id"]))
print("[seed] merged model card", m["id"], flush=True)
continue
conn.execute("INSERT INTO experiments(id,type,code,title,version,manifest,updated_at,updated_by) VALUES(?,?,?,?,?,?,?,?)",
(m["id"], m["type"], m["code"], m["title"], str(m.get("version", "1.0.0")),
json_dump(m), now_iso(), "system"))
finally:
conn.close()
def audit(conn, user_id, action, target=None, detail=None):
try:
conn.execute("INSERT INTO audit(ts,user_id,action,target,detail) VALUES(?,?,?,?,?)",
(now_iso(), user_id, action, target, detail))
except Exception:
pass
RUN_TIMELINE_SCHEMA = "cloudlab.run-timeline.v1"
def record_run_event(conn, run_id, event_type, worker_id=None, detail=None):
"""Append one durable lifecycle event. Telemetry must never fail a run."""
try:
conn.execute(
"INSERT INTO run_events(run_id,ts,type,worker_id,detail) VALUES(?,?,?,?,?)",
(run_id, now_iso(), str(event_type), worker_id,
json_dump(detail) if detail is not None else None))
except Exception:
pass
def run_timeline(conn, run_id):
"""Ordered lifecycle ledger for one run; never derives events from logs."""
try:
rows = conn.execute(
"SELECT id,ts,type,worker_id,detail FROM run_events WHERE run_id=? ORDER BY id",
(run_id,)).fetchall()
except sqlite3.OperationalError:
rows = []
events = []
for row in rows:
events.append({
"id": row["id"],
"ts": row["ts"],
"type": row["type"],
"workerId": row["worker_id"],
"detail": json_load(row["detail"], None),
})
return {"schema": RUN_TIMELINE_SCHEMA, "runId": run_id, "count": len(events), "events": events}
def count_active_runs(conn, user_id):
"""Runs that count against a user's admission quota (queued or running)."""
return conn.execute("SELECT COUNT(*) AS n FROM runs WHERE user_id=? AND status IN ('queued','running')",
(user_id,)).fetchone()["n"]
def count_project_active_runs(conn, project_id):
"""Runs that count against a project's active backlog/execution quota."""
return conn.execute("SELECT COUNT(*) AS n FROM runs WHERE project_id=? AND status IN ('queued','running')",
(project_id,)).fetchone()["n"]
def project_usage(conn, project_id):
"""Honest per-project usage: active backlog, running, queued, and recent completed."""
row = conn.execute("""SELECT
SUM(CASE WHEN status IN ('queued','running') THEN 1 ELSE 0 END) AS active,
SUM(CASE WHEN status='running' THEN 1 ELSE 0 END) AS running,
SUM(CASE WHEN status='queued' THEN 1 ELSE 0 END) AS queued
FROM runs WHERE project_id=?""", (project_id,)).fetchone()
return {"active": int(row["active"] or 0), "running": int(row["running"] or 0),
"queued": int(row["queued"] or 0)}
def run_queue_summary(conn, run_id):
"""Queue position for a queued run under the worker's current claim order.
The order is effective priority desc (batch ages to normal after
QUEUE_AGING_SECONDS), then the project with fewer running runs first, then
created_at/rowid. The count is a snapshot: starting a run changes the
running counts and therefore the order. Old/minimal test schemas without
project_id fall back to the previous priority/FIFO estimate.
"""
cols = {r["name"] for r in conn.execute("PRAGMA table_info(runs)")}
tables = {r["name"] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}
has_priority = "priority" in cols
has_project = "project_id" in cols and "projects" in tables
cutoff = queue_aging_cutoff() if has_priority else None
project_expr = ("(SELECT COUNT(*) FROM runs x WHERE x.project_id=r.project_id AND x.status='running') AS project_running"
if has_project else "0 AS project_running")
rows = conn.execute("SELECT r.rowid AS seq,r.id,r.created_at,"
+ ("COALESCE(r.priority,1)" if has_priority else "1")
+ " AS priority," + project_expr
+ " FROM runs r WHERE r.status='queued'").fetchall()
target = next((r for r in rows if r["id"] == run_id), None)
if not target:
return None
def key(row):
return (-effective_priority(row["priority"], row["created_at"], cutoff),
int(row["project_running"] or 0), row["created_at"] or "", row["seq"])
target_key = key(target)
pos = sum(1 for row in rows if key(row) <= target_key)
return {"position": pos, "ahead": max(0, pos - 1), "total": len(rows)}
def find_idempotent_run(conn, user_id, key):
"""Look up a run submitted earlier with the same user-scoped idempotency key."""
if not key:
return None
return conn.execute("SELECT * FROM runs WHERE user_id=? AND idempotency_key=?",
(user_id, key)).fetchone()
def idempotent_payload_matches(row, project_id, experiment_id, params, inputs, priority=None):
"""True only when the replayed key refers to the same normalized request."""
if not row:
return False
if priority is not None and int(row["priority"] if "priority" in row.keys() else 1) != int(priority):
return False
return (row["project_id"] == project_id and row["experiment_id"] == experiment_id
and canonical_json(json_load(row["params"], {})) == canonical_json(params)
and canonical_json(json_load(row["inputs"], {})) == canonical_json(inputs))
def average_runtime_seconds(conn, limit=20):
"""Mean wall-clock seconds of recent successful runs, or None without history."""
rows = conn.execute("""SELECT started_at,finished_at FROM runs
WHERE status='succeeded' AND started_at IS NOT NULL AND finished_at IS NOT NULL
ORDER BY finished_at DESC LIMIT ?""", (limit,)).fetchall()
values = []
for row in rows:
started, finished = parse_iso(row["started_at"]), parse_iso(row["finished_at"])
if started and finished and finished >= started:
values.append((finished - started).total_seconds())
return round(sum(values) / len(values), 3) if values else None
def _table_exists(conn, name):
"""True when a table exists; tests use reduced in-memory schemas."""
try:
conn.execute("SELECT 1 FROM " + name + " LIMIT 1")
return True
except sqlite3.OperationalError:
return False
def _age_seconds(value, now=None):
ts = parse_iso(value)
if not ts:
return None
now = now or datetime.now(timezone.utc)
return max(0, int((now - ts).total_seconds()))
def prune_workers(conn, keep_seconds=WORKER_RETENTION_SECONDS):
"""Drop long-dead registry rows so a recreated container id cannot grow the table forever."""
cutoff = now_iso(datetime.now(timezone.utc) - timedelta(seconds=keep_seconds))
cur = conn.execute("DELETE FROM workers WHERE last_seen < ?", (cutoff,))
return cur.rowcount
def register_worker(conn, worker_id, hostname, node, version, capacity=MAX_RUNS):
"""Register or refresh one worker process.
A restart preserves an operator-requested drain: the node stays out of the
claim pool until the admin explicitly resumes it. An offline row becomes
online again when its worker comes back.
"""
now = now_iso()
prune_workers(conn)
row = conn.execute("SELECT status FROM workers WHERE id=?", (worker_id,)).fetchone()
status = "draining" if row and row["status"] == "draining" else "online"
conn.execute("""INSERT INTO workers(id,hostname,node,version,capacity,status,started_at,last_seen,current_runs)
VALUES(?,?,?,?,?,?,?,?,0)
ON CONFLICT(id) DO UPDATE SET
hostname=excluded.hostname, node=excluded.node, version=excluded.version,
capacity=excluded.capacity, status=excluded.status,
started_at=excluded.started_at, last_seen=excluded.last_seen""",
(worker_id, hostname, node, version, int(capacity), status, now, now))
return status
def heartbeat_worker(conn, worker_id, current_runs=0):
"""Refresh liveness without overriding a drain decision."""
conn.execute("UPDATE workers SET last_seen=?,current_runs=? WHERE id=?",
(now_iso(), max(0, int(current_runs)), worker_id))
def mark_worker_offline(conn, worker_id):
"""Record a graceful worker shutdown; does not touch its active runs."""
conn.execute("UPDATE workers SET status='offline',current_runs=0,last_seen=? WHERE id=?",
(now_iso(), worker_id))
def worker_is_draining(conn, worker_id):
if not _table_exists(conn, "workers"):
return False
row = conn.execute("SELECT status FROM workers WHERE id=?", (worker_id,)).fetchone()
return bool(row and row["status"] == "draining")
def set_worker_status(conn, worker_id, status):
"""Admin drain/resume. Returns False when the worker is not registered."""
if status not in ("online", "draining"):
raise ValueError("worker status must be online or draining")
cur = conn.execute("UPDATE workers SET status=?,last_seen=? WHERE id=?",
(status, now_iso(), worker_id))
return cur.rowcount > 0
def worker_details(conn, window=WORKER_ONLINE_SECONDS):
"""Worker registry view merged with legacy settings heartbeats.
Liveness is derived from last_seen; currentRuns is counted from actual
running leases, not trusted from a heartbeat field. A draining worker is
still online but reports claiming=false.
"""
now = datetime.now(timezone.utc)
out = []
known = set()
if _table_exists(conn, "workers"):
rows = conn.execute("SELECT * FROM workers ORDER BY id").fetchall()
for row in rows:
known.add(row["id"])
last = parse_iso(row["last_seen"])
online = bool(last and (now - last).total_seconds() < window)
status = row["status"] if online else "offline"
if status not in ("online", "draining"):
status = "offline"
runs = conn.execute("""SELECT id,experiment_id,experiment_version,started_at,status
FROM runs WHERE lease_owner=? AND status='running' ORDER BY started_at LIMIT 10""",
(row["id"],)).fetchall()
out.append({
"id": row["id"],
"hostname": row["hostname"],
"node": row["node"],
"version": row["version"],
"capacity": int(row["capacity"] or MAX_RUNS),
"status": status,
"online": online,
"claiming": online and status == "online",
"startedAt": row["started_at"],
"lastSeen": row["last_seen"],
"currentRuns": len(runs),
"runs": [{"id": r["id"], "experimentId": r["experiment_id"],
"experimentVersion": r["experiment_version"], "startedAt": r["started_at"]} for r in runs],
"legacy": False,
})
# Compatibility with the pre-registry heartbeat rows used by old workers
# and by the reduced test schema.
try:
rows = conn.execute("SELECT key,value FROM settings WHERE key LIKE ?",
(WORKER_HEARTBEAT_PREFIX + "%" + WORKER_HEARTBEAT_SUFFIX,)).fetchall()
except sqlite3.OperationalError:
rows = []
for row in rows:
ts = parse_iso(row["value"])
if not ts or (now - ts).total_seconds() >= window:
continue
wid = row["key"][len(WORKER_HEARTBEAT_PREFIX):-len(WORKER_HEARTBEAT_SUFFIX)]
if not wid or wid in known:
continue
known.add(wid)
out.append({
"id": wid, "hostname": wid.split(":")[0], "node": "legacy", "version": "",
"capacity": MAX_RUNS, "status": "online", "online": True, "claiming": True,
"startedAt": None, "lastSeen": row["value"], "currentRuns": 0, "runs": [],
"legacy": True,
})
if not out:
legacy = parse_iso(get_setting(conn, "worker_heartbeat"))
if legacy and (now - legacy).total_seconds() < window:
wid = get_setting(conn, "worker_id") or "legacy"
out.append({
"id": wid, "hostname": wid.split(":")[0], "node": "legacy", "version": "",
"capacity": MAX_RUNS, "status": "online", "online": True, "claiming": True,
"startedAt": None, "lastSeen": get_setting(conn, "worker_heartbeat"),
"currentRuns": 0, "runs": [], "legacy": True,
})
out.sort(key=lambda w: (not w["online"], w["status"] != "online", w["id"]))
return out
def worker_status(conn, window=WORKER_ONLINE_SECONDS):
"""Live worker ids from the registry, with legacy heartbeat compatibility."""
live = [w["id"] for w in worker_details(conn, window) if w["online"]]
live = sorted(set(live))
return {"online": bool(live), "count": len(live), "workers": live}
def queue_admission(conn, limit=None):
"""Return the global queue admission state.
The limit is a load-shedding guard, not a distributed queue. When the
queued count reaches the cap, the API rejects new work instead of letting
the SQLite backlog grow without bound. limit=0 disables the cap.
"""
limit = MAX_QUEUE_RUNS if limit is None else max(0, int(limit))
queued = conn.execute("SELECT COUNT(*) AS n FROM runs WHERE status='queued'").fetchone()["n"]
full = bool(limit and queued >= limit)
return {"queued": int(queued), "limit": int(limit), "full": full,
"accepting": not full,
"retryAfterSeconds": QUEUE_RETRY_AFTER if full else 0}
def queue_snapshot(conn, window=WORKER_ONLINE_SECONDS):
"""Queue shape for operators: counts, age and per-project/priority pressure.
This is a view of the single SQLite queue, not a distributed scheduler.
agedQueued counts batch runs that have already crossed the aging cutoff and
therefore sort as normal.
"""
now = datetime.now(timezone.utc)
aging_cutoff = queue_aging_cutoff()
rows = conn.execute("""SELECT r.id,r.status,r.priority,r.created_at,r.project_id,
COALESCE(p.name,r.project_id) AS project_name,
COALESCE(p.max_active_runs,10) AS max_active_runs,
COALESCE(p.max_running,2) AS max_running
FROM runs r LEFT JOIN projects p ON p.id=r.project_id
WHERE r.status IN ('queued','running')""").fetchall()
queued = running = aged_queued = 0
oldest = None
by_priority = {"normal": {"queued": 0, "oldestSeconds": None},
"batch": {"queued": 0, "oldestSeconds": None}}
projects = {}
for row in rows:
age = _age_seconds(row["created_at"], now)
is_queued = row["status"] == "queued"
if is_queued:
queued += 1
if oldest is None or age is not None and age > oldest["seconds"]:
oldest = {"id": row["id"], "seconds": age}
key = "batch" if int(row["priority"] or 0) <= 0 else "normal"
by_priority[key]["queued"] += 1
if key == "batch" and effective_priority(row["priority"], row["created_at"], aging_cutoff) > 0:
aged_queued += 1
if by_priority[key]["oldestSeconds"] is None or age is not None and age > by_priority[key]["oldestSeconds"]:
by_priority[key]["oldestSeconds"] = age
else:
running += 1
key = row["project_id"] or ""
item = projects.setdefault(key, {
"projectId": key, "projectName": row["project_name"],
"queued": 0, "running": 0, "maxActiveRuns": int(row["max_active_runs"] or 10),
"maxRunning": int(row["max_running"] or 2),
})
if is_queued:
item["queued"] += 1
else:
item["running"] += 1
project_rows = sorted(projects.values(), key=lambda p: (-p["queued"], -p["running"], p["projectId"]))
worker = worker_status(conn, window)
admission = queue_admission(conn)
return {
"queued": queued, "running": running,
"queueLimit": admission["limit"], "queueFull": admission["full"],
"acceptingRuns": admission["accepting"], "retryAfterSeconds": admission["retryAfterSeconds"],
"oldestQueuedSeconds": oldest["seconds"] if oldest else None,
"oldestQueuedRunId": oldest["id"] if oldest else None,
"byPriority": by_priority,
"byProject": project_rows,
"workerOnline": worker["online"], "workerCount": worker["count"],
"agingSeconds": QUEUE_AGING_SECONDS,
"agedQueued": aged_queued,
"policy": (("priority desc (batch ages to normal after %ss), least-running project, created_at asc"
% QUEUE_AGING_SECONDS) if QUEUE_AGING_SECONDS > 0
else "priority desc, least-running project, created_at asc"),
"time": now_iso(),
}
def capacity_snapshot(conn, user_id):
"""Honest capacity view: counts, per-user remaining quota, and a rough wait estimate."""
active = conn.execute("SELECT COUNT(*) AS n FROM runs WHERE status='running'").fetchone()["n"]
queued = conn.execute("SELECT COUNT(*) AS n FROM runs WHERE status='queued'").fetchone()["n"]
worker = worker_status(conn)
online = worker["online"]
avg = average_runtime_seconds(conn)
available = max(0, MAX_RUNS - active)
estimate = None
if online and avg is not None:
if active < MAX_RUNS:
slots = MAX_RUNS - active
# A new run joins behind every queued run. It starts after this many full waves.
waves = max(0, -(-(queued + 1) // slots) - 1)
else:
# No free slot: first wait for one running wave, then process queue waves.
waves = -(-(queued + 1) // MAX_RUNS)
estimate = int(round(waves * avg))
user_active = count_active_runs(conn, user_id)
user_queued = conn.execute("SELECT COUNT(*) AS n FROM runs WHERE user_id=? AND status='queued'",
(user_id,)).fetchone()["n"]
has_priority = "priority" in {r["name"] for r in conn.execute("PRAGMA table_info(runs)")}
order = "priority DESC, created_at,rowid" if has_priority else "created_at,rowid"
queued_rows = conn.execute("SELECT id FROM runs WHERE user_id=? AND status='queued' ORDER BY " + order,
(user_id,)).fetchall()
queued_runs = []
for row in queued_rows:
q = run_queue_summary(conn, row["id"])
if q:
queued_runs.append({"id": row["id"], **q})
if not online:
basis = "worker 离线,无法估算开始时间"
elif avg is None:
basis = "成功运行历史不足,无法估算开始时间"
else:
basis = "按最近 20 次成功运行的平均耗时估算,不保证开始时间"
admission = queue_admission(conn)
return {
"capacity": MAX_RUNS,
"active": active,
"queued": queued,
"queueLimit": admission["limit"],
"queueFull": admission["full"],
"acceptingRuns": admission["accepting"],
"retryAfterSeconds": admission["retryAfterSeconds"],
"availableSlots": available,
"perUserLimit": MAX_RUNS_PER_USER,
"user": {
"active": user_active,
"queued": user_queued,
"remaining": max(0, MAX_RUNS_PER_USER - user_active),
"canSubmit": user_active < MAX_RUNS_PER_USER,
},
"workerOnline": online,
"workerCount": worker["count"],
"workers": worker["workers"],
"averageRuntimeSeconds": avg,
"estimatedWaitSeconds": estimate,
"estimateBasis": basis,
"queuedRuns": queued_runs,
"time": now_iso(),
}
def set_setting(conn, key, value):
conn.execute("INSERT INTO settings(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
(key, str(value)))
def get_setting(conn, key, default=None):
row = conn.execute("SELECT value FROM settings WHERE key=?", (key,)).fetchone()
return row["value"] if row else default
def safe_site_path(rel):
"""Resolve a relative path under SITE, rejecting traversal and absolute paths."""
rel = str(rel or "").replace("\\", "/").strip()
if not rel or rel.startswith("/") or "\x00" in rel:
raise ValueError("非法路径")
parts = [p for p in rel.split("/") if p not in ("", ".")]
if any(p == ".." for p in parts):
raise ValueError("非法路径")
p = (SITE / Path(*parts)).resolve()
root = SITE.resolve()
if root not in p.parents and p != root:
raise ValueError("路径越界")
if not p.is_file():
raise ValueError("文件不存在: " + rel)
return p