Files
CloudLab Deploy 4c312cac39
CloudLab CI/CD / 门禁 doctor (push) Failing after 38s
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(platform): add CloudLab execution platform and IDE web source
Freeze the real-execution control plane, runner, manifests, validation cases and tests under cloudlab-platform; preserve the IDE/static web source under cloudlab-web. Generated material library and runtime state are intentionally excluded.
2026-11-18 00:14:35 +08:00

158 lines
8.1 KiB
Python

#!/usr/bin/env python3
"""Worker registry, drain/resume and queue snapshot regression tests."""
import json
import sqlite3
import sys
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
import common # noqa: E402
import worker # noqa: E402
def dumps(value):
return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
class WorkerRegistryTests(unittest.TestCase):
def setUp(self):
self.conn = sqlite3.connect(":memory:", isolation_level=None)
self.conn.row_factory = sqlite3.Row
self.conn.executescript(common.SCHEMA)
common.migrate_db(self.conn)
self.conn.execute("INSERT INTO users(id,username,password_hash,role,created_at) VALUES(?,?,?,?,?)",
("u1", "tester", "x", "user", "2026-11-12T07:00:00Z"))
self.old_worker_id = worker.WORKER_ID
self.old_max_runs = worker.MAX_RUNS
worker.MAX_RUNS = 2
def tearDown(self):
worker.WORKER_ID = self.old_worker_id
worker.MAX_RUNS = self.old_max_runs
self.conn.close()
def add_project(self, pid="p1", max_active=10, max_running=2):
self.conn.execute("""INSERT INTO projects(id,name,description,created_at,max_active_runs,max_running)
VALUES(?,?,?,?,?,?)""",
(pid, pid, "", "2026-11-12T07:00:00Z", max_active, max_running))
def add_run(self, rid, project="p1", status="queued", priority=1, created="2026-11-12T08:00:00Z"):
manifest = {"id": "exp-x", "code": "EXP-X", "title": "Test", "version": "1.0.0",
"type": "bio", "op": "test", "inputs": []}
self.conn.execute("""INSERT INTO runs(id,project_id,experiment_id,experiment_version,user_id,status,
params,inputs,manifest,provenance,timeout_sec,attempt,priority,created_at)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(rid, project, "exp-x", "1.0.0", "u1", status, "{}", "{}", dumps(manifest),
"{}", 120, 0, priority, created))
def test_registry_records_node_and_counts_active_leases(self):
common.register_worker(self.conn, "w-a", "host-a", "node-a", "3.0.0", 2)
self.add_project()
self.add_run("run-running", status="running")
self.conn.execute("UPDATE runs SET lease_owner='w-a' WHERE id='run-running'")
common.heartbeat_worker(self.conn, "w-a", 9)
details = common.worker_details(self.conn)
self.assertEqual(len(details), 1)
item = details[0]
self.assertEqual(item["id"], "w-a")
self.assertEqual(item["node"], "node-a")
self.assertTrue(item["online"])
self.assertTrue(item["claiming"])
# Trust actual leases, not the heartbeat's optimistic current_runs field.
self.assertEqual(item["currentRuns"], 1)
self.assertEqual(item["runs"][0]["id"], "run-running")
self.assertEqual(common.worker_status(self.conn)["workers"], ["w-a"])
def test_drain_preserves_active_work_and_blocks_new_claims(self):
common.register_worker(self.conn, "w-test", "host", "node", "3.0.0", 2)
self.add_project()
self.add_run("run-q1")
self.assertTrue(common.worker_is_draining(self.conn, "w-test") is False)
self.assertTrue(common.set_worker_status(self.conn, "w-test", "draining"))
worker.WORKER_ID = "w-test"
self.assertIsNone(worker.claim_run(self.conn))
self.assertEqual(self.conn.execute("SELECT status FROM runs WHERE id='run-q1'").fetchone()["status"],
"queued")
self.assertTrue(common.worker_is_draining(self.conn, "w-test"))
# A process restart must not silently clear an operator drain.
common.register_worker(self.conn, "w-test", "host", "node", "3.0.0", 2)
self.assertTrue(common.worker_is_draining(self.conn, "w-test"))
self.assertTrue(common.set_worker_status(self.conn, "w-test", "online"))
self.assertEqual(worker.claim_run(self.conn)["id"], "run-q1")
self.assertFalse(common.worker_is_draining(self.conn, "w-test"))
def test_claim_appends_lifecycle_event(self):
common.register_worker(self.conn, "w-tl", "host", "node", "3.0.0", 2)
self.add_project()
self.add_run("run-tl")
common.record_run_event(self.conn, "run-tl", "submitted", detail={"priority": "normal"})
worker.WORKER_ID = "w-tl"
self.assertEqual(worker.claim_run(self.conn)["id"], "run-tl")
timeline = common.run_timeline(self.conn, "run-tl")
self.assertEqual(timeline["schema"], common.RUN_TIMELINE_SCHEMA)
self.assertEqual(timeline["count"], 2)
self.assertEqual([e["type"] for e in timeline["events"]], ["submitted", "claimed"])
self.assertEqual(timeline["events"][1]["workerId"], "w-tl")
self.assertEqual(timeline["events"][1]["detail"]["attempt"], 1)
def test_offline_worker_disappears_from_live_count(self):
common.register_worker(self.conn, "w-old", "host", "node", "3.0.0", 2)
self.conn.execute("UPDATE workers SET last_seen='2020-01-01T00:00:00Z' WHERE id='w-old'")
details = common.worker_details(self.conn)
self.assertEqual(details[0]["status"], "offline")
self.assertFalse(details[0]["online"])
self.assertFalse(details[0]["claiming"])
self.assertEqual(common.worker_status(self.conn)["count"], 0)
def test_stale_registry_rows_are_pruned_on_register(self):
common.register_worker(self.conn, "w-stale", "host", "node", "3.0.0", 2)
self.conn.execute("UPDATE workers SET last_seen='2020-01-01T00:00:00Z' WHERE id='w-stale'")
self.assertEqual(self.conn.execute("SELECT COUNT(*) n FROM workers").fetchone()["n"], 1)
common.register_worker(self.conn, "w-current", "host", "node", "3.0.0", 2)
ids = [w["id"] for w in common.worker_details(self.conn)]
self.assertNotIn("w-stale", ids)
self.assertEqual(ids, ["w-current"])
def test_set_status_rejects_unknown_worker_and_bad_state(self):
self.assertFalse(common.set_worker_status(self.conn, "missing", "draining"))
with self.assertRaises(ValueError):
common.set_worker_status(self.conn, "missing", "offline")
def test_queue_snapshot_groups_priority_and_project(self):
self.add_project("pa", max_active=10, max_running=2)
self.add_project("pb", max_active=4, max_running=1)
self.add_run("run-a-running", project="pa", status="running")
self.add_run("run-a-normal", project="pa", priority=1, created="2026-11-12T08:00:01Z")
self.add_run("run-a-batch", project="pa", priority=0, created="2026-11-12T08:00:02Z")
self.add_run("run-b-normal", project="pb", priority=1, created="2026-11-12T08:00:03Z")
queue = common.queue_snapshot(self.conn)
self.assertEqual(queue["queued"], 3)
self.assertEqual(queue["running"], 1)
self.assertEqual(queue["oldestQueuedRunId"], "run-a-normal")
self.assertEqual(queue["byPriority"]["normal"]["queued"], 2)
self.assertEqual(queue["byPriority"]["batch"]["queued"], 1)
by_project = {p["projectId"]: p for p in queue["byProject"]}
self.assertEqual(by_project["pa"]["queued"], 2)
self.assertEqual(by_project["pa"]["running"], 1)
self.assertEqual(by_project["pb"]["queued"], 1)
self.assertEqual(by_project["pb"]["maxRunning"], 1)
self.assertEqual(by_project["pb"]["maxActiveRuns"], 4)
def test_legacy_heartbeat_is_merged_without_duplicate_ids(self):
common.register_worker(self.conn, "w-new", "host", "node", "3.0.0", 2)
common.heartbeat_worker(self.conn, "w-new", 0)
common.set_setting(self.conn, "worker:w-new:heartbeat", common.now_iso())
common.set_setting(self.conn, "worker:w-legacy:heartbeat", common.now_iso())
details = common.worker_details(self.conn)
ids = [w["id"] for w in details]
self.assertEqual(ids.count("w-new"), 1)
self.assertIn("w-legacy", ids)
self.assertEqual(common.worker_status(self.conn)["count"], 2)
if __name__ == "__main__":
unittest.main()