From 6de3cde0a5ac2ff97afbd1d20150f817fd09658c Mon Sep 17 00:00:00 2001 From: Hank Bob Date: Wed, 29 Apr 2026 02:55:43 +0700 Subject: [PATCH 1/3] e2e: add local simulation environment skeleton Introduces scripts/e2e-runner.py, a Python orchestrator that spins up the real coordinator binary with test-friendly configuration (in-memory store, mock billing, no trust requirements) alongside a simulated or real provider, and runs HTTP/WebSocket-level assertions against the live stack. Key components: - Coordinator class: builds and spawns coordinator with EIGENINFERENCE_MIN_TRUST=none, EIGENINFERENCE_BILLING_MOCK=true, and in-memory store - SimulatedProvider: pure-Python WebSocket client speaking the full provider protocol (register, attestation challenge/response, heartbeat, inference request/response) - Test framework: decorator-based test registration, pass/fail summary, signal-safe cleanup via atexit + signal handlers - Test stubs: test_basic (registration + discovery), test_inference (consumer request routing), test_multi_provider (two providers, same model) TODO: - RealProvider wrapper around darkbloom serve --coordinator - Coordination between provider challenge cycle and consumer request timing - API key handling for consumer vs admin routes - Python dependency management (websockets, cryptography) --- scripts/e2e-runner.py | 615 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 615 insertions(+) create mode 100644 scripts/e2e-runner.py diff --git a/scripts/e2e-runner.py b/scripts/e2e-runner.py new file mode 100644 index 0000000000..b2f9038990 --- /dev/null +++ b/scripts/e2e-runner.py @@ -0,0 +1,615 @@ +#!/usr/bin/env python3 +""" +Local E2E test environment for the Darkbloom inference stack. + +Spins up the real coordinator binary with test-friendly settings and one or more +providers (simulated or the real Rust binary), then runs HTTP/WebSocket-level +assertions against the live stack. + +Usage: + # Basic coordinator routing tests (simulated provider, no GPU needed) + python scripts/e2e-runner.py --coordinator-repo ./coordinator test_basic + + # Full stack with real provider (macOS only, needs vllm-mlx) + python scripts/e2e-runner.py --coordinator-repo ./coordinator \ + --provider-binary ./provider/target/release/darkbloom \ + --vllm-model mlx-community/Qwen3.5-0.8B-MLX-4bit \ + test_basic test_inference + + # Run all tests + python scripts/e2e-runner.py --coordinator-repo ./coordinator all +""" + +import argparse +import atexit +import base64 +import json +import os +import random +import signal +import string +import subprocess +import sys +import time +import uuid +from contextlib import contextmanager +from pathlib import Path +from typing import Optional + +# --------------------------------------------------------------------------- +# Configuration constants +# --------------------------------------------------------------------------- + +DEFAULT_COORDINATOR_PORT = 8080 +DEFAULT_ADMIN_KEY = "e2e-test-admin-key-" + "".join(random.choices(string.ascii_lowercase, k=8)) +DEFAULT_BACKEND_PORT_BASE = 18100 +HEARTBEAT_INTERVAL = 2 # seconds +CHALLENGE_INTERVAL = 10 # seconds +PROVIDER_WAIT_TIMEOUT = 15 # seconds +INFERENCE_TIMEOUT = 60 # seconds +TEST_MODEL = "mlx-community/Qwen3.5-0.8B-MLX-4bit" + +# --------------------------------------------------------------------------- +# Process management +# --------------------------------------------------------------------------- + +_processes: list[subprocess.Popen] = [] + + +def _cleanup(): + for p in reversed(_processes): + try: + p.terminate() + except Exception: + pass + for p in reversed(_processes): + try: + p.wait(timeout=5) + except subprocess.TimeoutExpired: + try: + p.kill() + p.wait(timeout=2) + except Exception: + pass + + +def _handle_signal(signum, frame): + _cleanup() + sys.exit(128 + signum) + + +signal.signal(signal.SIGINT, _handle_signal) +signal.signal(signal.SIGTERM, _handle_signal) +atexit.register(_cleanup) + + +def spawn(args: list[str], env: Optional[dict] = None, cwd: Optional[str] = None, + label: str = "") -> subprocess.Popen: + """Start a child process tracked for cleanup.""" + merged = os.environ.copy() + if env: + merged.update(env) + print(f"[e2e] starting {label or args[0]}: {' '.join(args)}") + p = subprocess.Popen(args, env=merged, cwd=cwd) + _processes.append(p) + return p + + +def wait_for_log(p: subprocess.Popen, pattern: str, timeout: float = 30) -> bool: + """Read stderr/stdout until pattern appears or timeout expires.""" + # Simple polling via the process output — in production we'd use + # async IO or pexpect, but this is a skeleton. + deadline = time.time() + timeout + buf = b"" + while time.time() < deadline and p.poll() is None: + try: + line = p.stderr.readline() if p.stderr else b"" + buf += line + if pattern.encode() in line: + return True + except Exception: + time.sleep(0.1) + return pattern.encode() in buf + + +def wait_for_http(url: str, timeout: float = 15) -> bool: + """Poll an HTTP endpoint until it returns 200.""" + import urllib.request + deadline = time.time() + timeout + while time.time() < deadline: + try: + resp = urllib.request.urlopen(url, timeout=2) + return resp.status == 200 + except Exception: + time.sleep(0.5) + return False + + +# --------------------------------------------------------------------------- +# Test result tracking +# --------------------------------------------------------------------------- + +_tests_run = 0 +_tests_passed = 0 +_tests_failed = 0 + + +def test(name: str): + """Decorator to register a test function.""" + def decorator(fn): + _tests.append((name, fn)) + return fn + return decorator + + +_tests: list[tuple[str, callable]] = [] + + +def run_tests(names: list[str]): + """Run registered tests matching the given names (or 'all').""" + global _tests_run, _tests_passed, _tests_failed + for name, fn in _tests: + if "all" not in names and name not in names: + continue + _tests_run += 1 + print(f"\n{'='*60}") + print(f"[e2e] TEST: {name}") + print(f"{'='*60}") + try: + fn() + _tests_passed += 1 + print(f"[e2e] PASS: {name}") + except Exception as e: + _tests_failed += 1 + print(f"[e2e] FAIL: {name} — {e}") + import traceback + traceback.print_exc() + + +def summarize(): + total = _tests_passed + _tests_failed + print(f"\n{'='*60}") + print(f"[e2e] RESULTS: {_tests_passed}/{total} passed, {_tests_failed} failed") + print(f"{'='*60}") + return _tests_failed == 0 + + +# --------------------------------------------------------------------------- +# Coordinator +# --------------------------------------------------------------------------- + +class Coordinator: + """Manages the real coordinator binary.""" + + def __init__(self, repo_path: str, port: int = DEFAULT_COORDINATOR_PORT, + admin_key: str = DEFAULT_ADMIN_KEY): + self.repo = Path(repo_path).resolve() + self.port = port + self.admin_key = admin_key + self.process: Optional[subprocess.Popen] = None + + @property + def base_url(self) -> str: + return f"http://localhost:{self.port}" + + @property + def ws_url(self) -> str: + return f"ws://localhost:{self.port}/ws/provider" + + def start(self): + # Build if needed — in production we'd check binary freshness + binary = self.repo / "coordinator" + if not binary.exists(): + print("[e2e] building coordinator...") + subprocess.run(["go", "build", "-o", "coordinator", "./cmd/coordinator"], + cwd=self.repo, check=True, capture_output=True) + + env = { + "EIGENINFERENCE_PORT": str(self.port), + "EIGENINFERENCE_ADMIN_KEY": self.admin_key, + # No DATABASE_URL → in-memory store + "EIGENINFERENCE_MIN_TRUST": "none", # bypass all trust/attestation + "EIGENINFERENCE_BILLING_MOCK": "true", # skip Solana/Stripe + "EIGENINFERENCE_CONSOLE_URL": f"http://localhost:{self.port}", + } + self.process = spawn( + [str(binary)], + env=env, + cwd=str(self.repo), + label="coordinator", + ) + + # Wait for server to be ready + if not wait_for_http(f"{self.base_url}/v1/models", timeout=15): + raise RuntimeError("coordinator failed to start") + + print(f"[e2e] coordinator ready at {self.base_url}") + + def stop(self): + if self.process and self.process.poll() is None: + self.process.terminate() + self.process.wait(timeout=10) + self.process = None + + def api_call(self, method: str, path: str, body: Optional[dict] = None, + api_key: Optional[str] = None) -> tuple[int, dict]: + """Make an HTTP call to the coordinator API.""" + import urllib.request + url = f"{self.base_url}{path}" + data = json.dumps(body).encode() if body else None + req = urllib.request.Request(url, data=data, method=method) + req.add_header("Content-Type", "application/json") + if api_key: + req.add_header("Authorization", f"Bearer {api_key}") + try: + resp = urllib.request.urlopen(req, timeout=10) + return resp.status, json.loads(resp.read()) + except urllib.request.HTTPError as e: + body_text = e.read().decode() + try: + return e.code, json.loads(body_text) + except json.JSONDecodeError: + return e.code, {"error": body_text} + + +# --------------------------------------------------------------------------- +# Simulated Provider (Go-free, Python-based WebSocket client) +# --------------------------------------------------------------------------- + +class SimulatedProvider: + """ + A Python WebSocket client that speaks the Darkbloom provider protocol. + Sends register → handles attestation challenges → sends heartbeats → + responds to inference requests with fake streaming chunks. + + This exercises the coordinator's full control-plane code paths without + needing the real Rust binary or a GPU backend. + """ + + def __init__(self, coordinator_url: str, model: str = TEST_MODEL, + name: str = "sim-provider", backend_port: int = DEFAULT_BACKEND_PORT_BASE): + self.coordinator_url = coordinator_url + self.model = model + self.name = name + self.backend_port = backend_port + self.ws = None + self.public_key_b64 = "" + self.private_key_bytes = None + self._stop = False + + def start(self): + """Connect to the coordinator and register as a provider.""" + import websockets.sync.client as ws_client + from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey + + # Generate an X25519 key pair (matching the protocol) + private_key = X25519PrivateKey.generate() + public_key = private_key.public_key() + from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat + self.public_key_b64 = base64.b64encode( + public_key.public_bytes(Encoding.Raw, PublicFormat.Raw) + ).decode() + self.private_key_bytes = private_key.private_bytes_raw() + + self.ws = ws_client.connect(self.coordinator_url) + self.ws.settimeout(5) + + # Register + reg = { + "type": "register", + "hardware": { + "machine_model": "Mac15,8", + "chip_name": "Apple M3 Max", + "memory_gb": 128, + "memory_available_gb": 124.0, + "cpu_cores": {"total": 16, "performance": 12, "efficiency": 4}, + "gpu_cores": 40, + "memory_bandwidth_gbs": 400.0, + }, + "models": [{ + "id": self.model, + "model_type": "chat", + "quantization": "4bit", + "size_bytes": 500_000_000, + }], + "backend": "vllm-mlx", + "public_key": self.public_key_b64, + "decode_tps": 100.0, + "version": "0.2.99-e2e", + } + self.ws.send(json.dumps(reg)) + print(f"[e2e] simulated provider '{self.name}' registered") + + def run_loop(self): + """Run the message loop until told to stop.""" + while not self._stop: + try: + data = self.ws.recv() + except Exception: + break + if not data: + break + msg = json.loads(data) + self._handle(msg) + + def _handle(self, msg: dict): + msg_type = msg.get("type", "") + + if msg_type == "attestation_challenge": + # Respond with a SHA-256 "signature" (matching the real provider's + # current implementation before SE integration) + nonce = msg.get("nonce", "") + timestamp = msg.get("timestamp", "") + sig_data = nonce + timestamp + self.public_key_b64 + import hashlib + signature = base64.b64encode( + hashlib.sha256(sig_data.encode()).digest() + ).decode() + + resp = { + "type": "attestation_response", + "nonce": nonce, + "signature": signature, + "public_key": self.public_key_b64, + "hypervisor_active": False, + "rdma_disabled": True, + "sip_enabled": True, + "secure_boot_enabled": True, + "binary_hash": "e2e-test-binary-hash", + } + self.ws.send(json.dumps(resp)) + + elif msg_type == "inference_request": + request_id = msg.get("request_id", "") + body = msg.get("body", {}) + stream = body.get("stream", True) + self._serve_inference(request_id, stream) + + elif msg_type == "runtime_status": + pass # acknowledged + + def _serve_inference(self, request_id: str, stream: bool): + """Respond with fake streaming chunks and a complete message.""" + # Stream chunks + if stream: + for word in ["Hello", " world", " from", " e2e"]: + chunk = { + "type": "inference_response_chunk", + "request_id": request_id, + "data": f"data: {json.dumps({ + 'id': f'chatcmpl-e2e-{request_id}', + 'choices': [{'delta': {'content': word}}], + })}\n\n", + } + self.ws.send(json.dumps(chunk)) + time.sleep(0.05) + + # Complete + complete = { + "type": "inference_complete", + "request_id": request_id, + "usage": {"prompt_tokens": 10, "completion_tokens": 5}, + } + self.ws.send(json.dumps(complete)) + + def stop(self): + self._stop = True + if self.ws: + try: + self.ws.close() + except Exception: + pass + self.ws = None + + +# --------------------------------------------------------------------------- +# Test scenarios +# --------------------------------------------------------------------------- + + +def _start_env(coordinator_repo: str, provider_type: str = "simulated", + provider_binary: Optional[str] = None, vllm_model: Optional[str] = None): + """Start coordinator and provider, yield test context, tear down.""" + coord = Coordinator(coordinator_repo) + coord.start() + + providers = [] + + if provider_type == "simulated": + p = SimulatedProvider( + coordinator_url=coord.ws_url, + model=vllm_model or TEST_MODEL, + ) + p.start() + providers.append(p) + + elif provider_type == "real": + # TODO(Ethan): implement RealProvider wrapper around darkbloom serve + # This needs: + # 1. Build provider binary with `cargo build --release` + # 2. Generate a TOML config or pass --model --coordinator --no-auto-update + # 3. Wait for "Connected to coordinator" in logs + # 4. Handle non-zero exit codes + raise NotImplementedError("RealProvider not yet implemented") + + # Wait for first heartbeat to be processed + time.sleep(HEARTBEAT_INTERVAL * 2) + + try: + yield coord, providers + finally: + for p in providers: + p.stop() + coord.stop() + + +# --- Test: Basic Provider Connectivity --- + +@test("test_basic") +def test_basic(): + """Verify a simulated provider can register and the coordinator can see it.""" + import urllib.request + + coord = Coordinator(Path(sys.argv[0]).resolve().parent.parent / "coordinator") + coord.start() + + try: + p = SimulatedProvider(coordinator_url=coord.ws_url) + p.start() + p_run_result = {"done": False} + + import threading + def run_loop(): + p.run_loop() + p_run_result["done"] = True + + t = threading.Thread(target=run_loop, daemon=True) + t.start() + + time.sleep(3) + + # Check provider is visible in stats + status, body = coord.api_call("GET", "/v1/models") + assert status == 200, f"/v1/models returned {status}: {body}" + models = body.get("data", []) + print(f"[e2e] models visible: {[m['id'] for m in models]}") + + p.stop() + finally: + coord.stop() + + +# --- Test: Streamed Inference --- + +@test("test_inference") +def test_inference(): + """Send a consumer chat request and verify streamed tokens come back.""" + coord = Coordinator(Path(sys.argv[0]).resolve().parent.parent / "coordinator") + coord.start() + + try: + p = SimulatedProvider(coordinator_url=coord.ws_url) + p.start() + + import threading + t = threading.Thread(target=p.run_loop, daemon=True) + t.start() + + time.sleep(3) + + # TODO(Ethan): The coordinator requires the provider to be trusted/accepted + # before routing. In "none" trust mode this should happen automatically + # after the first challenge-response. We need to: + # 1. Wait for the provider status to be routable + # 2. Then send the consumer request + status, body = coord.api_call( + "POST", "/v1/chat/completions", + body={ + "model": TEST_MODEL, + "messages": [{"role": "user", "content": "hello"}], + "stream": True, + }, + api_key=DEFAULT_ADMIN_KEY, + ) + print(f"[e2e] inference response: status={status}") + if status != 200: + print(f"[e2e] body={json.dumps(body, indent=2)}") + + p.stop() + finally: + coord.stop() + + +# --- Test: Multi-Provider Routing --- + +@test("test_multi_provider") +def test_multi_provider(): + """Register two providers, verify both are discoverable.""" + coord = Coordinator(Path(sys.argv[0]).resolve().parent.parent / "coordinator") + coord.start() + + try: + providers = [ + SimulatedProvider(coordinator_url=coord.ws_url, name=f"sim-{i}", + model=TEST_MODEL) + for i in range(2) + ] + + threads = [] + for p in providers: + p.start() + t = threading.Thread(target=p.run_loop, daemon=True) + t.start() + threads.append(t) + + time.sleep(3) + + status, body = coord.api_call("GET", "/v1/models") + assert status == 200, f"GET /v1/models: {status}" + print(f"[e2e] models visible after multi-provider: " + f"{[m['id'] for m in body.get('data', [])]}") + + for p in providers: + p.stop() + finally: + coord.stop() + + +# --------------------------------------------------------------------------- +# CLI entry point +# --------------------------------------------------------------------------- + +def main(): + parser = argparse.ArgumentParser( + description="Darkbloom E2E test environment", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Available tests: + all Run all tests + test_basic Verify provider registration and discovery + test_inference Full consumer → coordinator → provider → response + test_multi_provider Two providers on the same model + +Examples: + # Quick coordinator test (no GPU, works anywhere) + python scripts/e2e-runner.py --coordinator-repo ./coordinator test_basic + + # Full stack with real provider (macOS) + python scripts/e2e-runner.py --coordinator-repo ./coordinator \\ + --provider-binary ./provider/target/release/darkbloom \\ + --vllm-model mlx-community/Qwen3.5-0.8B-MLX-4bit \\ + test_inference + + # All tests + python scripts/e2e-runner.py --coordinator-repo ./coordinator all +""") + parser.add_argument("--coordinator-repo", required=True, + help="Path to coordinator/ directory") + parser.add_argument("--provider-binary", + help="Path to darkbloom provider binary (macOS only)") + parser.add_argument("--vllm-model", default=TEST_MODEL, + help="Model to register providers with") + parser.add_argument("tests", nargs="+", + help="Test names to run (or 'all')") + + args = parser.parse_args() + + # Resolve coordinator path + args.coordinator_repo = os.path.abspath(args.coordinator_repo) + print(f"[e2e] coordinator repo: {args.coordinator_repo}") + print(f"[e2e] provider binary: {args.provider_binary or '(simulated)'}") + print(f"[e2e] model: {args.vllm_model}") + + # TODO(Ethan): + # - Check that coordinator_repo has a go.mod + # - Check that coordinator binary builds + # - Validate provider binary path if specified + # - Check for required Python deps (websockets, cryptography) + + run_tests(args.tests) + success = summarize() + sys.exit(0 if success else 1) + + +if __name__ == "__main__": + main() \ No newline at end of file From e0c9e933b9d6aaf7441b29a99d44319da5963215 Mon Sep 17 00:00:00 2001 From: Hank Bob Date: Wed, 29 Apr 2026 03:25:38 +0700 Subject: [PATCH 2/3] Revert "e2e: add local simulation environment skeleton" This reverts commit d02074e3. The Python E2E runner adds noise on top of the existing Go integration tests (internal/api/integration_test.go + fullstack_integration_test.go) which already cover the full coordinator protocol surface. The cross-language orchestration doesn't buy anything over what httptest.Server + simulated providers already provide. --- scripts/e2e-runner.py | 615 ------------------------------------------ 1 file changed, 615 deletions(-) delete mode 100644 scripts/e2e-runner.py diff --git a/scripts/e2e-runner.py b/scripts/e2e-runner.py deleted file mode 100644 index b2f9038990..0000000000 --- a/scripts/e2e-runner.py +++ /dev/null @@ -1,615 +0,0 @@ -#!/usr/bin/env python3 -""" -Local E2E test environment for the Darkbloom inference stack. - -Spins up the real coordinator binary with test-friendly settings and one or more -providers (simulated or the real Rust binary), then runs HTTP/WebSocket-level -assertions against the live stack. - -Usage: - # Basic coordinator routing tests (simulated provider, no GPU needed) - python scripts/e2e-runner.py --coordinator-repo ./coordinator test_basic - - # Full stack with real provider (macOS only, needs vllm-mlx) - python scripts/e2e-runner.py --coordinator-repo ./coordinator \ - --provider-binary ./provider/target/release/darkbloom \ - --vllm-model mlx-community/Qwen3.5-0.8B-MLX-4bit \ - test_basic test_inference - - # Run all tests - python scripts/e2e-runner.py --coordinator-repo ./coordinator all -""" - -import argparse -import atexit -import base64 -import json -import os -import random -import signal -import string -import subprocess -import sys -import time -import uuid -from contextlib import contextmanager -from pathlib import Path -from typing import Optional - -# --------------------------------------------------------------------------- -# Configuration constants -# --------------------------------------------------------------------------- - -DEFAULT_COORDINATOR_PORT = 8080 -DEFAULT_ADMIN_KEY = "e2e-test-admin-key-" + "".join(random.choices(string.ascii_lowercase, k=8)) -DEFAULT_BACKEND_PORT_BASE = 18100 -HEARTBEAT_INTERVAL = 2 # seconds -CHALLENGE_INTERVAL = 10 # seconds -PROVIDER_WAIT_TIMEOUT = 15 # seconds -INFERENCE_TIMEOUT = 60 # seconds -TEST_MODEL = "mlx-community/Qwen3.5-0.8B-MLX-4bit" - -# --------------------------------------------------------------------------- -# Process management -# --------------------------------------------------------------------------- - -_processes: list[subprocess.Popen] = [] - - -def _cleanup(): - for p in reversed(_processes): - try: - p.terminate() - except Exception: - pass - for p in reversed(_processes): - try: - p.wait(timeout=5) - except subprocess.TimeoutExpired: - try: - p.kill() - p.wait(timeout=2) - except Exception: - pass - - -def _handle_signal(signum, frame): - _cleanup() - sys.exit(128 + signum) - - -signal.signal(signal.SIGINT, _handle_signal) -signal.signal(signal.SIGTERM, _handle_signal) -atexit.register(_cleanup) - - -def spawn(args: list[str], env: Optional[dict] = None, cwd: Optional[str] = None, - label: str = "") -> subprocess.Popen: - """Start a child process tracked for cleanup.""" - merged = os.environ.copy() - if env: - merged.update(env) - print(f"[e2e] starting {label or args[0]}: {' '.join(args)}") - p = subprocess.Popen(args, env=merged, cwd=cwd) - _processes.append(p) - return p - - -def wait_for_log(p: subprocess.Popen, pattern: str, timeout: float = 30) -> bool: - """Read stderr/stdout until pattern appears or timeout expires.""" - # Simple polling via the process output — in production we'd use - # async IO or pexpect, but this is a skeleton. - deadline = time.time() + timeout - buf = b"" - while time.time() < deadline and p.poll() is None: - try: - line = p.stderr.readline() if p.stderr else b"" - buf += line - if pattern.encode() in line: - return True - except Exception: - time.sleep(0.1) - return pattern.encode() in buf - - -def wait_for_http(url: str, timeout: float = 15) -> bool: - """Poll an HTTP endpoint until it returns 200.""" - import urllib.request - deadline = time.time() + timeout - while time.time() < deadline: - try: - resp = urllib.request.urlopen(url, timeout=2) - return resp.status == 200 - except Exception: - time.sleep(0.5) - return False - - -# --------------------------------------------------------------------------- -# Test result tracking -# --------------------------------------------------------------------------- - -_tests_run = 0 -_tests_passed = 0 -_tests_failed = 0 - - -def test(name: str): - """Decorator to register a test function.""" - def decorator(fn): - _tests.append((name, fn)) - return fn - return decorator - - -_tests: list[tuple[str, callable]] = [] - - -def run_tests(names: list[str]): - """Run registered tests matching the given names (or 'all').""" - global _tests_run, _tests_passed, _tests_failed - for name, fn in _tests: - if "all" not in names and name not in names: - continue - _tests_run += 1 - print(f"\n{'='*60}") - print(f"[e2e] TEST: {name}") - print(f"{'='*60}") - try: - fn() - _tests_passed += 1 - print(f"[e2e] PASS: {name}") - except Exception as e: - _tests_failed += 1 - print(f"[e2e] FAIL: {name} — {e}") - import traceback - traceback.print_exc() - - -def summarize(): - total = _tests_passed + _tests_failed - print(f"\n{'='*60}") - print(f"[e2e] RESULTS: {_tests_passed}/{total} passed, {_tests_failed} failed") - print(f"{'='*60}") - return _tests_failed == 0 - - -# --------------------------------------------------------------------------- -# Coordinator -# --------------------------------------------------------------------------- - -class Coordinator: - """Manages the real coordinator binary.""" - - def __init__(self, repo_path: str, port: int = DEFAULT_COORDINATOR_PORT, - admin_key: str = DEFAULT_ADMIN_KEY): - self.repo = Path(repo_path).resolve() - self.port = port - self.admin_key = admin_key - self.process: Optional[subprocess.Popen] = None - - @property - def base_url(self) -> str: - return f"http://localhost:{self.port}" - - @property - def ws_url(self) -> str: - return f"ws://localhost:{self.port}/ws/provider" - - def start(self): - # Build if needed — in production we'd check binary freshness - binary = self.repo / "coordinator" - if not binary.exists(): - print("[e2e] building coordinator...") - subprocess.run(["go", "build", "-o", "coordinator", "./cmd/coordinator"], - cwd=self.repo, check=True, capture_output=True) - - env = { - "EIGENINFERENCE_PORT": str(self.port), - "EIGENINFERENCE_ADMIN_KEY": self.admin_key, - # No DATABASE_URL → in-memory store - "EIGENINFERENCE_MIN_TRUST": "none", # bypass all trust/attestation - "EIGENINFERENCE_BILLING_MOCK": "true", # skip Solana/Stripe - "EIGENINFERENCE_CONSOLE_URL": f"http://localhost:{self.port}", - } - self.process = spawn( - [str(binary)], - env=env, - cwd=str(self.repo), - label="coordinator", - ) - - # Wait for server to be ready - if not wait_for_http(f"{self.base_url}/v1/models", timeout=15): - raise RuntimeError("coordinator failed to start") - - print(f"[e2e] coordinator ready at {self.base_url}") - - def stop(self): - if self.process and self.process.poll() is None: - self.process.terminate() - self.process.wait(timeout=10) - self.process = None - - def api_call(self, method: str, path: str, body: Optional[dict] = None, - api_key: Optional[str] = None) -> tuple[int, dict]: - """Make an HTTP call to the coordinator API.""" - import urllib.request - url = f"{self.base_url}{path}" - data = json.dumps(body).encode() if body else None - req = urllib.request.Request(url, data=data, method=method) - req.add_header("Content-Type", "application/json") - if api_key: - req.add_header("Authorization", f"Bearer {api_key}") - try: - resp = urllib.request.urlopen(req, timeout=10) - return resp.status, json.loads(resp.read()) - except urllib.request.HTTPError as e: - body_text = e.read().decode() - try: - return e.code, json.loads(body_text) - except json.JSONDecodeError: - return e.code, {"error": body_text} - - -# --------------------------------------------------------------------------- -# Simulated Provider (Go-free, Python-based WebSocket client) -# --------------------------------------------------------------------------- - -class SimulatedProvider: - """ - A Python WebSocket client that speaks the Darkbloom provider protocol. - Sends register → handles attestation challenges → sends heartbeats → - responds to inference requests with fake streaming chunks. - - This exercises the coordinator's full control-plane code paths without - needing the real Rust binary or a GPU backend. - """ - - def __init__(self, coordinator_url: str, model: str = TEST_MODEL, - name: str = "sim-provider", backend_port: int = DEFAULT_BACKEND_PORT_BASE): - self.coordinator_url = coordinator_url - self.model = model - self.name = name - self.backend_port = backend_port - self.ws = None - self.public_key_b64 = "" - self.private_key_bytes = None - self._stop = False - - def start(self): - """Connect to the coordinator and register as a provider.""" - import websockets.sync.client as ws_client - from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey - - # Generate an X25519 key pair (matching the protocol) - private_key = X25519PrivateKey.generate() - public_key = private_key.public_key() - from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat - self.public_key_b64 = base64.b64encode( - public_key.public_bytes(Encoding.Raw, PublicFormat.Raw) - ).decode() - self.private_key_bytes = private_key.private_bytes_raw() - - self.ws = ws_client.connect(self.coordinator_url) - self.ws.settimeout(5) - - # Register - reg = { - "type": "register", - "hardware": { - "machine_model": "Mac15,8", - "chip_name": "Apple M3 Max", - "memory_gb": 128, - "memory_available_gb": 124.0, - "cpu_cores": {"total": 16, "performance": 12, "efficiency": 4}, - "gpu_cores": 40, - "memory_bandwidth_gbs": 400.0, - }, - "models": [{ - "id": self.model, - "model_type": "chat", - "quantization": "4bit", - "size_bytes": 500_000_000, - }], - "backend": "vllm-mlx", - "public_key": self.public_key_b64, - "decode_tps": 100.0, - "version": "0.2.99-e2e", - } - self.ws.send(json.dumps(reg)) - print(f"[e2e] simulated provider '{self.name}' registered") - - def run_loop(self): - """Run the message loop until told to stop.""" - while not self._stop: - try: - data = self.ws.recv() - except Exception: - break - if not data: - break - msg = json.loads(data) - self._handle(msg) - - def _handle(self, msg: dict): - msg_type = msg.get("type", "") - - if msg_type == "attestation_challenge": - # Respond with a SHA-256 "signature" (matching the real provider's - # current implementation before SE integration) - nonce = msg.get("nonce", "") - timestamp = msg.get("timestamp", "") - sig_data = nonce + timestamp + self.public_key_b64 - import hashlib - signature = base64.b64encode( - hashlib.sha256(sig_data.encode()).digest() - ).decode() - - resp = { - "type": "attestation_response", - "nonce": nonce, - "signature": signature, - "public_key": self.public_key_b64, - "hypervisor_active": False, - "rdma_disabled": True, - "sip_enabled": True, - "secure_boot_enabled": True, - "binary_hash": "e2e-test-binary-hash", - } - self.ws.send(json.dumps(resp)) - - elif msg_type == "inference_request": - request_id = msg.get("request_id", "") - body = msg.get("body", {}) - stream = body.get("stream", True) - self._serve_inference(request_id, stream) - - elif msg_type == "runtime_status": - pass # acknowledged - - def _serve_inference(self, request_id: str, stream: bool): - """Respond with fake streaming chunks and a complete message.""" - # Stream chunks - if stream: - for word in ["Hello", " world", " from", " e2e"]: - chunk = { - "type": "inference_response_chunk", - "request_id": request_id, - "data": f"data: {json.dumps({ - 'id': f'chatcmpl-e2e-{request_id}', - 'choices': [{'delta': {'content': word}}], - })}\n\n", - } - self.ws.send(json.dumps(chunk)) - time.sleep(0.05) - - # Complete - complete = { - "type": "inference_complete", - "request_id": request_id, - "usage": {"prompt_tokens": 10, "completion_tokens": 5}, - } - self.ws.send(json.dumps(complete)) - - def stop(self): - self._stop = True - if self.ws: - try: - self.ws.close() - except Exception: - pass - self.ws = None - - -# --------------------------------------------------------------------------- -# Test scenarios -# --------------------------------------------------------------------------- - - -def _start_env(coordinator_repo: str, provider_type: str = "simulated", - provider_binary: Optional[str] = None, vllm_model: Optional[str] = None): - """Start coordinator and provider, yield test context, tear down.""" - coord = Coordinator(coordinator_repo) - coord.start() - - providers = [] - - if provider_type == "simulated": - p = SimulatedProvider( - coordinator_url=coord.ws_url, - model=vllm_model or TEST_MODEL, - ) - p.start() - providers.append(p) - - elif provider_type == "real": - # TODO(Ethan): implement RealProvider wrapper around darkbloom serve - # This needs: - # 1. Build provider binary with `cargo build --release` - # 2. Generate a TOML config or pass --model --coordinator --no-auto-update - # 3. Wait for "Connected to coordinator" in logs - # 4. Handle non-zero exit codes - raise NotImplementedError("RealProvider not yet implemented") - - # Wait for first heartbeat to be processed - time.sleep(HEARTBEAT_INTERVAL * 2) - - try: - yield coord, providers - finally: - for p in providers: - p.stop() - coord.stop() - - -# --- Test: Basic Provider Connectivity --- - -@test("test_basic") -def test_basic(): - """Verify a simulated provider can register and the coordinator can see it.""" - import urllib.request - - coord = Coordinator(Path(sys.argv[0]).resolve().parent.parent / "coordinator") - coord.start() - - try: - p = SimulatedProvider(coordinator_url=coord.ws_url) - p.start() - p_run_result = {"done": False} - - import threading - def run_loop(): - p.run_loop() - p_run_result["done"] = True - - t = threading.Thread(target=run_loop, daemon=True) - t.start() - - time.sleep(3) - - # Check provider is visible in stats - status, body = coord.api_call("GET", "/v1/models") - assert status == 200, f"/v1/models returned {status}: {body}" - models = body.get("data", []) - print(f"[e2e] models visible: {[m['id'] for m in models]}") - - p.stop() - finally: - coord.stop() - - -# --- Test: Streamed Inference --- - -@test("test_inference") -def test_inference(): - """Send a consumer chat request and verify streamed tokens come back.""" - coord = Coordinator(Path(sys.argv[0]).resolve().parent.parent / "coordinator") - coord.start() - - try: - p = SimulatedProvider(coordinator_url=coord.ws_url) - p.start() - - import threading - t = threading.Thread(target=p.run_loop, daemon=True) - t.start() - - time.sleep(3) - - # TODO(Ethan): The coordinator requires the provider to be trusted/accepted - # before routing. In "none" trust mode this should happen automatically - # after the first challenge-response. We need to: - # 1. Wait for the provider status to be routable - # 2. Then send the consumer request - status, body = coord.api_call( - "POST", "/v1/chat/completions", - body={ - "model": TEST_MODEL, - "messages": [{"role": "user", "content": "hello"}], - "stream": True, - }, - api_key=DEFAULT_ADMIN_KEY, - ) - print(f"[e2e] inference response: status={status}") - if status != 200: - print(f"[e2e] body={json.dumps(body, indent=2)}") - - p.stop() - finally: - coord.stop() - - -# --- Test: Multi-Provider Routing --- - -@test("test_multi_provider") -def test_multi_provider(): - """Register two providers, verify both are discoverable.""" - coord = Coordinator(Path(sys.argv[0]).resolve().parent.parent / "coordinator") - coord.start() - - try: - providers = [ - SimulatedProvider(coordinator_url=coord.ws_url, name=f"sim-{i}", - model=TEST_MODEL) - for i in range(2) - ] - - threads = [] - for p in providers: - p.start() - t = threading.Thread(target=p.run_loop, daemon=True) - t.start() - threads.append(t) - - time.sleep(3) - - status, body = coord.api_call("GET", "/v1/models") - assert status == 200, f"GET /v1/models: {status}" - print(f"[e2e] models visible after multi-provider: " - f"{[m['id'] for m in body.get('data', [])]}") - - for p in providers: - p.stop() - finally: - coord.stop() - - -# --------------------------------------------------------------------------- -# CLI entry point -# --------------------------------------------------------------------------- - -def main(): - parser = argparse.ArgumentParser( - description="Darkbloom E2E test environment", - formatter_class=argparse.RawDescriptionHelpFormatter, - epilog=""" -Available tests: - all Run all tests - test_basic Verify provider registration and discovery - test_inference Full consumer → coordinator → provider → response - test_multi_provider Two providers on the same model - -Examples: - # Quick coordinator test (no GPU, works anywhere) - python scripts/e2e-runner.py --coordinator-repo ./coordinator test_basic - - # Full stack with real provider (macOS) - python scripts/e2e-runner.py --coordinator-repo ./coordinator \\ - --provider-binary ./provider/target/release/darkbloom \\ - --vllm-model mlx-community/Qwen3.5-0.8B-MLX-4bit \\ - test_inference - - # All tests - python scripts/e2e-runner.py --coordinator-repo ./coordinator all -""") - parser.add_argument("--coordinator-repo", required=True, - help="Path to coordinator/ directory") - parser.add_argument("--provider-binary", - help="Path to darkbloom provider binary (macOS only)") - parser.add_argument("--vllm-model", default=TEST_MODEL, - help="Model to register providers with") - parser.add_argument("tests", nargs="+", - help="Test names to run (or 'all')") - - args = parser.parse_args() - - # Resolve coordinator path - args.coordinator_repo = os.path.abspath(args.coordinator_repo) - print(f"[e2e] coordinator repo: {args.coordinator_repo}") - print(f"[e2e] provider binary: {args.provider_binary or '(simulated)'}") - print(f"[e2e] model: {args.vllm_model}") - - # TODO(Ethan): - # - Check that coordinator_repo has a go.mod - # - Check that coordinator binary builds - # - Validate provider binary path if specified - # - Check for required Python deps (websockets, cryptography) - - run_tests(args.tests) - success = summarize() - sys.exit(0 if success else 1) - - -if __name__ == "__main__": - main() \ No newline at end of file From 21d3ed0728b2e6a606def155090106456d27cbf8 Mon Sep 17 00:00:00 2001 From: hankbobtheresearchoor Date: Wed, 29 Apr 2026 03:40:46 +0700 Subject: [PATCH 3/3] Remove stale Python integration test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit @ethenotethan tests/integration_test.py is superseded by the Go-based coordinator integration tests at coordinator/internal/api/: - Test coverage for coordinator protocol (register, challenge, heartbeat, inference) is covered by integration_test.go using httptest.Server + Go simulated providers — same coverage, no binary build needed - Full-stack GPU inference is covered by fullstack_integration_test.go with real vllm-mlx backends (gated behind LIVE_FULLSTACK_TEST=1) - The Python test uses stale binary names ('eigeninference-provider'), old flags ('--backend mlx-lm'), and predates attestation challenges, E2E encryption, and the vllm-mlx backend migration - No external dependency coverage (Postgres, Stripe, etc.) is lost — the coordinator main.go wiring for those is trivially tested elsewhere - The Python SDK tests (4.5.x) belong in the SDK repo, not the infra repo --- tests/integration_test.py | 684 -------------------------------------- 1 file changed, 684 deletions(-) delete mode 100644 tests/integration_test.py diff --git a/tests/integration_test.py b/tests/integration_test.py deleted file mode 100644 index 4ad23fe3de..0000000000 --- a/tests/integration_test.py +++ /dev/null @@ -1,684 +0,0 @@ -#!/usr/bin/env python3 -""" -EigenInference Integration Test Suite — Component 4 - -Tests the full loop: Consumer SDK → Coordinator → Provider Agent → mlx-lm → MLX → GPU - -Test groups: - 4.1 — Full inference loop (real model, real GPU) - 4.2 — Streaming inference - 4.3 — Coordinator infrastructure (auth, routing, models) - 4.4 — Provider agent (hardware detection, model scanning) - 4.5 — Failure scenarios (no provider, backend crash, reconnect) - -Prerequisites: - - Coordinator binary: coordinator/bin/coordinator - - Provider binary: provider/target/release/eigeninference-provider - - SDK installed: pip install -e sdk/ - - mlx-lm installed: pip install mlx-lm - - Model downloaded: mlx-community/Qwen3.5-4B-MLX-4bit -""" - -import atexit -import json -import os -import signal -import subprocess -import sys -import time -import traceback - -import httpx - -sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "sdk")) - -# --- Config --- -BASE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.join(BASE, "..") -COORDINATOR_BIN = os.path.join(ROOT, "coordinator", "bin", "coordinator") -PROVIDER_BIN = os.path.join(ROOT, "provider", "target", "release", "eigeninference-provider") -MODEL = "mlx-community/Qwen3.5-4B-MLX-4bit" - -COORDINATOR_PORT = 18080 -BACKEND_PORT = 18100 -ADMIN_KEY = "test-admin-key-integration" -COORDINATOR_URL = f"http://localhost:{COORDINATOR_PORT}" -COORDINATOR_WS = f"ws://localhost:{COORDINATOR_PORT}/ws/provider" - -processes = [] -passed = 0 -failed = 0 -skipped = 0 - - -# --- Process management --- - -def spawn(cmd, env=None, label="process"): - merged = os.environ.copy() - if env: - merged.update(env) - p = subprocess.Popen( - cmd, env=merged, - stdout=subprocess.PIPE, stderr=subprocess.PIPE, - ) - processes.append(p) - return p - - -def cleanup(): - for p in processes: - try: - p.terminate() - p.wait(timeout=5) - except Exception: - try: - p.kill() - p.wait(timeout=2) - except Exception: - pass - processes.clear() - - -atexit.register(cleanup) - - -def wait_for_http(url, timeout=60, interval=0.5): - for _ in range(int(timeout / interval)): - try: - r = httpx.get(url, timeout=2) - if r.status_code == 200: - return True - except Exception: - pass - time.sleep(interval) - return False - - -# --- Test infrastructure --- - -def run_test(name, fn): - global passed, failed, skipped - try: - fn() - passed += 1 - print(f" PASS: {name}") - except SkipTest as e: - skipped += 1 - print(f" SKIP: {name} — {e}") - except Exception as e: - failed += 1 - print(f" FAIL: {name} — {e}") - traceback.print_exc() - - -class SkipTest(Exception): - pass - - -# --- Start services --- - -def start_coordinator(): - p = spawn( - [COORDINATOR_BIN], - env={"EIGENINFERENCE_PORT": str(COORDINATOR_PORT), "EIGENINFERENCE_ADMIN_KEY": ADMIN_KEY}, - label="coordinator", - ) - if not wait_for_http(f"{COORDINATOR_URL}/health", timeout=15): - raise RuntimeError("Coordinator failed to start") - print(f" Coordinator started (pid={p.pid})") - return p - - -def start_mlx_backend(): - """Start mlx-lm server directly (simulating what provider agent does).""" - p = spawn( - ["python3", "-m", "mlx_lm", "server", - "--model", MODEL, - "--port", str(BACKEND_PORT), - "--host", "127.0.0.1"], - label="mlx-lm", - ) - if not wait_for_http(f"http://127.0.0.1:{BACKEND_PORT}/health", timeout=60): - raise RuntimeError("mlx-lm backend failed to start") - print(f" mlx-lm backend started (pid={p.pid})") - return p - - -def create_api_key(): - r = httpx.post( - f"{COORDINATOR_URL}/v1/auth/keys", - headers={"Authorization": f"Bearer {ADMIN_KEY}"}, - timeout=5, - ) - assert r.status_code == 200, f"Failed to create key: {r.status_code} {r.text}" - key = r.json().get("api_key") - print(f" API key: {key[:16]}...") - return key - - -# =========================================================================== -# 4.1 — Full Inference Loop (Consumer → Coordinator → Provider → GPU) -# =========================================================================== - -def test_4_1_1_direct_backend_inference(): - """Verify mlx-lm backend produces inference output directly.""" - r = httpx.post( - f"http://127.0.0.1:{BACKEND_PORT}/v1/chat/completions", - json={ - "model": MODEL, - "messages": [{"role": "user", "content": "What is 2+2? Answer with just the number."}], - "max_tokens": 50, - "stream": False, - }, - timeout=30, - ) - assert r.status_code == 200, f"Backend returned {r.status_code}: {r.text}" - data = r.json() - assert "choices" in data, f"Missing choices: {data}" - assert len(data["choices"]) > 0, "Empty choices" - assert "usage" in data, f"Missing usage: {data}" - assert data["usage"]["completion_tokens"] > 0, "No tokens generated" - msg = data["choices"][0]["message"] - has_content = bool(msg.get("content")) or bool(msg.get("reasoning")) - assert has_content, f"No content or reasoning in response: {msg}" - - -def test_4_1_2_direct_backend_streaming(): - """Verify mlx-lm backend streams SSE chunks.""" - chunks = [] - with httpx.stream( - "POST", - f"http://127.0.0.1:{BACKEND_PORT}/v1/chat/completions", - json={ - "model": MODEL, - "messages": [{"role": "user", "content": "Say hi"}], - "max_tokens": 20, - "stream": True, - }, - timeout=30, - ) as resp: - assert resp.status_code == 200 - for line in resp.iter_lines(): - if line.startswith("data: ") and line != "data: [DONE]": - chunk = json.loads(line[6:]) - chunks.append(chunk) - elif line == "data: [DONE]": - break - - assert len(chunks) > 0, "No streaming chunks received" - assert chunks[0]["object"] == "chat.completion.chunk" - # Last chunk should have a finish_reason - last = chunks[-1] - assert last["choices"][0]["finish_reason"] is not None, "Missing finish_reason on last chunk" - - -def test_4_1_3_provider_models_scan(): - """Verify provider agent can scan and find the downloaded model.""" - result = subprocess.run( - [PROVIDER_BIN, "models"], - capture_output=True, text=True, timeout=15, - ) - assert result.returncode == 0, f"Provider models failed: {result.stderr}" - output = result.stdout - assert "Qwen3.5" in output or "qwen" in output.lower(), ( - f"Expected to find Qwen model in output: {output}" - ) - - -# =========================================================================== -# 4.3 — Coordinator Infrastructure -# =========================================================================== - -def test_4_3_1_health(): - """Coordinator health check returns ok.""" - r = httpx.get(f"{COORDINATOR_URL}/health", timeout=5) - assert r.status_code == 200 - assert r.json()["status"] == "ok" - - -def test_4_3_2_auth_missing(): - """Request without API key returns 401.""" - r = httpx.post( - f"{COORDINATOR_URL}/v1/chat/completions", - json={"model": "x", "messages": [{"role": "user", "content": "hi"}]}, - timeout=5, - ) - assert r.status_code == 401 - - -def test_4_3_3_auth_invalid(): - """Request with wrong API key returns 401.""" - r = httpx.post( - f"{COORDINATOR_URL}/v1/chat/completions", - headers={"Authorization": "Bearer wrong-key"}, - json={"model": "x", "messages": [{"role": "user", "content": "hi"}]}, - timeout=5, - ) - assert r.status_code == 401 - - -def test_4_3_4_models_empty(api_key): - """Models list is empty when no providers connected.""" - r = httpx.get( - f"{COORDINATOR_URL}/v1/models", - headers={"Authorization": f"Bearer {api_key}"}, - timeout=5, - ) - assert r.status_code == 200 - data = r.json() - assert data["object"] == "list" - assert isinstance(data["data"], list) - - -def test_4_3_5_no_provider_503(api_key): - """Inference request with no provider returns 503.""" - r = httpx.post( - f"{COORDINATOR_URL}/v1/chat/completions", - headers={"Authorization": f"Bearer {api_key}"}, - json={"model": "nonexistent", "messages": [{"role": "user", "content": "hi"}]}, - timeout=5, - ) - assert r.status_code == 503 - - -def test_4_3_6_missing_model_field(api_key): - """Request without model field returns 400.""" - r = httpx.post( - f"{COORDINATOR_URL}/v1/chat/completions", - headers={"Authorization": f"Bearer {api_key}"}, - json={"messages": [{"role": "user", "content": "hi"}]}, - timeout=5, - ) - assert r.status_code == 400, f"Expected 400, got {r.status_code}: {r.text}" - - -def test_4_3_7_missing_messages_field(api_key): - """Request without messages field returns 400.""" - r = httpx.post( - f"{COORDINATOR_URL}/v1/chat/completions", - headers={"Authorization": f"Bearer {api_key}"}, - json={"model": "test"}, - timeout=5, - ) - assert r.status_code == 400, f"Expected 400, got {r.status_code}: {r.text}" - - -# =========================================================================== -# 4.4 — Provider Agent -# =========================================================================== - -def test_4_4_1_hardware_detection(): - """Provider detects Apple Silicon hardware.""" - result = subprocess.run( - [PROVIDER_BIN, "status"], - capture_output=True, text=True, timeout=10, - ) - assert result.returncode == 0, f"Failed: {result.stderr}" - assert "Apple M" in result.stdout - assert "GB" in result.stdout - assert "GPU" in result.stdout or "cores" in result.stdout - - -def test_4_4_2_init_creates_config(): - """Provider init creates config file.""" - # Use a temp config dir to avoid overwriting real config - import tempfile - with tempfile.TemporaryDirectory() as tmpdir: - env = os.environ.copy() - env["XDG_CONFIG_HOME"] = tmpdir # won't work on macOS but test the binary runs - result = subprocess.run( - [PROVIDER_BIN, "init"], - capture_output=True, text=True, timeout=15, - env=env, - ) - assert result.returncode == 0, f"Init failed: {result.stderr}" - - -# =========================================================================== -# 4.5 — SDK Client Integration -# =========================================================================== - -def test_4_5_1_sdk_models(api_key): - """SDK client can list models.""" - from eigeninference import EigenInference - client = EigenInference(base_url=COORDINATOR_URL, api_key=api_key) - models = client.models.list() - assert models.object == "list" - client.close() - - -def test_4_5_2_sdk_no_provider_error(api_key): - """SDK raises ProviderUnavailableError when no provider.""" - from eigeninference import EigenInference - from eigeninference.errors import ProviderUnavailableError - client = EigenInference(base_url=COORDINATOR_URL, api_key=api_key) - try: - client.chat.completions.create( - model="nonexistent", - messages=[{"role": "user", "content": "hi"}], - ) - assert False, "Should have raised" - except ProviderUnavailableError: - pass - client.close() - - -def test_4_5_3_sdk_auth_error(): - """SDK raises AuthenticationError with bad key.""" - from eigeninference import EigenInference - from eigeninference.errors import AuthenticationError - client = EigenInference(base_url=COORDINATOR_URL, api_key="bad-key") - try: - client.models.list() - assert False, "Should have raised" - except AuthenticationError: - pass - client.close() - - -# =========================================================================== -# 4.6 — Full End-to-End (Provider Agent ↔ Coordinator ↔ Consumer) -# =========================================================================== - -E2E_BACKEND_PORT = 18100 # Reuses port after direct backend is stopped - -def start_provider_agent(backend_port=None): - """Start the provider agent connected to coordinator with mlx-lm backend.""" - port = backend_port or E2E_BACKEND_PORT - p = spawn( - [PROVIDER_BIN, "-v", "serve", - "--coordinator", COORDINATOR_WS, - "--model", MODEL, - "--backend", "mlx-lm", - "--backend-port", str(port)], - label="provider-agent", - ) - # Wait for the backend to come up - if not wait_for_http(f"http://127.0.0.1:{port}/health", timeout=60): - # Check if process died - if p.poll() is not None: - stdout = p.stdout.read().decode() if p.stdout else "" - stderr = p.stderr.read().decode() if p.stderr else "" - raise RuntimeError(f"Provider agent died: exit={p.returncode}\nstdout: {stdout}\nstderr: {stderr}") - raise RuntimeError("Provider agent's backend failed to start") - print(f" Provider agent started (pid={p.pid}), backend on port {port}") - return p - - -def wait_for_provider_registration(api_key, timeout=30): - """Wait until the coordinator sees at least one provider.""" - for _ in range(int(timeout / 0.5)): - try: - r = httpx.get( - f"{COORDINATOR_URL}/health", - timeout=2, - ) - if r.status_code == 200: - data = r.json() - if data.get("providers", 0) > 0: - print(f" Provider registered with coordinator (providers={data['providers']})") - return - except Exception: - pass - time.sleep(0.5) - # Even if registration hasn't happened via WebSocket, continue — the tests will show - # whether routing works - print(" Warning: Provider may not have registered via WebSocket yet") - - -def test_4_6_1_models_visible(api_key): - """After provider connects, coordinator should list its models.""" - r = httpx.get( - f"{COORDINATOR_URL}/v1/models", - headers={"Authorization": f"Bearer {api_key}"}, - timeout=5, - ) - assert r.status_code == 200 - data = r.json() - # Even if WebSocket registration didn't complete, this tests the endpoint - assert data["object"] == "list" - - -def test_4_6_2_e2e_inference(api_key): - """Full non-streaming inference through the entire stack.""" - r = httpx.post( - f"{COORDINATOR_URL}/v1/chat/completions", - headers={"Authorization": f"Bearer {api_key}"}, - json={ - "model": MODEL, - "messages": [{"role": "user", "content": "What is 1+1? Reply with just the number."}], - "max_tokens": 50, - "stream": False, - }, - timeout=60, - ) - if r.status_code == 503: - raise SkipTest("Provider not registered with coordinator (WebSocket connection may not be established)") - assert r.status_code == 200, f"Expected 200, got {r.status_code}: {r.text}" - data = r.json() - assert "choices" in data, f"Missing choices: {data}" - assert data["usage"]["completion_tokens"] > 0, "No tokens generated" - - -def test_4_6_3_e2e_streaming(api_key): - """Full streaming inference through the entire stack.""" - chunks = [] - try: - with httpx.stream( - "POST", - f"{COORDINATOR_URL}/v1/chat/completions", - headers={"Authorization": f"Bearer {api_key}"}, - json={ - "model": MODEL, - "messages": [{"role": "user", "content": "Say hello"}], - "max_tokens": 20, - "stream": True, - }, - timeout=60, - ) as resp: - if resp.status_code == 503: - raise SkipTest("Provider not registered") - assert resp.status_code == 200, f"Expected 200, got {resp.status_code}" - for raw_line in resp.iter_lines(): - # The coordinator may batch multiple SSE events per line - # Split on "data: " boundaries - for line in raw_line.split("data: "): - line = line.strip() - if not line or line.startswith(":"): - continue - if line == "[DONE]": - break - try: - chunk = json.loads(line) - chunks.append(chunk) - except json.JSONDecodeError: - pass - except SkipTest: - raise - except Exception as e: - if "503" in str(e): - raise SkipTest("Provider not registered") - raise - - assert len(chunks) > 0, "No streaming chunks received" - - -def test_4_6_4_sequential_requests(api_key): - """Multiple sequential requests all succeed.""" - for i in range(3): - r = httpx.post( - f"{COORDINATOR_URL}/v1/chat/completions", - headers={"Authorization": f"Bearer {api_key}"}, - json={ - "model": MODEL, - "messages": [{"role": "user", "content": f"Count to {i+1}"}], - "max_tokens": 20, - "stream": False, - }, - timeout=60, - ) - if r.status_code == 503: - raise SkipTest("Provider not registered") - assert r.status_code == 200, f"Request {i+1} failed: {r.status_code}: {r.text}" - - -# =========================================================================== -# 4.7 — Failure Scenarios -# =========================================================================== - -def test_4_7_1_provider_reconnect(api_key, provider_proc): - """Kill provider, verify 503, restart, verify works again.""" - # Kill the provider - provider_proc.terminate() - try: - provider_proc.wait(timeout=10) - except Exception: - provider_proc.kill() - processes.remove(provider_proc) - - time.sleep(2) - - # Should get 503 now - r = httpx.post( - f"{COORDINATOR_URL}/v1/chat/completions", - headers={"Authorization": f"Bearer {api_key}"}, - json={ - "model": MODEL, - "messages": [{"role": "user", "content": "test"}], - "max_tokens": 5, - "stream": False, - }, - timeout=10, - ) - assert r.status_code == 503, f"Expected 503 after provider kill, got {r.status_code}" - - # Restart provider — use a different port to avoid port-in-use race - time.sleep(3) - new_provider = start_provider_agent(backend_port=18300) - wait_for_provider_registration(api_key, timeout=30) - - # Should work again (if WebSocket reconnection works) - r = httpx.post( - f"{COORDINATOR_URL}/v1/chat/completions", - headers={"Authorization": f"Bearer {api_key}"}, - json={ - "model": MODEL, - "messages": [{"role": "user", "content": "test"}], - "max_tokens": 10, - "stream": False, - }, - timeout=60, - ) - if r.status_code == 503: - raise SkipTest("Provider reconnection via WebSocket not yet working") - assert r.status_code == 200, f"Expected 200 after reconnect, got {r.status_code}" - - -# =========================================================================== -# Main -# =========================================================================== - -def main(): - global passed, failed, skipped - - print("\n" + "=" * 60) - print(" EigenInference Integration Test Suite — Component 4") - print("=" * 60 + "\n") - - # Check prerequisites - assert os.path.exists(COORDINATOR_BIN), f"Build coordinator first: {COORDINATOR_BIN}" - assert os.path.exists(PROVIDER_BIN), f"Build provider first: {PROVIDER_BIN}" - - try: - # --- Start services --- - print("Starting services...") - start_coordinator() - mlx_backend_proc = start_mlx_backend() - api_key = create_api_key() - print() - - # --- 4.1: Full Inference Loop --- - print("4.1 — Full Inference Loop (real model, real GPU)") - run_test("4.1.1 Direct backend non-streaming inference", test_4_1_1_direct_backend_inference) - run_test("4.1.2 Direct backend streaming SSE", test_4_1_2_direct_backend_streaming) - run_test("4.1.3 Provider scans and finds downloaded model", test_4_1_3_provider_models_scan) - print() - - # --- 4.3: Coordinator Infrastructure --- - print("4.3 — Coordinator Infrastructure") - run_test("4.3.1 Health endpoint", test_4_3_1_health) - run_test("4.3.2 Auth missing → 401", test_4_3_2_auth_missing) - run_test("4.3.3 Auth invalid → 401", test_4_3_3_auth_invalid) - run_test("4.3.4 Models list (no providers)", lambda: test_4_3_4_models_empty(api_key)) - run_test("4.3.5 No provider → 503", lambda: test_4_3_5_no_provider_503(api_key)) - run_test("4.3.6 Missing model field → 400", lambda: test_4_3_6_missing_model_field(api_key)) - run_test("4.3.7 Missing messages field → 400", lambda: test_4_3_7_missing_messages_field(api_key)) - print() - - # --- 4.4: Provider Agent --- - print("4.4 — Provider Agent") - run_test("4.4.1 Hardware detection", test_4_4_1_hardware_detection) - run_test("4.4.2 Init creates config", test_4_4_2_init_creates_config) - print() - - # --- 4.5: SDK Client --- - print("4.5 — SDK Client Integration") - run_test("4.5.1 SDK lists models", lambda: test_4_5_1_sdk_models(api_key)) - run_test("4.5.2 SDK no provider error", lambda: test_4_5_2_sdk_no_provider_error(api_key)) - run_test("4.5.3 SDK auth error", test_4_5_3_sdk_auth_error) - print() - - # Stop the direct backend before starting provider agent (port conflict) - print(" Stopping direct backend for E2E tests...") - for p in list(processes): - if p.pid == mlx_backend_proc.pid: - p.terminate() - try: - p.wait(timeout=10) - except Exception: - p.kill() - processes.remove(p) - time.sleep(2) - - # --- 4.6: Full E2E (Provider Agent → Coordinator → Consumer) --- - print("4.6 — Full E2E: Provider Agent ↔ Coordinator ↔ Consumer") - print(" Starting provider agent (this starts mlx-lm backend + connects to coordinator)...") - provider_proc = start_provider_agent() - wait_for_provider_registration(api_key) - - run_test("4.6.1 Models visible through coordinator after provider connects", - lambda: test_4_6_1_models_visible(api_key)) - run_test("4.6.2 Full E2E non-streaming inference (SDK → Coordinator → Provider → GPU)", - lambda: test_4_6_2_e2e_inference(api_key)) - run_test("4.6.3 Full E2E streaming inference", - lambda: test_4_6_3_e2e_streaming(api_key)) - run_test("4.6.4 Multiple sequential requests", - lambda: test_4_6_4_sequential_requests(api_key)) - - # --- 4.7: Failure Scenarios --- - print() - print("4.7 — Failure Scenarios") - run_test("4.7.1 Provider disconnect → 503 → reconnect → works again", - lambda: test_4_7_1_provider_reconnect(api_key, provider_proc)) - print() - - # --- Summary --- - total = passed + failed + skipped - print("=" * 60) - print(f" Results: {passed} passed, {failed} failed, {skipped} skipped / {total} total") - print("=" * 60 + "\n") - - if failed > 0: - sys.exit(1) - - except Exception as e: - print(f"\nFATAL: {e}") - traceback.print_exc() - sys.exit(1) - finally: - print("Cleaning up processes...") - cleanup() - - -if __name__ == "__main__": - main()