"""Offline tests for the cockpit's own staleness detection. A running cockpit imports this repo's python once, at start, and serves its html from disk on every request. So a repo updated underneath a running process shows NEW controls backed by OLD logic. That happened on 2026-09-08: the switch selector offered two flash targets the action layer still refused, which is a button that errors when pressed. install.sh now restarts the unit, but a plain `git pull` does not, so the process compares its sources against disk and says so. These tests pin that it does, and that it stays quiet when nothing moved. cockpit.py is loaded as a module here: importing it must not bind a port or start a thread, which is itself worth pinning. """ import atexit import importlib.util import os import re import shutil import sys import tempfile import unittest from pathlib import Path HERE = Path(__file__).resolve() DASH = HERE.parents[1] # The environment this module sets for the cockpit it loads is handed back when it ends, # so the next module in the same process starts from what this one found. ENV_BEFORE = {} def setUpModule(): ENV_BEFORE.update(os.environ) def tearDownModule(): for name in set(os.environ) - set(ENV_BEFORE): del os.environ[name] os.environ.update(ENV_BEFORE) sys.path.insert(0, str(DASH)) def load_cockpit(from_dir: Path): """Import cockpit.py from a directory as a fresh module object. COCKPIT_CONFIG_DIR is redirected first because importing is not free of side effects: _session_secret() persists an HMAC secret so a service restart does not log every browser out, and without this it wrote cockpit-secret into the developer's own ~/.config/qwen38. The CI step "The offline suite touches nothing outside itself" is what found it. """ # not setdefault(): its argument is evaluated anyway, and left a directory per call if "COCKPIT_CONFIG_DIR" not in os.environ: os.environ["COCKPIT_CONFIG_DIR"] = tempfile.mkdtemp(prefix="cockpit-code-cfg-") atexit.register(shutil.rmtree, os.environ["COCKPIT_CONFIG_DIR"], ignore_errors=True) os.environ.setdefault("COCKPIT_PORT", "0") os.environ.setdefault("COCKPIT_AGENT_PORT", "0") spec = importlib.util.spec_from_file_location( f"cockpit_under_test_{from_dir.name}", from_dir / "cockpit.py") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module class Fingerprint(unittest.TestCase): @classmethod def setUpClass(cls): cls.ck = load_cockpit(DASH) def test_importing_the_cockpit_binds_nothing(self): # If importing it started the server, every test here would hold :30090. Measured # around a fresh import: the threads it leaves and the sockets it opens. It used to # look for a name nothing defines, so a server started at import passed (found in # review, 2026-09-24). import threading def sockets(): out = set() for fd in os.listdir("/proc/self/fd"): try: target = os.readlink(f"/proc/self/fd/{fd}") except OSError: # the listing's own descriptor, closed since continue if target.startswith("socket:"): out.add(target) return out if not os.path.isdir("/proc/self/fd"): self.skipTest("needs /proc to see the sockets a process holds") threads, socks = set(threading.enumerate()), sockets() ck = load_cockpit(DASH) new_threads = set(threading.enumerate()) - threads new_socks = sockets() - socks self.assertEqual(new_threads, set(), "importing cockpit.py started a thread") self.assertEqual(new_socks, set(), "importing cockpit.py opened a socket") self.assertTrue(callable(ck.code_fingerprint)) def test_it_watches_the_files_its_behaviour_comes_from(self): fp = self.ck.code_fingerprint() for name in ("cockpit.py", "recipes.py", "static/index.html", "static/js/base.js", "static/js/video.js"): self.assertIn(name, fp, name) self.assertNotEqual(fp[name], "missing", name) # every watched name exists in the shipped tree, or the check is noise for name in self.ck.CODE_FILES: self.assertTrue((DASH / name).exists(), name) def test_it_watches_each_module_of_its_own_it_imports(self): # engine_metrics.py was imported and not watched: a change to it alone left the old code running, and # nothing said so (found adding engines.py, 2026-11-08) text = (DASH / "cockpit.py").read_text() own = {m for m in re.findall(r"(?m)^import (\w+)(?: as \w+)?$", text) if (DASH / f"{m}.py").exists()} self.assertTrue({"lifecycle", "registry", "recipes", "engines"} <= own, own) for m in sorted(own): self.assertIn(f"{m}.py", self.ck.CODE_FILES, m) def test_the_page_gets_each_lanes_engine_from_its_collector(self): # decision 1178: the page names each lane's engine from engine_table, read every 30 s (the config's copy, read # once, missed a lane installed on its own afterwards: code review of v1.45.0) self.assertNotIn("engines", self.ck.STATE["config"]["data"]) self.assertIn("engine_table", self.ck.PERIODS) table = self.ck.collect_engine_table()["table"] self.assertEqual({u: {k: v for k, v in row.items() if k not in ("pinned", "window")} for u, row in table.items()}, self.ck.en.page_table()) self.assertTrue(all("pinned" in row and "window" in row for row in table.values()), table) self.assertEqual(table["qwen38-sglang.service"]["label"], "SGLang 0.5.22") def test_each_units_window_as_its_unit_starts_it(self): # FLASH_LOCAL_CONTEXT=1m (discussion #63): the page says the window the unit runs, read from the unit file import tempfile d = Path(tempfile.mkdtemp(prefix="units-")) (d / "qwen38-flash-local.service").write_text( "ExecStart=/bin/bash -c 'exec docker run eugr/spark-vllm-b12x@sha256:" + "0" * 64 + " vllm serve x \\\n" " --max-model-len 1048576 --max-num-seqs 8 \\\n --host 127.0.0.1 --port 30000'\n") old_dir, self.ck.UNIT_DIR = self.ck.UNIT_DIR, d ei = self.ck._engine_inputs() read, old_read = [], ei._read ei._read = lambda f: (read.append(f), old_read(f))[1] try: table = self.ck.engine_table() finally: self.ck.UNIT_DIR = old_dir ei._read = old_read self.assertEqual(table["qwen38-flash-local.service"]["window"], 1048576) self.assertIsNone(table["qwen38-sglang.service"]["window"], "no unit file there: nothing said") # read once, for its window and for what its engine starts (code review of v1.45.2: twice every 30 s) self.assertNotIn(str(d / "qwen38-flash-local.service"), read) self.assertIs(table["qwen38-flash-local.service"]["pinned"], False, "its image is not the pin") def test_quiet_when_nothing_moved(self): self.assertEqual(self.ck.code_is_stale(), []) def test_it_notices_a_changed_file(self): # A copy of the tree, so the real one is never touched. with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) / "dashboard" shutil.copytree(DASH, root, ignore=shutil.ignore_patterns( "__pycache__", ".ruff_cache", "tests")) (root / "tests").mkdir(exist_ok=True) ck = load_cockpit(root) self.assertEqual(ck.code_is_stale(), []) target = root / "static" / "js" / "base.js" target.write_text(target.read_text() + "\n// touched by a test\n") os.utime(target, (0, 0)) # a different mtime AND size self.assertEqual(ck.code_is_stale(), ["static/js/base.js"]) # two files, both reported, sorted other = root / "recipes.py" other.write_text(other.read_text() + "\n# touched\n") self.assertEqual(ck.code_is_stale(), ["recipes.py", "static/js/base.js"]) def test_a_deleted_file_is_reported_too(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) / "dashboard" shutil.copytree(DASH, root, ignore=shutil.ignore_patterns( "__pycache__", ".ruff_cache", "tests")) ck = load_cockpit(root) (root / "registry.py").unlink() self.assertIn("registry.py", ck.code_is_stale()) class TabsAgree(unittest.TestCase): """Three lists describe the views, and a view exists only if all three carry it: the rail's buttons, the sections they reveal, and the router's own array. Adding a view to two of the three is a rail entry that opens nothing, or a section nobody can reach. The System One, Image and Video views were added on 2026-09-21 and this is the gate that says the next one is added everywhere.""" def setUp(self): self.html = (DASH / "static/index.html").read_text() self.js = (DASH / "static/js/base.js").read_text() def test_the_rail_the_views_and_the_router_carry_the_same_views(self): import re rail = re.findall(r'class="nav" data-view="([a-z-]+)"', self.html) views = re.findall(r'class="view[^"]*" id="view-([a-z-]+)"', self.html) m = re.search(r"const VIEWS = \[([^\]]+)\]", self.js) self.assertTrue(m, "base.js no longer declares a VIEWS array") router = re.findall(r"'([a-z-]+)'", m.group(1)) self.assertEqual(sorted(rail), sorted(views), "a rail button opens no view, or a view has no button") self.assertEqual(sorted(rail), sorted(router), "the router and the rail disagree on which views exist") self.assertEqual(rail, router, "the rail and the router disagree on view ORDER") def test_every_old_address_still_lands_on_a_view(self): """Links in the docs and bookmarks name the old tabs (#agent, #engines, #overview).""" import re m = re.search(r"const ALIAS = \{([^}]+)\}", self.js) self.assertTrue(m, "base.js no longer maps the old tab names") router = re.findall(r"'([a-z-]+)'", re.search(r"const VIEWS = \[([^\]]+)\]", self.js).group(1)) old = ["overview", "agent", "engines", "requests", "machine", "models", "systemone", "image", "video", "logs", "setup"] alias = dict(re.findall(r"(\w+): '([a-z-]+)'", m.group(1))) for name in old: with self.subTest(name=name): self.assertIn(alias.get(name, name), router) def test_every_view_the_browser_checks_walk_is_a_view_that_exists(self): import re rail = re.findall(r'class="nav" data-view="([a-z-]+)"', self.html) for name in ("monkey-check.mjs", "mobile-check.mjs"): src = (DASH / "tests" / name).read_text() m = re.search(r"const VIEWS = \[([^\]]+)\]", src) self.assertTrue(m, f"{name} no longer declares a VIEWS array") walked = re.findall(r"'([a-z-]+)'", m.group(1)) self.assertEqual(sorted(walked), sorted(rail), f"{name} walks views the page does not have, or misses one") if __name__ == "__main__": unittest.main(verbosity=2)