diff --git a/evidence/localrouter-setup/host-suite.log b/evidence/localrouter-setup/host-suite.log new file mode 100644 index 00000000..5e780b10 --- /dev/null +++ b/evidence/localrouter-setup/host-suite.log @@ -0,0 +1,5 @@ +cc -std=gnu11 -Wall -Wextra -Werror -MMD -MP -D_GNU_SOURCE -O2 -Isrc -I./m16 -I./nvrm -I./third_party/nvidia-open-580.173.02/src/common/sdk/nvidia/inc -I./third_party/nvidia-open-580.173.02/kernel-open/common/inc -I./third_party/nvidia-open-580.173.02/kernel-open/nvidia-uvm -I./third_party/nvidia-open-580.173.02/src/nvidia/arch/nvalloc/unix/include -c src/omega_blackwell_engine.c -o build/omega_blackwell_engine.o +src/omega_blackwell_engine.c: Assembler messages: +src/omega_blackwell_engine.c:558: Error: number of operands mismatch for `ds' +src/omega_blackwell_engine.c:393: Error: number of operands mismatch for `ds' +make: *** [Makefile:38: build/omega_blackwell_engine.o] Error 1 diff --git a/evidence/localrouter-setup/negative-control.log b/evidence/localrouter-setup/negative-control.log new file mode 100644 index 00000000..5c693553 --- /dev/null +++ b/evidence/localrouter-setup/negative-control.log @@ -0,0 +1,2 @@ +PASS: shared-lock guard removed in scratch copy; intended rejection test failed +mutant exit code: 1 diff --git a/evidence/localrouter-setup/python-tests.log b/evidence/localrouter-setup/python-tests.log new file mode 100644 index 00000000..c985623f --- /dev/null +++ b/evidence/localrouter-setup/python-tests.log @@ -0,0 +1,14 @@ +test_candidate_preserves_omega_lock_without_router_shared_lock (test_setup.SetupTests.test_candidate_preserves_omega_lock_without_router_shared_lock) ... ok +test_completion_rejects_other_model_and_tool_results (test_setup.SetupTests.test_completion_rejects_other_model_and_tool_results) ... ok +test_http_probe_exercises_real_loopback_transport_but_never_claims_gpu (test_setup.SetupTests.test_http_probe_exercises_real_loopback_transport_but_never_claims_gpu) ... ok +test_missing_server_or_tokenizer_is_a_setup_failure (test_setup.SetupTests.test_missing_server_or_tokenizer_is_a_setup_failure) ... ok +test_refuses_mixed_workers_host_lock_and_remote_bind (test_setup.SetupTests.test_refuses_mixed_workers_host_lock_and_remote_bind) ... ok +test_rejects_live_ports_bad_budgets_and_unsafe_model_ids (test_setup.SetupTests.test_rejects_live_ports_bad_budgets_and_unsafe_model_ids) ... ok +test_sse_rejects_error_truncation_wrong_model_and_empty_output (test_setup.SetupTests.test_sse_rejects_error_truncation_wrong_model_and_empty_output) ... ok +test_stub_explicitly_has_no_gpu_qualification (test_setup.SetupTests.test_stub_explicitly_has_no_gpu_qualification) ... ok +test_valid_sse_and_usage_only_final_event (test_setup.SetupTests.test_valid_sse_and_usage_only_final_event) ... ok + +---------------------------------------------------------------------- +Ran 9 tests in 0.515s + +OK diff --git a/evidence/localrouter-setup/receipt.json b/evidence/localrouter-setup/receipt.json new file mode 100644 index 00000000..afc64b11 --- /dev/null +++ b/evidence/localrouter-setup/receipt.json @@ -0,0 +1,50 @@ +{ + "baseline_commit": "232332422bfdc31c8918085b50f13c1e18ab702e", + "issue": "https://github.com/aien-dev/CUDApp/issues/27", + "machine": "x86_64", + "python": "3.12.14", + "source_sha256": { + "tools/localrouter/setup.py": "06508aca53b9d067c8e63e6b46de061f859b7251177cfe7afdfa812bd0817dd9", + "tools/localrouter/README.md": "c0d97ef86675b041f2a61f0cab44fd61492a40e63ebce41bc86ab03ae8c8381b", + "tests/localrouter/test_setup.py": "61174009fd756eba2b7ed8eece9cbbde0717389aa55595d4576f6770eb3e00bb", + "tests/localrouter/negative_control.py": "23e251f883a629c00bc0b6557331f56a38927cfe632ece133c5759ac70b83a2b" + }, + "checks": [ + { + "command": "python3 -m unittest discover -s tests/localrouter -v", + "exit_code": 0, + "result": "PASS", + "tests": 9, + "log": "python-tests.log", + "scope": "Python client and loopback fixtures only" + }, + { + "command": "python3 tests/localrouter/negative_control.py", + "exit_code": 0, + "result": "PASS", + "log": "negative-control.log", + "scope": "removing shared-lock rejection causes intended test failure" + }, + { + "command": "make test", + "exit_code": 2, + "result": "FAIL", + "log": "host-suite.log", + "cause": "existing unguarded AArch64 dsb sy in omega_blackwell_engine.c on x86_64" + }, + { + "command": "git diff --check", + "exit_code": 0, + "result": "PASS" + } + ], + "not_run": [ + "real LocalRouter Zig build/tests (Zig 0.17.0 unavailable in this workspace)", + "real LocalRouter + aien-serve-http integration", + "GB10 correctness and model/memory measurements", + "unload/reload/cancel and child-process cleanup", + "runtime CUDA library/provenance verification", + "MCP client integration" + ], + "live_service_changes": false +} diff --git a/tests/localrouter/negative_control.py b/tests/localrouter/negative_control.py new file mode 100644 index 00000000..0ab947cf --- /dev/null +++ b/tests/localrouter/negative_control.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Remove the shared-lock guard in a temporary copy; its test must fail.""" +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile + + +root = Path(__file__).resolve().parents[2] +with tempfile.TemporaryDirectory(prefix="localrouter-control-") as name: + temp = Path(name) + for relative in ("tools/localrouter/setup.py", "tests/localrouter/test_setup.py"): + target = temp / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(root / relative, target) + script = temp / "tools/localrouter/setup.py" + text = script.read_text() + before = 'require(cfg.get("gpu_lock") == "",' + if text.count(before) != 1: + sys.exit("FAIL: shared-lock guard was not found exactly once") + script.write_text(text.replace(before, 'require(True,')) + run = subprocess.run([sys.executable, "-m", "unittest", "discover", "-s", + "tests/localrouter", "-p", "test_setup.py", "-v"], + cwd=temp, capture_output=True, text=True) + output = run.stdout + run.stderr + # A crash/import failure cannot count as detecting this control. + if run.returncode == 0 or "AssertionError: ValueError not raised" not in output or "FAILED (failures=1)" not in output: + print(output) + sys.exit("FAIL: removing the shared-lock guard did not fail its intended check") + print("PASS: shared-lock guard removed in scratch copy; intended rejection test failed") + print("mutant exit code:", run.returncode) diff --git a/tests/localrouter/test_setup.py b/tests/localrouter/test_setup.py new file mode 100644 index 00000000..922cdd2d --- /dev/null +++ b/tests/localrouter/test_setup.py @@ -0,0 +1,179 @@ +# SPDX-License-Identifier: MIT +"""Host-only contract tests. No LocalRouter binary, model, or GPU is opened.""" +import copy +import importlib.util +import json +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +import tempfile +import threading +import unittest + + +SCRIPT = Path(__file__).resolve().parents[2] / "tools/localrouter/setup.py" +spec = importlib.util.spec_from_file_location("localrouter_setup", SCRIPT) +setup = importlib.util.module_from_spec(spec) +spec.loader.exec_module(setup) + + +class SetupTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.server = self.root / "aien-serve-http" + self.server.write_text("#!/bin/sh\nexit 0\n") + self.server.chmod(0o755) + self.model = self.root / "model" + self.model.mkdir() + (self.model / "tokenizer.json").write_text("{}") + + def config(self, **extra): + args = dict(server=str(self.server), model_dir=str(self.model), + model_id="omega-candidate", engine="omega", + resident_bytes=1024, working_bytes=512, + data_dir=str(self.root / "data"), router_port=8192, + backend_port=18092, reserve_bytes=8589934592) + args.update(extra) + return setup.make_config(**args) + + def test_candidate_preserves_omega_lock_without_router_shared_lock(self): + cfg = self.config() + setup.validate_config(cfg) + self.assertEqual(cfg["gpu_lock"], "") + self.assertEqual(len(cfg["tools"]), 1) + self.assertFalse(cfg["tools"][0]["keep_loaded"]) + self.assertFalse(cfg["voice"]["tools"]) + self.assertFalse(cfg["voice"]["speculate"]) + self.assertNotIn("env", cfg["tools"][0]["options"]) + command = cfg["tools"][0]["options"]["server"] + self.assertEqual(command[command.index("--port") + 1], "{port}") + self.assertEqual(command[command.index("--model-id") + 1], "{id}") + + def test_rejects_live_ports_bad_budgets_and_unsafe_model_ids(self): + for change in [dict(backend_port=18091), dict(router_port=18091), + dict(backend_port=8192), dict(resident_bytes=0), + dict(working_bytes=-1), dict(model_id="../live"), + dict(router_port=0), dict(reserve_bytes=0)]: + with self.subTest(change=change), self.assertRaises(ValueError): + self.config(**change) + + def test_refuses_mixed_workers_host_lock_and_remote_bind(self): + for mutate in [lambda c: c.update(host="0.0.0.0"), + lambda c: c.update(gpu_lock="/tmp/aien-gb10.lock"), + lambda c: c["tools"].append(copy.deepcopy(c["tools"][0])), + lambda c: c["voice"].update(tools=True), + lambda c: c["tools"][0].update(keep_loaded=True)]: + cfg = self.config() + mutate(cfg) + with self.assertRaises(ValueError): + setup.validate_config(cfg) + + def test_missing_server_or_tokenizer_is_a_setup_failure(self): + cfg = self.config() + setup.check_files(cfg) + (self.model / "tokenizer.json").unlink() + with self.assertRaises(ValueError): + setup.check_files(cfg) + self.server.unlink() + with self.assertRaises(ValueError): + setup.check_files(cfg) + + def test_stub_explicitly_has_no_gpu_qualification(self): + cfg = self.config(engine="stub", resident_bytes=0, working_bytes=0) + (self.model / "tokenizer.json").unlink() + setup.check_files(cfg) + self.assertEqual(setup.engine_of(cfg), "stub") + + def test_valid_sse_and_usage_only_final_event(self): + frames = [ + {"model": "omega-candidate", "choices": [{"delta": {"content": "hello"}, "finish_reason": None}]}, + {"model": "omega-candidate", "choices": [{"delta": {}, "finish_reason": "stop"}]}, + {"model": "omega-candidate", "choices": [], "usage": {"completion_tokens": 1}}, + ] + lines = [": keep-alive\n", "\n"] + for frame in frames: + lines.extend(["data: " + json.dumps(frame) + "\n", "\n"]) + lines.extend(["data: [DONE]\n", "\n"]) + self.assertEqual(setup.check_sse(iter(lines), "omega-candidate"), 5) + + def test_sse_rejects_error_truncation_wrong_model_and_empty_output(self): + valid = {"model": "omega-candidate", "choices": [{"delta": {"content": "ok"}, "finish_reason": "stop"}]} + cases = [ + ["data: " + json.dumps(valid) + "\n", "\n"], + ["data: {\"error\":{\"message\":\"fault\"}}\n", "\n", "data: [DONE]\n", "\n"], + ["data: " + json.dumps(dict(valid, model="other")) + "\n", "\n", "data: [DONE]\n", "\n"], + ["data: [DONE]\n", "\n"], + ] + for lines in cases: + with self.subTest(lines=lines), self.assertRaises(ValueError): + setup.check_sse(iter(lines), "omega-candidate") + + def test_completion_rejects_other_model_and_tool_results(self): + response = {"model": "omega-candidate", "choices": [{"message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}]} + self.assertEqual(setup.check_completion(response, "omega-candidate"), "ok") + with self.assertRaises(ValueError): + setup.check_completion(dict(response, model="other"), "omega-candidate") + response["choices"][0]["message"]["tool_calls"] = [{}] + with self.assertRaises(ValueError): + setup.check_completion(response, "omega-candidate") + + def test_http_probe_exercises_real_loopback_transport_but_never_claims_gpu(self): + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_args): + pass + + def send_json(self, status, value): + body = json.dumps(value).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + if self.path == "/health": + self.send_json(200, {"model": "omega-candidate", "engine": "stub"}) + elif self.path == "/v1/models": + self.send_json(200, {"data": [{"id": "omega-candidate"}]}) + else: + self.send_json(404, {"error": "unknown path"}) + + def do_POST(self): + value = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + if value.get("model") != "omega-candidate": + self.send_json(404, {"error": "unknown model"}) + elif value.get("tools"): + self.send_json(400, {"error": "tools unsupported"}) + elif value.get("stream"): + event = {"model": "omega-candidate", "choices": [{"delta": {"content": "hello"}, "finish_reason": "stop"}]} + body = ("data: " + json.dumps(event) + "\n\ndata: [DONE]\n\n").encode() + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + else: + self.send_json(200, {"model": "omega-candidate", "choices": [{"message": {"role": "assistant", "content": "hello"}, "finish_reason": "stop"}]}) + + servers = [] + for _ in range(2): + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + servers.append(server) + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + cfg = self.config(engine="stub", resident_bytes=0, working_bytes=0, + router_port=servers[0].server_port, + backend_port=servers[1].server_port) + result = setup.exercise(cfg, 5) + self.assertEqual(result["http_protocol"], "PASS") + self.assertEqual(result["gpu_qualification"], "NOT_RUN") + self.assertEqual(len(result["checks"]), 8) + with self.assertRaises(ValueError): + setup.check_ports(cfg) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/localrouter/README.md b/tools/localrouter/README.md new file mode 100644 index 00000000..a2676d13 --- /dev/null +++ b/tools/localrouter/README.md @@ -0,0 +1,157 @@ +# LocalRouter with an Omega text server + +This is a text-only candidate setup, tracked by [CUDApp #27](https://github.com/aien-dev/CUDApp/issues/27). +It generates configuration and checks HTTP behavior. It installs no service, downloads no weights, +and changes no GPU driver. It does not port LocalRouter's image/video kernels to CUDA++. + +## What connects + +An OpenAI client or LocalRouter's MCP `chat` tool reaches LocalRouter on loopback port 8192. +LocalRouter's existing `openai_server` worker launches a separate `aien-serve-http` candidate +on loopback port 18092. That server selects the Omega engine. Its actual linked GPU backend +must be qualified through the canonical CUDApp consumption work in #5. + +Inspected sources: + +| Repository | Revision | Contract | +| --- | --- | --- | +| [LocalRouter](https://github.com/jayleaton/localrouter/tree/70ad4fa198dfc0c8175d02fff746e95759c42d59) | `70ad4fa198dfc0c8175d02fff746e95759c42d59` | `src/engines/openai_server.zig`, `src/config.zig`, `src/tool/process.zig` | +| [sovereign-core](https://github.com/aien-dev/aien-sovereign-core-mv/tree/754c07b118f41ad899607b60329bd851b1ccb13e) | `754c07b118f41ad899607b60329bd851b1ccb13e` | `crates/aien-serve-http/src/{main,server,omega_engine}.rs` | +| CUDA++ | `232332422bfdc31c8918085b50f13c1e18ab702e` | baseline before this integration | + +Recheck these contracts if consuming different revisions. Do not overwrite the live motor's binary, +configuration or CUDApp pin to make this example run. + +## Two integration limits + +**Process ownership:** `openai_server` starts a child and terminates it on unload or daemon exit. +It cannot attach to the existing motor. Use a separate immutable candidate binary, candidate +model ID, data directory and ports. The generator reserves port 18091 for the live motor. +Other live-service ports must also be excluded by the operator. `check` refuses occupied ports, +but checking a free port does not reserve it against another process. + +**GPU locking:** LocalRouter normally holds its configured host lock shared while any model +is loaded. The inspected Omega engine takes `/tmp/aien-gb10.lock` exclusively during load and +generation. Using that file for both would block Omega. This profile therefore leaves +LocalRouter's `gpu_lock` empty, keeps Omega's lock unchanged, and permits exactly one text tool. +Do not add LocalRouter image/video/speech GPU workers to this profile. Their execution would +need an explicitly qualified lock/admission handoff. The memory budget is admission accounting, +not a global reservation against other processes. Coordinate candidate loading with the GPU +owner and keep the live motor's memory in the budget. + +## Before starting + +You need Python 3.10+, a LocalRouter binary and a separately qualified `aien-serve-http` candidate. +The inspected LocalRouter build requires **exactly Zig 0.17.0** and pins TensorFold in +`build.zig.zon`. Its documented host build is `zig build -Doptimize=ReleaseSafe`; omit `-Dnvcc` +for this text-only experiment. That avoids embedding its own CUDA kernels. It does not prove +that every LocalRouter process is free of CUDA library mappings. Record and inspect the actual +binaries/processes before making that claim. Run upstream's `zig build test` on the build host. + +Reuse the server build and complete source/dependency closure from the #5 integration owner. +The inspected server accepts `--engine omega`, `--model-dir`, `--bind`, `--port`, `--model-id` +and `--max-context`. This profile limits context to 4096 and uses the server's existing default +FP8 weights. Use its supported Qwen checkpoint and tokenizer, not an image/video checkpoint. +The candidate needs enough free memory for its own load even when the live motor is resident. + +Measure and record `resident_bytes` and incremental per-request `working_bytes` for the +chosen engine, checkpoint and context. Do not copy another model's memory numbers or enter +zero for an unmeasured Omega resident size. Zero incremental working memory is valid only +when measured. The generator requires these values explicitly. + +## Generate and check a candidate config + +Run from the CUDA++ checkout on the target host. Supply real absolute paths and measured byte +counts. These shell parameters deliberately refuse missing values: + +```sh +python3 tools/localrouter/setup.py config \ + --server "${OMEGA_CANDIDATE_BIN:?absolute path to a separate aien-serve-http}" \ + --model-dir "${OMEGA_MODEL_DIR:?absolute path to the supported checkpoint}" \ + --data-dir "${LOCALROUTER_CANDIDATE_DATA:?absolute path to a separate data directory}" \ + --resident-bytes "${OMEGA_RESIDENT_BYTES:?measured resident bytes}" \ + --working-bytes "${OMEGA_WORKING_BYTES:?measured incremental working bytes}" \ + --router-port 8192 --backend-port 18092 \ + > localrouter-omega.candidate.json + +python3 tools/localrouter/setup.py check --config localrouter-omega.candidate.json +``` + +Keep generated host-specific config outside version control. Generation only inspects paths. +`check` additionally tests whether the ports are available. Neither starts a server or opens a GPU. +The 8 GiB OS reserve is a starting configuration, not a measured model budget or an OOM guarantee. +Increase it to account for the other resident workloads as needed with `--reserve-bytes`. + +Use a foreground daemon first, on the same host as the candidate binary and model files: + +```sh +/absolute/path/to/localrouter serve --config localrouter-omega.candidate.json +``` + +There is no boot service, container, tailnet exposure or full Jarvis installation in this setup. +The generated `keep_loaded: false` prevents eager model loading at daemon startup. A generation +request loads the candidate. It can then remain warm until its 300-second idle timeout or an +explicit unload. Logs are under the configured data directory. + +## Read-only inspection, then opt-in generation + +In a second terminal: + +```sh +# Lists the candidate without asking it to load or generate. +python3 tools/localrouter/setup.py probe --config localrouter-omega.candidate.json + +# Coordinated GPU window only: this sends several short requests and loads the model. +python3 tools/localrouter/setup.py probe --config localrouter-omega.candidate.json \ + --exercise --timeout 180 > localrouter-omega.http-receipt.json +``` + +The exercised probe checks router model listing, a whole completion, backend health/model/engine, +a second turn, a complete SSE response, rejected tool calling and an unknown-model error. +SSE errors, empty replies, wrong models and missing finish/[DONE] events fail. A local mock test +of the client is not a test of the real Zig daemon or Rust model server. + +The HTTP receipt always leaves GPU correctness, process lifecycle and CUDA-free provenance +`NOT_RUN`. It establishes only protocol behavior. Qualify the actual model with golden/numerical +checks, cancellation, unload/reload, process cleanup, memory measurements, source/binary hashes, +and `/proc//maps` observations in a separate receipt before promoting this configuration. +Confirm the live motor is still healthy before and after the window. Do not run deliberate +faults against the live service. + +At the inspected sovereign-core revision, nonempty `tools` and `tool` message roles are rejected. +The generated voice settings disable tools, model management, speculative chat and priming. +LocalRouter MCP can still expose a plain-text `chat` tool to an external agent, but this does +not give Omega native tool calling. Validate MCP separately if enabling it in a client. + +## Stop and rollback + +Stop only the foreground candidate daemon with Ctrl-C. LocalRouter is expected to stop its +worker and owned server. Verify port 18092 is closed and its child PID has exited; record a +lifecycle failure if either survives. Keep the live 18091 motor untouched. Keep model files and +qualified binaries; remove only the candidate configuration/data when no longer needed. +Do not use a broad `pkill`, restart the production service, unload GPU modules, or install the +full upstream Jarvis profile as a shortcut for this experiment. + +## Host smoke test without a model + +Use the server's explicit `--engine stub` mode with an empty temporary model directory and +`--resident-bytes 0 --working-bytes 0`. Follow the same generate/check/start/probe sequence. +Label every result `stub`, not GPU-qualified. The setup script itself has no compiler or model +dependency: + +```sh +python3 -m unittest discover -s tests/localrouter -v +``` + +## After text routing works + +1. Qualify shared-lock ownership and capability reporting before adding other GPU workers. +2. Benchmark one matched RMSNorm/SwiGLU operation with identical shape, datatype and numerical + contract. Compare full outputs, warm latency, submission cost and memory on the same GB10. +3. Extend to a short native chain using #18 and #19. Reusable graph replay additionally needs + persistent resources, safe parameter updates and lifecycle tests; command lists alone do + not establish CUDA Graph equivalence. +4. Treat NVFP4/image/video parity as separate numerical and kernel-coverage work. Existing CUDA + fatbins cannot simply be passed to CUDA++'s native kernel builder. + +No speedup or full Jarvis capability is claimed by this integration. diff --git a/tools/localrouter/setup.py b/tools/localrouter/setup.py new file mode 100644 index 00000000..fe54fda7 --- /dev/null +++ b/tools/localrouter/setup.py @@ -0,0 +1,287 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Prepare and probe an isolated, text-only LocalRouter -> Omega candidate.""" +import argparse +import hashlib +import http.client +import json +import os +from pathlib import Path +import re +import socket +import sys +import time + + +MAX_BODY = 2 * 1024 * 1024 +MODEL_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,95}\Z") + + +def require(ok, message): + if not ok: + raise ValueError(message) + + +def engine_of(cfg): + command = cfg["tools"][0]["options"]["server"] + return command[command.index("--engine") + 1] + + +def make_config(*, server, model_dir, model_id, engine, resident_bytes, + working_bytes, data_dir, router_port, backend_port, reserve_bytes): + cfg = { + "host": "127.0.0.1", "port": router_port, "data_dir": data_dir, + "reserve_bytes": reserve_bytes, "gpu_lock": "", + "defaults": {"chat_completion": model_id}, + "voice": {"tools": False, "manage_models": False, "speculate": False, + "prime_chat": False}, + "tools": [{ + "id": model_id, "kind": "chat", "engine": "openai_server", + "name": "Omega text candidate", "weights": model_dir, + "resident_bytes": resident_bytes, "working_bytes": working_bytes, + "keep_loaded": False, "idle_ttl_s": 300, "priority": 100, + "load_timeout_s": 900, "generate_timeout_s": 180, + "options": { + "port": backend_port, "health": "/health", "stop_timeout_s": 30, + "server": [server, "--engine", engine, "--model-dir", "{weights}", + "--bind", "127.0.0.1", "--port", "{port}", + "--model-id", "{id}", "--max-context", "4096"], + }, + }], + } + validate_config(cfg) + return cfg + + +def validate_config(cfg): + """Validate only this setup profile, not arbitrary LocalRouter configurations.""" + require(cfg.get("host") == "127.0.0.1", "candidate must bind 127.0.0.1") + require(cfg.get("gpu_lock") == "", "LocalRouter must not hold a shared GPU lock in this text-only profile") + tools = cfg.get("tools", []) + require(len(tools) == 1, "candidate must contain exactly one text tool; mixed GPU scheduling is unqualified") + tool = tools[0] + require(tool.get("kind") == "chat" and tool.get("engine") == "openai_server", "expected one openai_server chat tool") + require(MODEL_ID.fullmatch(tool.get("id", "")), "model id must be a simple name, not a path") + require(cfg.get("defaults", {}).get("chat_completion") == tool["id"], "default model must match the backend model id") + require(tool.get("keep_loaded") is False, "candidate must load on demand, not at daemon startup") + voice = cfg.get("voice", {}) + require(all(voice.get(k) is False for k in ("tools", "manage_models", "speculate", "prime_chat")), + "disable voice tool calling, model management, speculation and priming") + opts = tool.get("options", {}) + command = opts.get("server", []) + require(isinstance(command, list) and all(isinstance(x, str) for x in command), "server command must be an argv array") + require(len(command) == 13, "unexpected server command; regenerate this candidate profile") + engine = command[2] + require(engine in ("stub", "omega"), "engine must be stub or omega") + require(command[1:] == ["--engine", engine, "--model-dir", "{weights}", "--bind", "127.0.0.1", + "--port", "{port}", "--model-id", "{id}", "--max-context", "4096"], + "server must use the inspected loopback, port and model-id contract") + require("env" not in opts, "this profile must not override Omega's lock environment") + for path in (command[0], tool.get("weights", ""), cfg.get("data_dir", "")): + require(Path(path).is_absolute() and not any(c in path for c in "\x00\n\r{}"), + "server, model and data paths must be absolute and contain no template braces or control characters") + ports = (cfg.get("port"), opts.get("port")) + require(all(type(p) is int and 1024 <= p <= 65535 and p != 18091 for p in ports), + "use unprivileged candidate ports; live motor port 18091 is reserved") + require(ports[0] != ports[1], "router and backend ports must differ") + for key, value in (("resident_bytes", tool.get("resident_bytes")), + ("working_bytes", tool.get("working_bytes")), + ("reserve_bytes", cfg.get("reserve_bytes"))): + require(type(value) is int and 0 <= value < 2**63, key + " must be a bounded nonnegative byte count") + require(cfg["reserve_bytes"] > 0, "keep a nonzero OS reserve") + require(engine == "stub" or tool["resident_bytes"] > 0, "Omega requires an explicit nonzero measured resident budget") + + +def check_files(cfg): + validate_config(cfg) + tool = cfg["tools"][0] + server = Path(tool["options"]["server"][0]) + require(server.is_file() and os.access(server, os.X_OK), "server binary does not exist or is not executable: " + str(server)) + model = Path(tool["weights"]) + require(model.is_dir(), "model directory does not exist: " + str(model)) + if engine_of(cfg) == "omega": + require((model / "tokenizer.json").is_file(), "Omega model directory needs tokenizer.json and its supported checkpoint") + + +def check_ports(cfg): + for port in (cfg["port"], cfg["tools"][0]["options"]["port"]): + try: + with socket.socket() as sock: + sock.bind(("127.0.0.1", port)) + except OSError as exc: + raise ValueError(f"candidate port {port} is unavailable; do not stop its owner") from exc + + +def check_completion(value, model): + require(isinstance(value, dict) and value.get("model") == model and "error" not in value, "completion error or wrong model") + choices = value.get("choices", []) + require(len(choices) == 1, "expected one completion choice") + choice = choices[0] + msg = choice.get("message", {}) + require(msg.get("role") == "assistant" and not msg.get("tool_calls"), "expected a plain-text assistant response") + text = msg.get("content") + require(isinstance(text, str) and text.strip(), "completion has no text") + require(choice.get("finish_reason") in ("stop", "length"), "completion has no successful finish reason") + return text + + +def check_sse(lines, model): + text = [] + finished = False + data = [] + for raw in lines: + line = raw.rstrip("\r\n") + if line.startswith(":"): + continue + if line.startswith("data:"): + data.append(line[5:].lstrip(" ")) + continue + if line or not data: + continue + payload = "\n".join(data) + data.clear() + if payload == "[DONE]": + require(finished and "".join(text).strip(), "SSE ended without text and a finish reason") + return len("".join(text)) + event = json.loads(payload) + require(isinstance(event, dict) and "error" not in event and event.get("model") == model, + "SSE contains an error or wrong model") + for choice in event.get("choices", []): + delta = choice.get("delta", {}) + require(not delta.get("tool_calls"), "unexpected tool call in text-only SSE") + if delta.get("content") is not None: + require(isinstance(delta["content"], str), "invalid content delta") + text.append(delta["content"]) + if choice.get("finish_reason") is not None: + require(choice["finish_reason"] in ("stop", "length"), "SSE failed finish reason") + finished = True + raise ValueError("SSE truncated: no complete [DONE] event") + + +def request(port, method, path, payload=None, *, timeout=180, stream_model=None): + """Literal loopback only; no proxies, redirects or arbitrary upstream URLs.""" + conn = http.client.HTTPConnection("127.0.0.1", port, timeout=timeout) + try: + body = None if payload is None else json.dumps(payload).encode() + conn.request(method, path, body, {"Content-Type": "application/json"}) + response = conn.getresponse() + if stream_model is not None and response.status == 200: + require(response.getheader("Content-Type", "").startswith("text/event-stream"), "expected SSE content type") + def lines(): + total = 0 + deadline = time.monotonic() + timeout + while True: + require(time.monotonic() < deadline, "SSE deadline exceeded") + if conn.sock: + conn.sock.settimeout(max(0.01, deadline - time.monotonic())) + raw = response.readline(65537) + if not raw: + return + total += len(raw) + require(len(raw) <= 65536 and total <= MAX_BODY, "SSE exceeds smoke-test size limit") + yield raw.decode("utf-8") + return response.status, {"text_chars": check_sse(lines(), stream_model)} + raw = response.read(MAX_BODY + 1) + require(len(raw) <= MAX_BODY, "response exceeds smoke-test size limit") + return response.status, json.loads(raw) + finally: + conn.close() + + +def exercise(cfg, timeout): + """Explicitly sends short generation requests to an already running candidate.""" + validate_config(cfg) + tool = cfg["tools"][0] + model, port = tool["id"], cfg["port"] + upstream = tool["options"]["port"] + checks = [] + def expect(name, actual, expected): + require(actual == expected, f"{name}: expected {expected}, got {actual}") + checks.append(name) + status, listed = request(port, "GET", "/v1/models", timeout=timeout) + expect("router_models", status, 200) + require(any(x.get("id") == model for x in listed.get("data", [])), "candidate model is not listed by router") + messages = [{"role": "user", "content": "Reply with a short greeting."}] + payload = {"model": model, "messages": messages, "temperature": 0, "max_tokens": 64} + status, reply = request(port, "POST", "/v1/chat/completions", payload, timeout=timeout) + expect("whole_chat", status, 200) + first = check_completion(reply, model) + status, health = request(upstream, "GET", "/health", timeout=timeout) + expect("backend_health", status, 200) + require(health.get("model") == model and health.get("engine") == engine_of(cfg), "backend health model or engine mismatch") + status, listed = request(upstream, "GET", "/v1/models", timeout=timeout) + expect("backend_models", status, 200) + require(any(x.get("id") == model for x in listed.get("data", [])), "backend model mismatch") + second = dict(payload, messages=messages + [{"role": "assistant", "content": first}, + {"role": "user", "content": "Now reply with another short greeting."}]) + status, reply = request(port, "POST", "/v1/chat/completions", second, timeout=timeout) + expect("second_turn", status, 200) + check_completion(reply, model) + status, _ = request(port, "POST", "/v1/chat/completions", dict(payload, stream=True), + timeout=timeout, stream_model=model) + expect("streamed_chat", status, 200) + function = {"type": "function", "function": {"name": "smoke_noop", "parameters": {"type": "object", "properties": {}}}} + status, _ = request(port, "POST", "/v1/chat/completions", dict(payload, tools=[function]), timeout=timeout) + expect("tool_call_rejected", status, 400) + status, _ = request(port, "POST", "/v1/chat/completions", dict(payload, model="missing-smoke-model"), timeout=timeout) + expect("unknown_model_rejected", status, 404) + return {"http_protocol": "PASS", "engine": engine_of(cfg), "checks": checks, + "gpu_qualification": "NOT_RUN", "lifecycle_qualification": "NOT_RUN", + "cuda_free_provenance": "NOT_RUN", + "note": "HTTP checks do not establish GPU correctness, memory budgets, lifecycle or deployed library provenance."} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="action", required=True) + generate = sub.add_parser("config", help="print candidate JSON; starts nothing") + generate.add_argument("--server", required=True) + generate.add_argument("--model-dir", required=True) + generate.add_argument("--data-dir", required=True) + generate.add_argument("--model-id", default="omega-candidate") + generate.add_argument("--engine", choices=("omega", "stub"), default="omega") + generate.add_argument("--resident-bytes", type=int, required=True) + generate.add_argument("--working-bytes", type=int, required=True) + generate.add_argument("--reserve-bytes", type=int, default=8 * 1024**3) + generate.add_argument("--router-port", type=int, default=8192) + generate.add_argument("--backend-port", type=int, default=18092) + for name in ("check", "probe"): + p = sub.add_parser(name, help="check setup without launching any process") + p.add_argument("--config", type=Path, required=True) + if name == "probe": + p.add_argument("--exercise", action="store_true", help="send short generation requests to the running candidate") + p.add_argument("--timeout", type=int, default=180) + args = parser.parse_args(argv) + try: + if args.action == "config": + fields = vars(args).copy() + fields.pop("action") + cfg = make_config(**fields) + check_files(cfg) + print(json.dumps(cfg, indent=2)) + else: + raw = args.config.read_bytes() + cfg = json.loads(raw) + validate_config(cfg) + if args.action == "check": + check_files(cfg) + check_ports(cfg) + result = {"setup": "PASS", "processes_started": 0, "gpu_qualification": "NOT_RUN"} + elif args.exercise: + require(1 <= args.timeout <= 1800, "timeout must be 1..1800 seconds") + result = exercise(cfg, args.timeout) + else: + status, value = request(cfg["port"], "GET", "/v1/models", timeout=10) + require(status == 200 and any(x.get("id") == cfg["tools"][0]["id"] for x in value.get("data", [])), + "candidate model not listed") + result = {"router_listing": "PASS", "generation": "NOT_RUN", "gpu_qualification": "NOT_RUN"} + result["config_sha256"] = hashlib.sha256(raw).hexdigest() + print(json.dumps(result, indent=2)) + return 0 + except (ValueError, KeyError, TypeError, IndexError, AttributeError, OSError, http.client.HTTPException) as exc: + print(f"localrouter setup: FAIL: {exc}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main())