From e8e1ba4d2af3107e9885ac25dcbe975885fc8a52 Mon Sep 17 00:00:00 2001 From: nullata Date: Sun, 1 Nov 2026 17:46:38 +0200 Subject: [PATCH 1/5] fix: make instance wake single-flight; don't remove running containers on a name conflict (#111) Concurrent wakes all passed the status check, because status stays "sleeping" until the container is up. On Docker the loser's 409 force-removed the winner's live container; bare-metal the loser failed and briefly marked it stopped. --- api/instances.py | 55 +++++- tests/test_wake_single_flight.py | 287 +++++++++++++++++++++++++++++++ 2 files changed, 338 insertions(+), 4 deletions(-) create mode 100644 tests/test_wake_single_flight.py diff --git a/api/instances.py b/api/instances.py index fb3c8bf..65652ae 100644 --- a/api/instances.py +++ b/api/instances.py @@ -445,20 +445,30 @@ def _run_container( except docker.errors.ImageNotFound: return None, engine.image_missing_message(image_name) except docker.errors.APIError as e: - _remove_unstarted_container(container_name) + _remove_unstarted_container(container_name, name_conflict=e.status_code == 409) return None, f"Docker API error: {e}" except Exception as e: _remove_unstarted_container(container_name) return None, str(e) -def _remove_unstarted_container(container_name: str) -> None: +def _remove_unstarted_container(container_name: str, name_conflict: bool = False) -> None: """containers.run creates the container, then starts it: when the start fails (a mount error, a full disk) the created container stays behind, - holds its image (it can't be deleted) and nothing else removes it.""" + holds its image (it can't be deleted) and nothing else removes it. + + On a name conflict the create itself failed, so the container under that + name isn't one this call made. A running one is left alone: it may be + serving, or be a sleeping instance's container still inside its stop + grace. A dead leftover is still removed, or it would hold the name for good.""" import docker try: - get_docker_client().containers.get(container_name).remove(force=True) + container = get_docker_client().containers.get(container_name) + if name_conflict and container.status in ("running", "restarting", "paused"): + logger.warning("Not removing container %s: name conflict with a %s container", + container_name, container.status) + return + container.remove(force=True) except docker.errors.NotFound: pass except Exception as e: @@ -469,7 +479,44 @@ def _remove_unstarted_container(container_name: str) -> None: # Launch / Stop / Sleep # --------------------------------------------------------------------------- +class _Wake: + """One in-flight relaunch; `result` is valid once `done` is set.""" + + def __init__(self): + self.done = threading.Event() + self.result = False + + +_wakes_lock = threading.Lock() +_wakes: dict[str, _Wake] = {} + + def relaunch_inactive_instance(inst_id: str) -> bool: + """Wake a sleeping/stopped instance, blocking until it is healthy. + + Single-flight per instance: a caller arriving during a wake joins it and + gets its result rather than starting a second container. Status stays + "sleeping" until the container is up, so the status check alone can't stop + concurrent callers (proxy wake-on-request, kb, auto-restart, the model API). + A joined caller shares a failure too; the next call after it tries afresh.""" + with _wakes_lock: + wake = _wakes.get(inst_id) + joined = wake is not None + if not joined: + wake = _wakes[inst_id] = _Wake() + if joined: + wake.done.wait() + return wake.result + try: + wake.result = _relaunch_inactive_instance(inst_id) + return wake.result + finally: + with _wakes_lock: + del _wakes[inst_id] + wake.done.set() + + +def _relaunch_inactive_instance(inst_id: str) -> bool: with instances_lock: inst = instances.get(inst_id) if inst is None or inst["status"] not in ("sleeping", "stopped"): diff --git a/tests/test_wake_single_flight.py b/tests/test_wake_single_flight.py new file mode 100644 index 0000000..834c344 --- /dev/null +++ b/tests/test_wake_single_flight.py @@ -0,0 +1,287 @@ +# Copyright (c) llamaMan. Licensed under the Elastic License 2.0 - see LICENSE. + +"""relaunch_inactive_instance is single-flight per instance. Status stays +"sleeping" until the container is up, so without it concurrent wakes (proxy +wake-on-request, kb, auto-restart, model API) all pass the status check and +start the same container: on Docker the loser's 409 name conflict used to +force-remove the winner's container; bare-metal the loser saw the port taken +and marked the instance stopped.""" + +import os +import threading +import unittest +from unittest.mock import Mock, patch + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +os.environ.setdefault("MODELS_DIR", os.path.join(REPO_ROOT, "test-models")) +os.environ.setdefault("DATA_DIR", os.path.join(REPO_ROOT, "test-data")) +os.environ.setdefault("LOGS_DIR", os.path.join(REPO_ROOT, "test-logs")) +os.environ.setdefault("LLAMAMAN_NODE_NAME", "test-node") + +import docker + +import api.instances as instances_api +from core.state import instances, instances_lock + +CALLERS = 8 +TIMEOUT = 10 + + +def _sleeper(inst_id): + return { + "id": inst_id, "status": "sleeping", "model_path": f"/models/{inst_id}.gguf", + "port": 8000, "_internal_port": 9000, "container_name": f"llamaman-{inst_id}", + "config": {"ctx_size": 4096}, + } + + +def _conflict(): + return docker.errors.APIError("Conflict: name already in use", + response=Mock(status_code=409)) + + +class _FakeDocker: + """Enforces Docker's name rule: creating a live name is a 409. run() holds + until released, so a test controls how long a wake stays in flight.""" + + def __init__(self): + self.containers = self + self.release = threading.Event() + self.lock = threading.Lock() + self.live = {} + self.run_calls = 0 + self.removed = [] + + def run(self, **kwargs): + name = kwargs["name"] + with self.lock: + self.run_calls += 1 + if name in self.live: + raise _conflict() + container = Mock(id=f"id-{name}", status="running") + self.live[name] = container + self.release.wait(TIMEOUT) + return container + + def get(self, name): + with self.lock: + if name not in self.live: + raise docker.errors.NotFound("gone") + container = self.live[name] + + def remove(force=False): + with self.lock: + self.removed.append(name) + self.live.pop(name, None) + container.remove = remove + return container + + +class _WakeCase(unittest.TestCase): + + def setUp(self): + with instances_lock: + self._saved = dict(instances) + instances.clear() + self.addCleanup(self._restore) + for target, value in ( + ("api.instances.save_state", Mock()), + ("api.instances.is_port_available", Mock(return_value=True)), + ("api.instances._merge_preset_into_config", lambda _path, config: config), + ("api.instances.resolve_llama_endpoint", Mock(return_value=("host", 8080))), + ("api.instances.wait_for_healthy", Mock(return_value=True)), + ("api.instances.load_timeout_for", Mock(return_value=1)), + ): + patcher = patch(target, value) + patcher.start() + self.addCleanup(patcher.stop) + + def _restore(self): + with instances_lock: + instances.clear() + instances.update(self._saved) + + def _wake_all(self, inst_id, count=CALLERS, before_join=None): + """`count` concurrent wakes; returns their results.""" + results = [] + lock = threading.Lock() + + def wake(): + result = instances_api.relaunch_inactive_instance(inst_id) + with lock: + results.append(result) + + threads = [threading.Thread(target=wake, daemon=True) for _ in range(count)] + for t in threads: + t.start() + if before_join: + before_join() + for t in threads: + t.join(TIMEOUT) + self.assertFalse(any(t.is_alive() for t in threads), "a wake never returned") + return results + + +class SingleFlightTests(_WakeCase): + + def test_concurrent_wakes_start_one_container_and_all_succeed(self): + # The real _run_container against a fake daemon: this is the Docker + # deployment's failure, where a loser's 409 removed the live container. + instances["a"] = _sleeper("a") + fake = _FakeDocker() + with patch("api.instances.get_docker_client", return_value=fake), \ + patch("api.instances.ensure_docker_network"), \ + patch("api.instances._start_log_relay"), \ + patch("api.instances.get_vendor", return_value="cpu"): + # Let the others reach the wake while the first is mid-start. + results = self._wake_all( + "a", before_join=lambda: (threading.Event().wait(0.2), fake.release.set())) + + self.assertEqual(results, [True] * CALLERS) + self.assertEqual(fake.run_calls, 1) + self.assertEqual(fake.removed, []) + self.assertIn("llamaman-a", fake.live) + self.assertEqual(instances["a"]["status"], "healthy") + + def test_a_port_taken_by_our_own_wake_does_not_mark_it_stopped(self): + # Bare-metal: once the first wake's container holds the port, a second + # caller's port check fails. It must never get that far. + instances["a"] = _sleeper("a") + release = threading.Event() + run = Mock(side_effect=lambda *a, **k: (release.wait(TIMEOUT), (Mock(id="c"), None))[1]) + seen = [] + + def port_free(_port): + seen.append(_port) + return len(seen) == 1 + + with patch("api.instances._run_container", run), \ + patch("api.instances.is_port_available", port_free), \ + patch("api.instances.get_engine"): + results = self._wake_all( + "a", before_join=lambda: (threading.Event().wait(0.2), release.set())) + + self.assertEqual(results, [True] * CALLERS) + self.assertEqual(run.call_count, 1) + self.assertEqual(instances["a"]["status"], "healthy") + + def test_joined_callers_share_a_failed_wake_and_a_later_one_retries(self): + instances["a"] = _sleeper("a") + release = threading.Event() + run = Mock(side_effect=lambda *a, **k: (release.wait(TIMEOUT), (None, "boom"))[1]) + with patch("api.instances._run_container", run): + results = self._wake_all( + "a", before_join=lambda: (threading.Event().wait(0.2), release.set())) + self.assertFalse(any(results)) + self.assertEqual(instances["a"]["status"], "sleeping") + + # A failed wake must not block the next attempt. + calls_before = run.call_count + run.side_effect = None + run.return_value = (Mock(id="c"), None) + with patch("api.instances._run_container", run), patch("api.instances.get_engine"): + self.assertTrue(instances_api.relaunch_inactive_instance("a")) + self.assertEqual(run.call_count, calls_before + 1) + self.assertEqual(instances["a"]["status"], "healthy") + + def test_a_raising_wake_releases_joined_callers_and_the_next_attempt(self): + instances["a"] = _sleeper("a") + started = threading.Event() + release = threading.Event() + + def explode(*_a, **_k): + started.set() + release.wait(TIMEOUT) + raise RuntimeError("boom") + + leader_error = [] + + def leader(): + try: + instances_api.relaunch_inactive_instance("a") + except RuntimeError as e: + leader_error.append(e) + + with patch("api.instances._run_container", side_effect=explode): + thread = threading.Thread(target=leader, daemon=True) + thread.start() + self.assertTrue(started.wait(TIMEOUT)) + results = self._wake_all( + "a", count=3, before_join=lambda: (threading.Event().wait(0.2), release.set())) + thread.join(TIMEOUT) + + self.assertEqual(len(leader_error), 1) # the caller that ran it sees the error + self.assertEqual(results, [False] * 3) + with patch("api.instances._run_container", return_value=(Mock(id="c"), None)) as run, \ + patch("api.instances.get_engine"): + self.assertTrue(instances_api.relaunch_inactive_instance("a")) + run.assert_called_once() + + def test_different_instances_wake_in_parallel(self): + # Single-flight is per instance: one cold load must not hold up another. + instances["a"] = _sleeper("a") + instances["b"] = _sleeper("b") + both_in_flight = threading.Barrier(2, timeout=TIMEOUT) + + def run(*_a, **_k): + both_in_flight.wait() # BrokenBarrierError if they were serialized + return Mock(id="c"), None + + results = [] + with patch("api.instances._run_container", side_effect=run), \ + patch("api.instances.get_engine"): + threads = [threading.Thread( + target=lambda i=i: results.append(instances_api.relaunch_inactive_instance(i)), + daemon=True) for i in ("a", "b")] + for t in threads: + t.start() + for t in threads: + t.join(TIMEOUT * 2) + self.assertEqual(results, [True, True]) + + def test_awake_instances_still_short_circuit(self): + instances["a"] = {**_sleeper("a"), "status": "healthy"} + instances["b"] = {**_sleeper("b"), "status": "starting"} + instances["c"] = {**_sleeper("c"), "status": "stopping"} + with patch("api.instances._run_container") as run: + self.assertTrue(instances_api.relaunch_inactive_instance("a")) + self.assertTrue(instances_api.relaunch_inactive_instance("b")) + self.assertFalse(instances_api.relaunch_inactive_instance("c")) + self.assertFalse(instances_api.relaunch_inactive_instance("missing")) + run.assert_not_called() + + +class NameConflictCleanupTests(unittest.TestCase): + """A 409 says the name belongs to something that isn't ours to assume dead.""" + + def _run(self, error, existing_status): + client = Mock() + client.containers.run.side_effect = error + existing = Mock(status=existing_status) + client.containers.get.return_value = existing + with patch("api.instances.get_docker_client", return_value=client), \ + patch("api.instances.ensure_docker_network"), \ + patch("api.instances._start_log_relay"), \ + patch("api.instances.get_vendor", return_value="cpu"): + container, err = instances_api._run_container( + "inst1", "llamaman-test-8000", "/models/m.gguf", 8000, + {"ctx_size": 4096}, os.path.join(REPO_ROOT, "test-logs", "x.log")) + self.assertIsNone(container) + self.assertIn("Docker API error", err) + return existing + + def test_a_running_container_is_left_alone(self): + self._run(_conflict(), "running").remove.assert_not_called() + + def test_a_dead_leftover_still_gets_cleared(self): + # Otherwise a stale container blocks that name for good. + for status in ("exited", "created", "dead"): + self._run(_conflict(), status).remove.assert_called_once_with(force=True) + + def test_other_api_errors_still_remove_whatever_was_created(self): + error = docker.errors.APIError("no space left on device", response=Mock(status_code=500)) + self._run(error, "running").remove.assert_called_once_with(force=True) + + +if __name__ == "__main__": + unittest.main() From 481209a2565aa9f02a178959634ebecd8fe47110 Mon Sep 17 00:00:00 2001 From: nullata Date: Sun, 1 Nov 2026 17:57:09 +0200 Subject: [PATCH 2/5] fix: serve a queue group alias whatever state its local members are in (#111) An alias usually names no file, so a request for a sleeping or starting member died as "model not found", or woke an unrelated file that substring-matched. Members now rank healthy > starting > sleeping, and the wake runs outside the global lock. Stopping, stopped and failed wakes return typed 503s, and a forwarding peer is told to try its next member. Nodes advertise alias_wake. --- api/cluster.py | 17 ++ api/llamaman.py | 168 +++++++++++-- tests/test_alias_resolution.py | 438 +++++++++++++++++++++++++++++++++ 3 files changed, 605 insertions(+), 18 deletions(-) create mode 100644 tests/test_alias_resolution.py diff --git a/api/cluster.py b/api/cluster.py index 92df698..ad05f7c 100644 --- a/api/cluster.py +++ b/api/cluster.py @@ -43,6 +43,11 @@ _local_models_cache = {"at": 0.0, "data": []} +# "alias_wake": a group alias sent here is served even when the member isn't +# healthy yet (api.llamaman._serve_alias_member). +NODE_FEATURES = ("alias_wake",) + + def _local_models_snapshot() -> list[dict]: """Compact local model list for cross-node library rendering, cached briefly so the 5s heartbeat doesn't rescan disk every tick.""" @@ -120,6 +125,10 @@ def build_local_snapshot() -> dict: except Exception: pass + # What this node's code can do, for peers deciding what to send it. Same + # opaque-to-older-peers rule as "engines". + system = {**system, "features": list(NODE_FEATURES)} + return { "system": system, "gpus": gpus, @@ -326,6 +335,9 @@ def api_cluster_proxy(node_id, subpath): # gate / sampling / recording. A loop guard header stops re-dispatch on the hop. _DISPATCH_HEADER = "X-Cluster-Dispatch" # value = hop count (1, 2, ...) +# On a forwarded request's 503: this node served nothing and a sibling might, so +# the forwarder tries its next member. A peer without it just passes the 503 on. +RETRY_ELSEWHERE_HEADER = "X-Llamaman-Retry-Elsewhere" MAX_HOPS = 3 # entry pick + up to 2 migrations _OVERFLOW_POLL_S = 0.5 # how often a queued request re-checks peers @@ -623,6 +635,11 @@ def _forward_inference(node: dict, path: str, body: bytes, content_type: str | N resp.close() _inflight_dec(nid) return None + if resp.status_code == 503 and resp.headers.get(RETRY_ELSEWHERE_HEADER): + logger.info("cluster forward to %s: peer could not serve it, trying elsewhere", name) + resp.close() + _inflight_dec(nid) + return None out_headers = [(k, v) for k, v in resp.headers.items() if k.lower() not in _PROXY_HOP_BY_HOP] diff --git a/api/llamaman.py b/api/llamaman.py index a02e12e..014efc7 100644 --- a/api/llamaman.py +++ b/api/llamaman.py @@ -283,22 +283,138 @@ def _details_from_peer_group_member(name: str) -> dict: return _group_min_details(name) +class ModelUnavailable(str): + """_ensure_model_running's error, when the outcome isn't "no such model". + A str, so the (inst, err) contract and the message stay as they were; the + surfaces read `http_status` and `code`. `retry_elsewhere` says this node + served nothing and a sibling might: see RETRY_ELSEWHERE_HEADER.""" + + def __new__(cls, code: str, message: str, http_status: int = 503, + retry_elsewhere: bool = True): + self = super().__new__(cls, message) + self.code = code + self.http_status = http_status + self.retry_elsewhere = retry_elsewhere + return self + + +def _model_error_response(err: str, payload: dict, default_status: int): + resp = jsonify(payload) + resp.status_code = getattr(err, "http_status", default_status) + if getattr(err, "retry_elsewhere", False): + from api.cluster import RETRY_ELSEWHERE_HEADER, _request_hops + # Only for a forwarding peer; a client has no "elsewhere" to try. + if _request_hops() >= 1: + resp.headers[RETRY_ELSEWHERE_HEADER] = "1" + return resp + + +def _ollama_model_error(err: str): + return _model_error_response(err, {"error": str(err)}, 500) + + +def _openai_model_error(err: str): + error = {"message": str(err)} + if getattr(err, "code", None): + error["code"] = err.code + return _model_error_response(err, {"error": error}, 503) + + +# Which member of a group serves its alias: never a sleeper while a sibling is +# up, and a member on its way down only when nothing else is left. +_ALIAS_STATUS_RANK = {"healthy": 0, "starting": 1, "sleeping": 2} + + +def _alias_of(inst: dict) -> str: + return ((inst.get("config") or {}).get("share_queue_group") or "").strip().lower() + + +def _alias_request(name: str) -> str: + return name.split(":")[0].lower() + + def _find_running_instance_by_alias(name: str) -> dict | None: - """Find a running instance that opted into the cluster alias `name`. + """The best non-stopped instance that opted into the cluster alias `name`. Without this, a client calling by an alias (e.g. "qwen2.5-14b" mapped to a Q4 file by share_queue_group) would only find the instance through cluster dispatch - direct calls to this node's compat endpoint would 404 on the - name even when a running instance is honestly serving it via --alias.""" - req = name.split(":")[0].lower() + name even when a running instance is honestly serving it via --alias. + + An exact alias wins. A partial name (peers route by substring, so one can + arrive forwarded) resolves only when it points at a single alias; when it + fits several, only an already healthy member answers, since waking one + would be a guess.""" + req = _alias_request(name) + exact, partial = [], [] with instances_lock: for inst in instances.values(): - if inst.get("status") in ("stopped",): + if inst.get("status") == "stopped": continue - alias = ((inst.get("config") or {}).get("share_queue_group") or "").strip().lower() - if alias and (alias == req or req in alias): - return inst - return None + alias = _alias_of(inst) + if alias == req and alias: + exact.append(inst) + elif alias and req in alias: + partial.append(inst) + + def best(members): + return min(members, key=lambda i: _ALIAS_STATUS_RANK.get(i.get("status"), 3)) + + if exact: + return best(exact) + if len({_alias_of(i) for i in partial}) == 1: + return best(partial) + return next((i for i in partial if i.get("status") == "healthy"), None) + + +def _names_file_exactly(model: dict | None, name: str) -> bool: + """`model` (from _find_model_by_name) was found by its exact file name or an + engine's served name for it, not by the substring rule.""" + return bool(model) and ( + bool(model.get("_engine")) or model_name_from_path(model["path"]) == _alias_request(name)) + + +def _stopped_alias_error(name: str, model: dict | None) -> "ModelUnavailable | None": + """The error for an exact alias whose members on this node are all stopped; + None when `name` isn't one. A stop is usually deliberate, so it doesn't wake + them and must not launch some file the name happens to substring-match. The + exception is a member's own file answering to that name: asking for a file + by name wakes its stopped instance, alias or not.""" + req = _alias_request(name) + with instances_lock: + stopped = [i for i in instances.values() + if i.get("status") == "stopped" and _alias_of(i) == req] + if not stopped or (model and any(_inst_runs_file(i, model["path"]) for i in stopped)): + return None + return ModelUnavailable("group_stopped", f"model '{name}' is stopped on this node") + + +def _serve_alias_member(name: str) -> tuple[dict | None, str | None]: + """Bring up the best local member of alias `name`, which isn't healthy yet. + + Same as the file path: a `starting` member is returned for the caller to + wait on. The re-check is under _llamaman_lock so it can't race an eviction, + but the wake is outside it: the lock is global and a wake blocks until + healthy. Concurrent wakes join (relaunch_inactive_instance is single-flight).""" + from api.instances import relaunch_inactive_instance + + with _llamaman_lock: + inst = _find_running_instance_by_alias(name) + if inst is None: + return None, ModelUnavailable("group_stopped", f"model '{name}' is stopped on this node") + with instances_lock: + status = inst.get("status") + inst["_last_request_at"] = time.time() + + if status in ("healthy", "starting"): + return inst, None + if status != "sleeping": + return None, ModelUnavailable("model_stopping", f"model '{name}' is stopping on this node") + if relaunch_inactive_instance(inst["id"]): + return inst, None + if inst.get("status") == "starting": + return None, ModelUnavailable("wake_timeout", f"model '{name}' did not become healthy in time") + return None, ModelUnavailable("wake_failed", "failed to wake model") def _inst_runs_file(inst: dict, model_path: str) -> bool: @@ -483,6 +599,11 @@ def _ensure_model_running( # _find_running_instance_by_alias matches share_queue_group by substring, so # without this a pretty name like "qwen" would be captured by an unrelated # group "qwen2.5-14b" and served by the wrong model. + # + # A member that isn't healthy is brought up the same way, or a sleeping group + # 500s here: an alias usually names no file, and one that does by substring + # would wake that unrelated file instead. Only a partial alias gives way, and + # only to a file with exactly that name. from core.model_alias import resolve_to_path if not resolve_to_path(model_name): aliased = _find_running_instance_by_alias(model_name) @@ -491,6 +612,14 @@ def _ensure_model_running( if aliased["id"] in instances: instances[aliased["id"]]["_last_request_at"] = time.time() return aliased, None + if aliased: + if _alias_of(aliased) == _alias_request(model_name) \ + or not _names_file_exactly(_find_model_by_name(model_name), model_name): + return _serve_alias_member(model_name) + else: + stopped_err = _stopped_alias_error(model_name, _find_model_by_name(model_name)) + if stopped_err: + return None, stopped_err model = _find_model_by_name(model_name) if model is None: @@ -545,17 +674,21 @@ def _ensure_model_running( can_evict_admin=can_evict_admin, ) if not room: - return None, ( + return None, ModelUnavailable( + "model_limit", f"model limit reached (LLAMAMAN_MAX_MODELS={LLAMAMAN_MAX_MODELS}); " - "admin-launched models cannot be evicted via the API" + "admin-launched models cannot be evicted via the API", + retry_elsewhere=False, ) else: # OpenAI API: never evict - only proceed if there is already room. if not incoming_excluded and LLAMAMAN_MAX_MODELS > 0: if _count_running_instances() >= LLAMAMAN_MAX_MODELS: - return None, ( + return None, ModelUnavailable( + "model_limit", f"model limit reached (LLAMAMAN_MAX_MODELS={LLAMAMAN_MAX_MODELS}); " - "the OpenAI API does not evict running models" + "the OpenAI API does not evict running models", + retry_elsewhere=False, ) if would_wake_existing: @@ -563,7 +696,7 @@ def _ensure_model_running( # succeeds the instance is ready for requests immediately. if relaunch_inactive_instance(existing["id"]): return existing, None - return None, "failed to wake model" + return None, ModelUnavailable("wake_failed", "failed to wake model") port = find_available_port() if port is None: @@ -1259,8 +1392,7 @@ def _handle_request(mode: str = "chat"): inst, err = _ensure_model_running(model_name) if err: - code = 503 if "model limit reached" in err else 500 - return jsonify({"error": err}), code + return _ollama_model_error(err) if inst.get("config", {}).get("embedding_model"): return jsonify({"error": f"model '{model_name}' is embedding-only and cannot handle chat completions"}), 422 @@ -1585,7 +1717,7 @@ def llamaman_v1_chat(): model_name, allow_eviction=_openai_evict, can_evict_admin=_openai_evict ) if err: - return jsonify({"error": {"message": err}}), 503 + return _openai_model_error(err) if inst.get("config", {}).get("embedding_model"): return jsonify({"error": {"message": f"model '{model_name}' is embedding-only and cannot handle chat completions"}}), 422 @@ -1803,7 +1935,7 @@ def _proxy_passthrough(upstream_path: str, endpoint_label: str, decision: bool = model_name, allow_eviction=_openai_evict, can_evict_admin=_openai_evict ) if err: - return jsonify({"error": {"message": err}}), 503 + return _openai_model_error(err) if not decision: if inst.get("config", {}).get("embedding_model"): return jsonify({"error": {"message": f"model '{model_name}' is embedding-only and cannot generate completions"}}), 422 @@ -1953,7 +2085,7 @@ def llamaman_v1_embeddings(): model_name, allow_eviction=_openai_evict, can_evict_admin=_openai_evict ) if err: - return jsonify({"error": {"message": err}}), 503 + return _openai_model_error(err) if not inst.get("config", {}).get("embedding_model"): return jsonify({"error": {"message": f"model '{model_name}' is not configured as an embedding model"}}), 422 diff --git a/tests/test_alias_resolution.py b/tests/test_alias_resolution.py new file mode 100644 index 0000000..f1df7a1 --- /dev/null +++ b/tests/test_alias_resolution.py @@ -0,0 +1,438 @@ +# Copyright (c) llamaMan. Licensed under the Elastic License 2.0 - see LICENSE. + +"""#111 gap 2: the node owning a queue group's members serves its alias whatever +state they're in. An alias usually names no file, so a request for a sleeping +group used to reach _find_model_by_name and die as "model not found"; one that +substring-matched a file woke that unrelated file instead.""" + +import json +import os +import threading +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest.mock import MagicMock, Mock, patch + +from flask import Flask + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +os.environ.setdefault("MODELS_DIR", os.path.join(REPO_ROOT, "test-models")) +os.environ.setdefault("DATA_DIR", os.path.join(REPO_ROOT, "test-data")) +os.environ.setdefault("LOGS_DIR", os.path.join(REPO_ROOT, "test-logs")) +os.environ.setdefault("LLAMAMAN_NODE_NAME", "test-node") + +import api.cluster as cluster_api +import api.llamaman as llamaman +from core.state import instances, instances_lock + +RETRY_HEADER = cluster_api.RETRY_ELSEWHERE_HEADER + + +def _member(inst_id, status, alias="chat-pool", path=None): + return { + "id": inst_id, "status": status, "port": 8000, + "model_path": path or f"/models/{inst_id}.gguf", + "config": {"share_queue": True, "share_queue_group": alias}, + } + + +def _file(stem): + return {"path": f"/models/{stem}.gguf", "name": f"{stem}.gguf"} + + +class _AliasCase(unittest.TestCase): + """The real _ensure_model_running; only the library and the wake are faked.""" + + def setUp(self): + with instances_lock: + saved = dict(instances) + instances.clear() + + def restore(): + with instances_lock: + instances.clear() + instances.update(saved) + self.addCleanup(restore) + + self.library = [] + self.wake = Mock(side_effect=self._woke) + for target, value in ( + ("api.llamaman._library", lambda: self.library), + ("api.instances.relaunch_inactive_instance", self.wake), + ("core.model_alias.resolve_to_path", Mock(return_value=None)), + ): + patcher = patch(target, value) + patcher.start() + self.addCleanup(patcher.stop) + + def _woke(self, inst_id): + instances[inst_id]["status"] = "healthy" + return True + + def _add(self, *members): + for m in members: + instances[m["id"]] = m + + def _ensure(self, name="chat-pool"): + return llamaman._ensure_model_running(name) + + +class RankingTests(_AliasCase): + + def test_a_sleeping_member_is_woken_and_served(self): + self._add(_member("a", "sleeping")) + inst, err = self._ensure() + self.assertIsNone(err) + self.assertEqual(inst["id"], "a") + self.wake.assert_called_once_with("a") + + def test_a_starting_member_is_returned_for_the_caller_to_wait_on(self): + self._add(_member("a", "starting")) + inst, err = self._ensure() + self.assertIsNone(err) + self.assertEqual(inst["id"], "a") + self.wake.assert_not_called() + + def test_a_sleeper_listed_first_cannot_hide_a_healthy_sibling(self): + self._add(_member("asleep", "sleeping"), _member("up", "healthy")) + inst, _ = self._ensure() + self.assertEqual(inst["id"], "up") + self.wake.assert_not_called() + + def test_starting_beats_sleeping(self): + # Waking a second copy while one is already loading wastes a cold load. + self._add(_member("asleep", "sleeping"), _member("loading", "starting")) + inst, _ = self._ensure() + self.assertEqual(inst["id"], "loading") + self.wake.assert_not_called() + + def test_a_stopping_member_does_not_hide_a_sleeper(self): + self._add(_member("going", "stopping"), _member("asleep", "sleeping")) + inst, _ = self._ensure() + self.assertEqual(inst["id"], "asleep") + + def test_the_tag_and_case_of_the_request_are_ignored(self): + self._add(_member("a", "sleeping")) + inst, _ = self._ensure("CHAT-POOL:latest") + self.assertEqual(inst["id"], "a") + + def test_a_pretty_name_still_beats_an_alias(self): + self._add(_member("a", "sleeping", alias="qwen2.5-14b")) + self.library = [_file("other")] + with patch("core.model_alias.resolve_to_path", return_value=self.library[0]["path"]), \ + patch.object(llamaman, "_find_running_instance_for_model", + return_value={"id": "o", "status": "healthy"}): + inst, _ = self._ensure("qwen") + self.assertEqual(inst["id"], "o") + self.wake.assert_not_called() + + +class ExactVersusSubstringTests(_AliasCase): + + def test_an_exact_alias_never_falls_through_to_a_substring_file(self): + self._add(_member("a", "sleeping")) + self.library = [_file("chat-pool-unrelated-q8")] + with patch("api.instances.launch_instance") as launch: + inst, _ = self._ensure() + self.assertEqual(inst["id"], "a") + launch.assert_not_called() + + def test_an_exact_alias_beats_an_exact_file_name(self): + # The operator opted that instance into the name. + self._add(_member("a", "sleeping")) + self.library = [_file("chat-pool")] + inst, _ = self._ensure() + self.assertEqual(inst["id"], "a") + + def test_a_partial_name_resolves_to_a_single_alias(self): + # Peers route by substring, so one can arrive forwarded. + self._add(_member("a", "sleeping")) + inst, _ = self._ensure("chat") + self.assertEqual(inst["id"], "a") + + def test_a_partial_alias_beats_a_substring_file(self): + self._add(_member("a", "sleeping")) + self.library = [_file("chatterbox-q4")] + inst, _ = self._ensure("chat") + self.assertEqual(inst["id"], "a") + + def test_a_partial_name_gives_way_to_a_file_with_exactly_that_name(self): + self._add(_member("a", "sleeping")) + file = _file("chat") + self.library = [file] + running = {"id": "file-inst", "status": "healthy"} + with patch.object(llamaman, "_find_running_instance_for_model", return_value=running): + inst, _ = self._ensure("chat") + self.assertEqual(inst["id"], "file-inst") + self.wake.assert_not_called() + + def test_a_partial_name_fitting_two_aliases_wakes_neither(self): + self._add(_member("a", "sleeping", alias="chat-pool"), + _member("b", "sleeping", alias="chat-large")) + inst, err = self._ensure("chat") + self.assertIsNone(inst) + self.assertIn("not found", err) + self.wake.assert_not_called() + + def test_a_partial_name_fitting_two_aliases_still_finds_a_healthy_member(self): + self._add(_member("a", "sleeping", alias="chat-pool"), + _member("b", "healthy", alias="chat-large")) + inst, _ = self._ensure("chat") + self.assertEqual(inst["id"], "b") + self.wake.assert_not_called() + + def test_an_unknown_name_is_still_not_found(self): + self._add(_member("a", "sleeping")) + inst, err = self._ensure("llama-3") + self.assertIsNone(inst) + self.assertEqual(err, "model 'llama-3' not found") + self.assertFalse(hasattr(err, "http_status")) + + +class UnavailableMemberTests(_AliasCase): + + def _assert_unavailable(self, err, code): + self.assertIsInstance(err, llamaman.ModelUnavailable) + self.assertEqual(err.code, code) + self.assertEqual(err.http_status, 503) + self.assertTrue(err.retry_elsewhere) + + def test_stopping_is_typed_and_launches_nothing(self): + self._add(_member("a", "stopping")) + self.library = [_file("chat-pool-unrelated")] + with patch("api.instances.launch_instance") as launch: + inst, err = self._ensure() + self.assertIsNone(inst) + self._assert_unavailable(err, "model_stopping") + launch.assert_not_called() + self.wake.assert_not_called() + + def test_stopped_is_typed_and_wakes_nothing(self): + self._add(_member("a", "stopped")) + self.library = [_file("chat-pool-unrelated")] + with patch("api.instances.launch_instance") as launch: + inst, err = self._ensure() + self.assertIsNone(inst) + self._assert_unavailable(err, "group_stopped") + launch.assert_not_called() + self.wake.assert_not_called() + + def test_a_stopped_member_named_by_its_own_file_still_wakes(self): + # Asking for a file by name wakes its stopped instance, alias or not. + member = _member("a", "stopped", alias="q4", path="/models/q4.gguf") + self._add(member) + self.library = [_file("q4")] + with patch.object(llamaman, "_count_running_instances", return_value=0), \ + patch("api.presets.resolve_preset_for_node", return_value={}), \ + patch.object(llamaman, "get_storage"): + inst, err = self._ensure("q4") + self.assertIsNone(err) + self.assertEqual(inst["id"], "a") + self.wake.assert_called_once_with("a") + + def test_a_failed_wake_is_typed(self): + self._add(_member("a", "sleeping")) + self.wake.side_effect = lambda _id: False + inst, err = self._ensure() + self.assertIsNone(inst) + self._assert_unavailable(err, "wake_failed") + + def test_a_wake_that_timed_out_is_typed_apart_from_one_that_failed(self): + self._add(_member("a", "sleeping")) + + def timed_out(inst_id): + instances[inst_id]["status"] = "starting" + return False + + self.wake.side_effect = timed_out + inst, err = self._ensure() + self.assertIsNone(inst) + self._assert_unavailable(err, "wake_timeout") + + def test_a_member_evicted_before_the_recheck_is_typed(self): + self._add(_member("a", "sleeping")) + real = llamaman._find_running_instance_by_alias + answers = [real("chat-pool"), None] + with patch.object(llamaman, "_find_running_instance_by_alias", + side_effect=lambda _n: answers.pop(0)): + inst, err = self._ensure() + self.assertIsNone(inst) + self._assert_unavailable(err, "group_stopped") + self.wake.assert_not_called() + + def test_the_wake_runs_outside_the_global_lock(self): + # It blocks until healthy, and every slow-path launch shares that lock. + self._add(_member("a", "sleeping")) + held = [] + + def wake(inst_id): + held.append(llamaman._llamaman_lock.locked()) + return self._woke(inst_id) + + self.wake.side_effect = wake + self._ensure() + self.assertEqual(held, [False]) + + +@patch("api.cluster.dispatch_inference", return_value=None) +class SurfaceTests(unittest.TestCase): + """The typed error's status, shape and failover header on each surface.""" + + OPENAI = {"model": "m", "messages": [{"role": "user", "content": "hi"}]} + ROUTES = ( + ("/api/chat", OPENAI), + ("/v1/chat/completions", OPENAI), + ("/v1/completions", {"model": "m", "prompt": "hi"}), + ("/v1/embeddings", {"model": "m", "input": "hi"}), + ) + + def _post(self, path, body, err, dispatched=False): + app = Flask(__name__) + app.register_blueprint(llamaman.bp) + headers = {"X-Cluster-Dispatch": "1"} if dispatched else {} + with patch.object(llamaman, "_ensure_model_running", return_value=(None, err)): + return app.test_client().post(path, json=body, headers=headers) + + @staticmethod + def _unavailable(): + return llamaman.ModelUnavailable("model_stopping", "model 'm' is stopping on this node") + + def test_typed_errors_are_503_on_every_surface(self, _): + for path, body in self.ROUTES: + with self.subTest(path=path): + self.assertEqual(self._post(path, body, self._unavailable()).status_code, 503) + + def test_each_surface_keeps_its_error_shape(self, _): + r = self._post("/api/chat", self.OPENAI, self._unavailable()) + self.assertEqual(r.get_json(), {"error": "model 'm' is stopping on this node"}) + r = self._post("/v1/chat/completions", self.OPENAI, self._unavailable()) + self.assertEqual(r.get_json(), {"error": {"message": "model 'm' is stopping on this node", + "code": "model_stopping"}}) + + def test_plain_errors_keep_their_old_status(self, _): + r = self._post("/api/chat", self.OPENAI, "model 'm' not found") + self.assertEqual(r.status_code, 500) + self.assertEqual(r.get_json(), {"error": "model 'm' not found"}) + r = self._post("/v1/chat/completions", self.OPENAI, "model 'm' not found") + self.assertEqual(r.status_code, 503) + self.assertEqual(r.get_json(), {"error": {"message": "model 'm' not found"}}) + + def test_the_model_limit_is_still_503_on_ollama(self, _): + err = llamaman.ModelUnavailable("model_limit", "model limit reached (x)", retry_elsewhere=False) + self.assertEqual(self._post("/api/chat", self.OPENAI, err).status_code, 503) + + def test_only_a_forwarding_peer_is_told_to_retry_elsewhere(self, _): + for path, body in self.ROUTES: + with self.subTest(path=path): + r = self._post(path, body, self._unavailable(), dispatched=True) + self.assertEqual(r.headers.get(RETRY_HEADER), "1") + r = self._post(path, body, self._unavailable()) + self.assertIsNone(r.headers.get(RETRY_HEADER)) + + def test_errors_that_arent_about_this_node_dont_fail_over(self, _): + limit = llamaman.ModelUnavailable("model_limit", "model limit reached (x)", retry_elsewhere=False) + for err in (limit, "model 'm' not found"): + r = self._post("/api/chat", self.OPENAI, err, dispatched=True) + self.assertIsNone(r.headers.get(RETRY_HEADER)) + + +class ForwardFailoverTests(unittest.TestCase): + + NODE = {"node_id": "peer", "node_name": "peer"} + + def _forward(self, status, headers): + resp = MagicMock(status_code=status, headers=headers, content=b"{}") + app = Flask(__name__) + with app.test_request_context("/v1/chat/completions", method="POST"), \ + patch("core.cluster.cluster_request", return_value=resp): + before = cluster_api._inflight_get("peer") + out = cluster_api._forward_inference(self.NODE, "/v1/chat/completions", b"{}", None) + return out, resp, cluster_api._inflight_get("peer") - before + + def test_a_retry_elsewhere_503_tries_the_next_member(self): + out, resp, inflight = self._forward(503, {RETRY_HEADER: "1"}) + self.assertIsNone(out) + resp.close.assert_called() + self.assertEqual(inflight, 0) + + def test_a_plain_503_is_returned_as_before(self): + # An older peer, or a failure that isn't about this node. + out, _, _ = self._forward(503, {"Content-Type": "application/json"}) + self.assertEqual(out.status_code, 503) + + def test_the_header_only_means_something_on_a_503(self): + out, _, _ = self._forward(200, {RETRY_HEADER: "1", "Content-Type": "application/json"}) + self.assertEqual(out.status_code, 200) + + +class _FakeServer(BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length") or 0)) + payload = json.dumps({ + "id": "x", "object": "chat.completion", "model": "m", "created": 0, + "choices": [{"index": 0, "finish_reason": "stop", + "message": {"role": "assistant", "content": "hello"}}], + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}, + }).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + + def log_message(self, *_): + pass + + +class OwnerEndToEndTests(_AliasCase): + """The reported failure on a real route: a forwarded request for a sleeping + member, answered by a real HTTP server once the wake (faked) brings it up.""" + + def setUp(self): + super().setUp() + self.server = ThreadingHTTPServer(("127.0.0.1", 0), _FakeServer) + threading.Thread(target=self.server.serve_forever, daemon=True).start() + self.addCleanup(self.server.server_close) + self.addCleanup(self.server.shutdown) + member = _member("a", "sleeping") + member.update(_server_host="127.0.0.1", _server_port=self.server.server_address[1]) + self._add(member) + app = Flask(__name__) + app.register_blueprint(llamaman.bp) + self.client = app.test_client() + + def _post(self, path): + with patch("api.llamaman.get_gate", return_value=None): + return self.client.post( + path, headers={"X-Cluster-Dispatch": "1"}, + json={"model": "chat-pool", "stream": False, + "messages": [{"role": "user", "content": "hi"}]}) + + def test_openai_chat(self): + r = self._post("/v1/chat/completions") + self.assertEqual(r.status_code, 200, r.get_data(as_text=True)) + self.assertIn("hello", r.get_data(as_text=True)) + self.wake.assert_called_once_with("a") + + def test_ollama_chat(self): + r = self._post("/api/chat") + self.assertEqual(r.status_code, 200, r.get_data(as_text=True)) + self.assertIn("hello", r.get_data(as_text=True)) + self.wake.assert_called_once_with("a") + + def test_a_stopping_member_tells_the_forwarder_to_try_elsewhere(self): + instances["a"]["status"] = "stopping" + r = self._post("/api/chat") + self.assertEqual(r.status_code, 503) + self.assertEqual(r.headers.get(RETRY_HEADER), "1") + self.wake.assert_not_called() + + +class CapabilityTests(unittest.TestCase): + + def test_the_snapshot_advertises_alias_wake(self): + snap = cluster_api.build_local_snapshot() + self.assertIn("alias_wake", snap["system"]["features"]) + + +if __name__ == "__main__": + unittest.main() From 4bf04afcdf48e43d96f8c0a7b0accddeea985e2c Mon Sep 17 00:00:00 2001 From: nullata Date: Sun, 1 Nov 2026 18:02:05 +0200 Subject: [PATCH 3/5] fix: rank awake queue group members ahead of sleeping ones (#111) A sleeping member's gate reads empty, so it won load ties and any backlog, and queued work migrated onto it as free capacity. Load reports now count healthy, starting and sleeping members and take free slots from healthy members only. Dispatch and evacuation try awake members first. Older peers are skipped unless their snapshot shows a healthy member. Must ship with the eager wake in PR3. --- api/cluster.py | 214 ++++++++++++------- tests/test_awake_first_ranking.py | 333 ++++++++++++++++++++++++++++++ tests/test_cluster.py | 4 +- tests/test_cluster_strata.py | 3 +- 4 files changed, 476 insertions(+), 78 deletions(-) create mode 100644 tests/test_awake_first_ranking.py diff --git a/api/cluster.py b/api/cluster.py index ad05f7c..5a8428e 100644 --- a/api/cluster.py +++ b/api/cluster.py @@ -509,36 +509,78 @@ def _inflight_dec(node_id: str) -> None: _inflight.pop(node_id, None) +# How awake a group member is. Lower serves sooner. +_TIER_HEALTHY, _TIER_STARTING, _TIER_SLEEPING = 0, 1, 2 +_STATUS_TIER = {"healthy": _TIER_HEALTHY, "starting": _TIER_STARTING, "sleeping": _TIER_SLEEPING} + +# The order dispatch and evacuation try (is_fallback, tier) in: awake capacity +# beats a cold load, so even a fallback that's up comes before a sleeping primary. +_CANDIDATE_ORDER = ( + (False, _TIER_HEALTHY), (False, _TIER_STARTING), + (True, _TIER_HEALTHY), (True, _TIER_STARTING), + (False, _TIER_SLEEPING), (True, _TIER_SLEEPING), +) + + +def _member_tier(status: str | None) -> int: + return _STATUS_TIER.get(status, _TIER_HEALTHY) + + def _local_group_load(model_name: str): - """This node's backlog (in-flight + queued) for the requested group, plus - whether it's serving only as a fallback. Returns (load, is_fallback) or - None if this node hosts no matching instance. - - A node is "fallback" for the group only when ALL its matching instances - are fallback-only. A single primary instance flips the whole node to - primary - which is correct: if you also run a primary here, the primary's - own local share_queue path will serve traffic and the fallback sibling is - just extra capacity below it.""" + """This node's backlog (in-flight + queued) for the requested group, whether + it's serving only as a fallback, and how awake it is. Returns (load, + is_fallback, tier) or None if this node hosts no matching instance. + + All three describe the members this node would actually serve from: those in + its best tier (_ensure_model_running ranks them the same way). A saturated + healthy member is not idle because a sleeper sits beside it. Within that + tier a node is "fallback" only when ALL its members are fallback-only: one + primary flips it, as the primary's own local share_queue path will serve + traffic and the fallback sibling is just extra capacity below it.""" from core.state import instances, instances_lock from proxy import get_gate - best = None - saw_primary = False with instances_lock: items = list(instances.values()) - for inst in items: - cfg = inst.get("config") or {} - if not cfg.get("share_queue") or inst.get("status") in ("stopped", "stopping"): - continue - if not _inst_matches_request(inst, model_name): - continue - if not cfg.get("share_queue_fallback"): - saw_primary = True - gate = get_gate(inst["id"]) - load = (gate.active + gate.queued) if gate else 0 - best = load if best is None else min(best, load) - if best is None: + members = [inst for inst in items + if (inst.get("config") or {}).get("share_queue") + and inst.get("status") not in ("stopped", "stopping") + and _inst_matches_request(inst, model_name)] + if not members: return None - return (best, not saw_primary) + tier = min(_member_tier(inst.get("status")) for inst in members) + serving = [inst for inst in members if _member_tier(inst.get("status")) == tier] + loads = [] + for inst in serving: + gate = get_gate(inst["id"]) + loads.append((gate.active + gate.queued) if gate else 0) + fallback = all((inst.get("config") or {}).get("share_queue_fallback") for inst in serving) + return (min(loads), fallback, tier) + + +def _peer_tier(live: dict) -> int: + """How awake a peer's load entry says it is. An older peer reports no counts: + assume awake, and _peer_can_serve answers for it from its snapshot.""" + if live.get("healthy"): + return _TIER_HEALTHY + if live.get("starting"): + return _TIER_STARTING + if live.get("sleeping"): + return _TIER_SLEEPING + return _TIER_HEALTHY + + +def _peer_can_serve(node: dict, model_name: str) -> bool: + """False for an older peer whose members for this group aren't healthy: it + would answer an alias with a 500. Its live load can't reveal that, so this + reads the stored snapshot (~5s old), whose feature list also identifies it. + With no snapshot there's nothing to go on, so the live load stands.""" + snapshot = node.get("snapshot") + if not snapshot: + return True + if "alias_wake" in ((snapshot.get("system") or {}).get("features") or []): + return True + return any(inst.get("status") == "healthy" and _inst_matches_request(inst, model_name) + for inst in snapshot.get("instances") or []) def _group_candidates(model_name: str) -> list[dict]: @@ -552,9 +594,9 @@ def _group_candidates(model_name: str) -> list[dict]: candidates = [] local = _local_group_load(model_name) if local is not None: - load, fallback = local + load, fallback, tier = local candidates.append({"node": {"node_id": self_id, "node_name": ""}, - "load": load, "is_self": True, "fallback": fallback}) + "load": load, "is_self": True, "fallback": fallback, "tier": tier}) for node in get_storage().list_nodes(): nid = node.get("node_id") if nid == self_id or not _is_online(node): @@ -562,11 +604,12 @@ def _group_candidates(model_name: str) -> list[dict]: if not (node.get("advertise_url") or "").strip(): continue # can't forward to a node with no advertise URL live = _peer_live_load(node, model_name) - if not live: + if not live or not _peer_can_serve(node, model_name): continue load = (live.get("active") or 0) + (live.get("queued") or 0) + _inflight_get(nid) candidates.append({"node": node, "load": load, "is_self": False, - "fallback": bool(live.get("fallback", False))}) + "fallback": bool(live.get("fallback", False)), + "tier": _peer_tier(live)}) return candidates @@ -702,20 +745,21 @@ def relay(): def _order_candidates(candidates: list[dict]) -> list[dict]: """Least-loaded first, but round-robin among the equally-least-loaded nodes. - Fallback-only candidates are always sorted AFTER all primaries, regardless - of load: a fallback exists to serve when primaries are saturated, so even - an idle fallback must wait its turn behind a busy primary. The dispatch - loop walks this list and 429s fall through to the next entry, so the - fallback naturally absorbs overflow only when every primary refused. + Fallback-only candidates are always sorted AFTER all awake primaries, + regardless of load: a fallback exists to serve when primaries are saturated, + so even an idle fallback must wait its turn behind a busy primary. The + dispatch loop walks this list and 429s fall through to the next entry, so + the fallback naturally absorbs overflow only when every primary refused. + + Sleeping candidates come after everything awake (_CANDIDATE_ORDER): their + gates read empty, so on load alone they'd win every tie and any backlog, + and each of those requests would pay a cold load. In-flight counts only rise after a request acquires its gate, which happens after this decision, so a simultaneous burst sees every node tied at the same count. Always preferring self there would pin the whole burst to the entry node; rotating the tie spreads it across the group.""" global _rr_counter - primaries = [c for c in candidates if not c.get("fallback")] - fallbacks = [c for c in candidates if c.get("fallback")] - def _sort_tier(tier: list[dict]) -> list[dict]: if not tier: return [] @@ -731,7 +775,11 @@ def _sort_tier(tier: list[dict]) -> list[dict]: _rr_counter += 1 return tied[start:] + tied[:start] + rest - return _sort_tier(primaries) + _sort_tier(fallbacks) + ordered = [] + for fallback, tier in _CANDIDATE_ORDER: + ordered += _sort_tier([c for c in candidates + if bool(c.get("fallback")) == fallback and c.get("tier", 0) == tier]) + return ordered def dispatch_inference(model_name: str): @@ -791,38 +839,57 @@ def dispatch_inference(model_name: str): def local_load_by_model() -> dict: """This node's live gate load per shared-queue group: in-flight, queued, - free slots, and a per-group `fallback` flag. Keyed by the effective group - key (alias if set, else filename stem) so peers asking by alias find this - node without a filename match. Read straight from gate state - cheap, no DB. - - `fallback` is true for the group only when EVERY contributing instance is - fallback-only; one primary flips the whole group's flag back to false on - this node, matching the local routing rule (a primary sibling here will - serve traffic, so this node should be treated as primary by peers too).""" + free slots, how many members are healthy / starting / sleeping, and a + per-group `fallback` flag. Keyed by the effective group key (alias if set, + else filename stem) so peers asking by alias find this node without a + filename match. Read straight from gate state - cheap, no DB. + + `free` counts healthy members only: a sleeper's gate reads empty, and work + moved onto it as "free" would pay a cold load. Members sharing a gate + (siblings of one file) count it once. + + `fallback` is true for the group only when EVERY instance in its best tier + is fallback-only; one primary there flips the flag back to false, matching + the local routing rule (a primary sibling here will serve traffic, so this + node should be treated as primary by peers too).""" from core.state import instances, instances_lock from proxy import get_gate with instances_lock: snap = [(i["id"], i.get("model_path", ""), dict(i.get("config") or {}), i.get("status")) for i in instances.values()] - out: dict = {} + groups: dict[str, list] = {} for inst_id, model_path, cfg, status in snap: if not cfg.get("share_queue") or status in ("stopped", "stopping"): continue - gate = get_gate(inst_id) - if gate: - active, queued, mc = gate.active, gate.queued, gate.max_concurrent - else: - active, queued, mc = 0, 0, int(cfg.get("max_concurrent") or 0) - free = max(0, mc - active) if mc else 1 # no gate => unlimited => free - key = effective_group_key(model_path, cfg) - cur = out.setdefault(key, {"active": 0, "queued": 0, "free": 0, - "max_concurrent": 0, "fallback": True}) - cur["active"] += active - cur["queued"] += queued - cur["free"] += free - cur["max_concurrent"] += mc - if not cfg.get("share_queue_fallback"): - cur["fallback"] = False + groups.setdefault(effective_group_key(model_path, cfg), []).append((inst_id, cfg, status)) + + out: dict = {} + for key, members in groups.items(): + cur = {"active": 0, "queued": 0, "free": 0, "max_concurrent": 0, + "healthy": 0, "starting": 0, "sleeping": 0} + counted, free_counted = set(), set() + for inst_id, cfg, status in members: + cur[{_TIER_HEALTHY: "healthy", _TIER_STARTING: "starting", + _TIER_SLEEPING: "sleeping"}[_member_tier(status)]] += 1 + gate = get_gate(inst_id) + if gate: + active, queued, mc = gate.active, gate.queued, gate.max_concurrent + else: + active, queued, mc = 0, 0, int(cfg.get("max_concurrent") or 0) + # A gateless member is its own capacity; a gate may be several members'. + slot_key = id(gate) if gate else inst_id + if slot_key not in counted: + counted.add(slot_key) + cur["active"] += active + cur["queued"] += queued + cur["max_concurrent"] += mc + if _member_tier(status) == _TIER_HEALTHY and slot_key not in free_counted: + free_counted.add(slot_key) + cur["free"] += max(0, mc - active) if mc else 1 # no gate => unlimited => free + best = min(_member_tier(status) for _, _, status in members) + cur["fallback"] = all(cfg.get("share_queue_fallback") for _, cfg, status in members + if _member_tier(status) == best) + out[key] = cur return out @@ -872,7 +939,7 @@ def _find_free_peer(model_name: str): if not (node.get("advertise_url") or "").strip(): continue load = _peer_live_load(node, model_name) - if not load: + if not load or not _peer_can_serve(node, model_name): continue eff_free = (load.get("free", 0) or 0) - _inflight_get(nid) if eff_free <= 0: @@ -902,8 +969,7 @@ def _find_evacuation_peer(model_name: str): evacuating local node only retries to peers that actually accepted (a 429 falls through to the next candidate).""" self_id = cl.get_node_id() - best_primary = None # (backlog, node) - best_fallback = None + best = None # (rank in _CANDIDATE_ORDER, backlog, node) for node in get_storage().list_nodes(): nid = node.get("node_id") if nid == self_id or not _is_online(node): @@ -911,20 +977,18 @@ def _find_evacuation_peer(model_name: str): if not (node.get("advertise_url") or "").strip(): continue load = _peer_live_load(node, model_name) - if not load: - continue # peer doesn't host this model (or unreachable) + if not load or not _peer_can_serve(node, model_name): + continue # peer doesn't host this model (or unreachable, or can't serve it) backlog = (load.get("active", 0) or 0) + (load.get("queued", 0) or 0) + _inflight_get(nid) # Even when evacuating, prefer alive primaries over fallbacks: the # operator marked the fallback as second-class for a reason (different - # model, slower hardware), so use it only if no primary is alive. - if load.get("fallback"): - if best_fallback is None or backlog < best_fallback[0]: - best_fallback = (backlog, node) - else: - if best_primary is None or backlog < best_primary[0]: - best_primary = (backlog, node) - chosen = best_primary or best_fallback - return chosen[1] if chosen else None + # model, slower hardware), so use it only if no primary is alive. A + # sleeper ranks last but still counts: this node's worker is dead, so a + # cold load beats having nowhere to go. + rank = _CANDIDATE_ORDER.index((bool(load.get("fallback")), _peer_tier(load))) + if best is None or (rank, backlog) < best[:2]: + best = (rank, backlog, node) + return best[2] if best else None def acquire_or_overflow(gate, model_name: str): diff --git a/tests/test_awake_first_ranking.py b/tests/test_awake_first_ranking.py new file mode 100644 index 0000000..844c758 --- /dev/null +++ b/tests/test_awake_first_ranking.py @@ -0,0 +1,333 @@ +# Copyright (c) llamaMan. Licensed under the Elastic License 2.0 - see LICENSE. + +"""#111 gap 1: a sleeping member's gate reads active=0, so on load alone it won +every tie and any backlog, and queued work migrated onto it as "free". Load +reporting now tells members apart by how awake they are, and everything that +picks a node ranks awake capacity ahead of a cold load.""" + +import os +import unittest +from unittest.mock import Mock, patch + +from flask import Flask + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +os.environ.setdefault("MODELS_DIR", os.path.join(REPO_ROOT, "test-models")) +os.environ.setdefault("DATA_DIR", os.path.join(REPO_ROOT, "test-data")) +os.environ.setdefault("LOGS_DIR", os.path.join(REPO_ROOT, "test-logs")) +os.environ.setdefault("LLAMAMAN_NODE_NAME", "test-node") + +import api.cluster as ca +import proxy +from core.state import instances, instances_lock + +SELF = ca.cl.get_node_id() + + +def _candidate(name, load=0, fallback=False, tier=0, is_self=False): + return {"node": {"node_id": name}, "load": load, "fallback": fallback, + "tier": tier, "is_self": is_self} + + +def _live(healthy=0, starting=0, sleeping=0, active=0, queued=0, free=0, fallback=False): + return {"active": active, "queued": queued, "free": free, "max_concurrent": 2, + "fallback": fallback, "healthy": healthy, "starting": starting, "sleeping": sleeping} + + +def _peer(name, features=("alias_wake",), instances_=()): + return {"node_id": name, "node_name": name, "advertise_url": f"http://{name}:5000", + "snapshot": {"system": {"features": list(features)}, "instances": list(instances_)}} + + +class OrderTests(unittest.TestCase): + + def _names(self, candidates): + return [c["node"]["node_id"] for c in ca._order_candidates(candidates)] + + def test_the_full_tier_order(self): + by_name = { + "primary-healthy": _candidate("primary-healthy", load=9), + "primary-starting": _candidate("primary-starting", load=8, tier=1), + "fallback-healthy": _candidate("fallback-healthy", load=7, fallback=True), + "fallback-starting": _candidate("fallback-starting", load=6, fallback=True, tier=1), + "primary-sleeping": _candidate("primary-sleeping", tier=2), + "fallback-sleeping": _candidate("fallback-sleeping", fallback=True, tier=2), + } + self.assertEqual(self._names(list(by_name.values())[::-1]), list(by_name)) + + def test_a_tie_with_a_sleeper_never_goes_to_the_sleeper(self): + # "Roughly every other request fails": both read load 0 and used to rotate. + for _ in range(6): + self.assertEqual(self._names([_candidate("asleep", tier=2), _candidate("up")])[0], "up") + + def test_a_backlog_on_the_awake_member_does_not_lose_to_a_sleeper(self): + names = self._names([_candidate("asleep", tier=2), _candidate("up", load=50)]) + self.assertEqual(names, ["up", "asleep"]) + + def test_ties_within_a_tier_still_rotate(self): + firsts = {self._names([_candidate("a"), _candidate("b")])[0] for _ in range(4)} + self.assertEqual(firsts, {"a", "b"}) + + def test_a_bare_candidate_counts_as_awake(self): + bare = {"node": {"node_id": "old"}, "load": 5, "is_self": False} + self.assertEqual(self._names([_candidate("asleep", tier=2), bare]), ["old", "asleep"]) + + +class _LocalCase(unittest.TestCase): + + def setUp(self): + with instances_lock: + saved = dict(instances) + instances.clear() + self.gates = [] + + def restore(): + for inst_id in self.gates: + proxy.remove_gate(inst_id) + with instances_lock: + instances.clear() + instances.update(saved) + self.addCleanup(restore) + + def add(self, inst_id, status, path=None, busy=0, fallback=False, group="g", mc=2, shared=False): + path = path or f"/models/{inst_id}.gguf" + proxy.create_gate(inst_id, mc, 10, model_path=path, share_queue=shared) + self.gates.append(inst_id) + gate = proxy.get_gate(inst_id) + for _ in range(busy): + self.assertTrue(gate.acquire(timeout=1)) + self.addCleanup(lambda: [gate.release() for _ in range(busy)]) + with instances_lock: + instances[inst_id] = { + "id": inst_id, "status": status, "model_path": path, + "config": {"share_queue": True, "share_queue_group": group, + "share_queue_fallback": fallback, "max_concurrent": mc}, + } + + +class LocalLoadTests(_LocalCase): + + def test_a_sleeper_adds_no_free_slots_beside_a_saturated_member(self): + # The issue's repro: this used to report free=2. + self.add("up", "healthy", busy=2) + self.add("asleep", "sleeping") + entry = ca.local_load_by_model()["g"] + self.assertEqual(entry["free"], 0) + self.assertEqual((entry["healthy"], entry["starting"], entry["sleeping"]), (1, 0, 1)) + + def test_a_starting_member_adds_no_free_slots(self): + self.add("loading", "starting") + entry = ca.local_load_by_model()["g"] + self.assertEqual(entry["free"], 0) + self.assertEqual(entry["starting"], 1) + + def test_only_sleepers_report_as_sleeping_with_nothing_free(self): + self.add("asleep", "sleeping") + entry = ca.local_load_by_model()["g"] + self.assertEqual((entry["free"], entry["healthy"], entry["sleeping"]), (0, 0, 1)) + + def test_stopped_and_stopping_members_are_not_counted(self): + self.add("gone", "stopped") + self.add("going", "stopping") + self.assertEqual(ca.local_load_by_model(), {}) + + def test_members_sharing_a_gate_count_it_once(self): + self.add("one", "healthy", path="/models/same.gguf", busy=1, shared=True) + self.add("two", "healthy", path="/models/same.gguf", shared=True) + entry = ca.local_load_by_model()["g"] + self.assertEqual((entry["active"], entry["free"], entry["max_concurrent"]), (1, 1, 2)) + self.assertEqual(entry["healthy"], 2) + + def test_a_gate_shared_with_a_sleeper_is_free_whichever_is_listed_first(self): + self.add("asleep", "sleeping", path="/models/same.gguf", shared=True) + self.add("up", "healthy", path="/models/same.gguf", shared=True) + self.assertEqual(ca.local_load_by_model()["g"]["free"], 2) + + def test_a_gateless_member_is_unlimited(self): + with instances_lock: + instances["free"] = {"id": "free", "status": "healthy", "model_path": "/models/f.gguf", + "config": {"share_queue": True, "share_queue_group": "g"}} + self.assertEqual(ca.local_load_by_model()["g"]["free"], 1) + + def test_a_healthy_fallback_outranks_the_sleeping_primary_beside_it(self): + self.add("asleep", "sleeping") + self.add("spare", "healthy", fallback=True) + self.assertTrue(ca.local_load_by_model()["g"]["fallback"]) + self.assertTrue(ca._local_group_load("g")[1]) + + def test_one_primary_in_the_best_tier_still_flips_the_flag(self): + self.add("primary", "healthy") + self.add("spare", "healthy", fallback=True) + self.assertFalse(ca.local_load_by_model()["g"]["fallback"]) + self.assertFalse(ca._local_group_load("g")[1]) + + +class LocalGroupLoadTests(_LocalCase): + + def test_a_sleeper_does_not_make_a_busy_node_look_idle(self): + # The issue's repro: min() across members used to report 0. + self.add("up", "healthy", busy=2) + self.add("asleep", "sleeping") + self.assertEqual(ca._local_group_load("g"), (2, False, ca._TIER_HEALTHY)) + + def test_starting_is_used_when_nothing_is_healthy(self): + self.add("loading", "starting", busy=1) + self.add("asleep", "sleeping") + self.assertEqual(ca._local_group_load("g"), (1, False, ca._TIER_STARTING)) + + def test_a_node_of_only_sleepers_is_the_sleeping_tier(self): + self.add("asleep", "sleeping") + self.assertEqual(ca._local_group_load("g"), (0, False, ca._TIER_SLEEPING)) + + def test_no_members_is_none(self): + self.add("gone", "stopped") + self.assertIsNone(ca._local_group_load("g")) + + +class _PeersCase(_LocalCase): + + def peers(self, *entries): + """entries: (node, live load).""" + loads = {node["node_id"]: live for node, live in entries} + storage = Mock() + storage.list_nodes.return_value = [node for node, _ in entries] + for target, value in ( + ("api.cluster.get_storage", lambda: storage), + ("api.cluster._is_online", lambda _n: True), + ("api.cluster._inflight_get", lambda _n: 0), + ("api.cluster._peer_live_load", lambda node, _m: loads[node["node_id"]]), + ("api.cluster.cl.is_cluster_enabled", lambda: True), + ): + patcher = patch(target, value) + patcher.start() + self.addCleanup(patcher.stop) + + +class FreePeerTests(_PeersCase): + + def test_a_queued_request_does_not_migrate_to_a_sleeper(self): + # Its `free` is computed from healthy members, so a new peer reports 0. + self.peers((_peer("asleep"), _live(sleeping=1, free=0))) + self.assertIsNone(ca._find_free_peer("g")) + + def test_it_migrates_to_a_real_free_slot(self): + up = _peer("up") + self.peers((_peer("asleep"), _live(sleeping=1, free=0)), (up, _live(healthy=1, free=1))) + self.assertIs(ca._find_free_peer("g"), up) + + +class EvacuationTests(_PeersCase): + + def test_an_awake_peer_beats_an_idle_sleeper(self): + busy = _peer("busy") + self.peers((_peer("asleep"), _live(sleeping=1)), (busy, _live(healthy=1, active=9))) + self.assertIs(ca._find_evacuation_peer("g"), busy) + + def test_a_sleeper_is_still_a_target_when_nothing_else_is_left(self): + asleep = _peer("asleep") + self.peers((asleep, _live(sleeping=1))) + self.assertIs(ca._find_evacuation_peer("g"), asleep) + + def test_an_awake_fallback_beats_a_sleeping_primary(self): + spare = _peer("spare") + self.peers((_peer("asleep"), _live(sleeping=1)), (spare, _live(healthy=1, fallback=True))) + self.assertIs(ca._find_evacuation_peer("g"), spare) + + def test_least_backlog_wins_within_a_tier(self): + quiet = _peer("quiet") + self.peers((_peer("busy"), _live(healthy=1, active=5)), (quiet, _live(healthy=1, active=1))) + self.assertIs(ca._find_evacuation_peer("g"), quiet) + + +class OlderPeerTests(_PeersCase): + """A peer without alias_wake 500s an alias unless its member is healthy.""" + + # An older peer's live load: no counts, and a sleeper reads as free. + OLD_LIVE = {"active": 0, "queued": 0, "free": 2, "max_concurrent": 2, "fallback": False} + + @staticmethod + def _inst(status): + return {"status": status, "model_path": "/models/m.gguf", + "config": {"share_queue": True, "share_queue_group": "g"}} + + def _candidate_nodes(self): + return [c["node"]["node_id"] for c in ca._group_candidates("g")] + + def test_a_sleeping_member_is_skipped_everywhere(self): + self.peers((_peer("old", features=(), instances_=[self._inst("sleeping")]), self.OLD_LIVE)) + self.assertEqual(self._candidate_nodes(), []) + self.assertIsNone(ca._find_free_peer("g")) + self.assertIsNone(ca._find_evacuation_peer("g")) + + def test_a_healthy_member_still_gets_traffic(self): + # Old peers keep working as they do today. + self.peers((_peer("old", features=(), instances_=[self._inst("healthy")]), self.OLD_LIVE)) + self.assertEqual(self._candidate_nodes(), ["old"]) + + def test_its_candidate_counts_as_awake(self): + self.peers((_peer("old", features=(), instances_=[self._inst("healthy")]), self.OLD_LIVE)) + self.assertEqual(ca._group_candidates("g")[0]["tier"], ca._TIER_HEALTHY) + + def test_a_peer_advertising_the_feature_is_taken_at_its_word(self): + self.peers((_peer("new", instances_=[self._inst("sleeping")]), _live(sleeping=1))) + candidates = ca._group_candidates("g") + self.assertEqual(candidates[0]["tier"], ca._TIER_SLEEPING) + + def test_no_snapshot_leaves_the_live_load_to_decide(self): + node = {"node_id": "bare", "advertise_url": "http://bare:5000"} + self.peers((node, self.OLD_LIVE)) + self.assertEqual(self._candidate_nodes(), ["bare"]) + + +class DispatchTests(_PeersCase): + """The real dispatch path, entry node included.""" + + def _dispatch(self): + forward = Mock(return_value="forwarded") + app = Flask(__name__) + with app.test_request_context("/v1/chat/completions", method="POST", json={}), \ + patch("api.cluster._forward_inference", forward): + return ca.dispatch_inference("g"), forward + + def test_every_request_goes_to_the_healthy_peer_not_the_sleeper(self): + up = _peer("up") + self.peers((_peer("asleep"), _live(sleeping=1)), (up, _live(healthy=1))) + for _ in range(6): + _, forward = self._dispatch() + self.assertIs(forward.call_args.args[0], up) + + def test_a_healthy_peer_is_preferred_over_this_nodes_own_sleeper(self): + self.add("mine", "sleeping") + up = _peer("up") + self.peers((up, _live(healthy=1, active=3))) + out, forward = self._dispatch() + self.assertEqual(out, "forwarded") + self.assertIs(forward.call_args.args[0], up) + + def test_this_nodes_healthy_member_is_served_here_over_a_peers_sleeper(self): + self.add("mine", "healthy", busy=2) + self.peers((_peer("asleep"), _live(sleeping=1))) + out, forward = self._dispatch() + self.assertIsNone(out) + forward.assert_not_called() + + def test_a_sleeper_is_used_when_nothing_is_awake(self): + asleep = _peer("asleep") + self.add("mine", "stopped") + self.peers((asleep, _live(sleeping=1)), (_peer("spare"), _live(sleeping=1, fallback=True))) + _, forward = self._dispatch() + self.assertIs(forward.call_args.args[0], asleep) + + def test_a_peer_that_cannot_serve_falls_through_to_the_next(self): + asleep = _peer("asleep") + self.peers((_peer("up"), _live(healthy=1)), (asleep, _live(sleeping=1))) + forward = Mock(side_effect=[None, "forwarded"]) + app = Flask(__name__) + with app.test_request_context("/v1/chat/completions", method="POST", json={}), \ + patch("api.cluster._forward_inference", forward): + self.assertEqual(ca.dispatch_inference("g"), "forwarded") + self.assertIs(forward.call_args.args[0], asleep) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_cluster.py b/tests/test_cluster.py index 440ac1a..fe8f40c 100644 --- a/tests/test_cluster.py +++ b/tests/test_cluster.py @@ -1576,7 +1576,7 @@ def test_local_group_load_flags_pure_fallback_node(self): with instances_lock: instances.clear(); instances.update(saved) self.assertIsNotNone(result) - load, is_fb = result + load, is_fb, _tier = result self.assertEqual(load, 0) self.assertTrue(is_fb) @@ -1607,7 +1607,7 @@ def test_local_group_load_one_primary_flips_node_to_primary(self): with instances_lock: instances.clear(); instances.update(saved) self.assertIsNotNone(result) - _load, is_fb = result + _load, is_fb, _tier = result self.assertFalse(is_fb) diff --git a/tests/test_cluster_strata.py b/tests/test_cluster_strata.py index 4c73f7f..e5b6930 100644 --- a/tests/test_cluster_strata.py +++ b/tests/test_cluster_strata.py @@ -149,7 +149,8 @@ def test_local_load_map_is_keyed_for_peers(self): self.add_local("s1", STRATA_PATH, busy=1) load = cluster_api.local_load_by_model() self.assertEqual(load[GROUP_KEY], {"active": 1, "queued": 0, "free": 0, - "max_concurrent": 1, "fallback": False}) + "max_concurrent": 1, "fallback": False, + "healthy": 1, "starting": 0, "sleeping": 0}) def test_every_client_name_reaches_the_group(self): inst = {"model_path": STRATA_PATH, "config": {"engine": "strata", "share_queue": True}} From a98cd9be073f3669c7a487e5b52bb077af3c9b2d Mon Sep 17 00:00:00 2001 From: nullata Date: Sun, 1 Nov 2026 18:07:21 +0200 Subject: [PATCH 4/5] feat: wake a sleeping queue group member when its group stays saturated (#111) With sleepers ranked last and awake gates queueing rather than 429ing, a sleeper only saw traffic after a whole queue overflowed. A pass beside the heartbeat now wakes one once every healthy member in the group is full with work queued for eager_wake_polls polls in a row (default 3). Only the lowest node id holding a sleeper wakes, at most one per group per pass, and only if it fits free VRAM. --- api/cluster.py | 51 ++++- api/settings.py | 10 + core/monitoring.py | 143 +++++++++++++ core/node_settings.py | 4 + tests/test_eager_wake.py | 448 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 650 insertions(+), 6 deletions(-) create mode 100644 tests/test_eager_wake.py diff --git a/api/cluster.py b/api/cluster.py index 5a8428e..ae44881 100644 --- a/api/cluster.py +++ b/api/cluster.py @@ -893,11 +893,9 @@ def local_load_by_model() -> dict: return out -def _peer_live_load(node: dict, model_name: str): - """Live load for `model_name` on a peer (briefly cached). Returns the - per-model dict or None on miss/unreachable. The whole node map is cached so - one query serves any model; matching is fuzzy/case-insensitive so a quant- - suffixed request (gpt-oss-20b-Q4_K_M) still finds the lowercase-keyed entry.""" +def _peer_load_map(node: dict) -> dict: + """A peer's whole local-load map (briefly cached, so one query serves any + model), or {} when unreachable.""" nid = node.get("node_id") now = _time.monotonic() with _load_cache_lock: @@ -911,7 +909,48 @@ def _peer_live_load(node: dict, model_name: str): data = {} with _load_cache_lock: _load_cache[nid] = (now, data) - return _match_model_load(data, model_name) + return data + + +def _peer_live_load(node: dict, model_name: str): + """Live load for `model_name` on a peer (briefly cached). Returns the + per-model dict or None on miss/unreachable. Matching is fuzzy/case-insensitive + so a quant-suffixed request (gpt-oss-20b-Q4_K_M) still finds the + lowercase-keyed entry.""" + return _match_model_load(_peer_load_map(node), model_name) + + +def group_wants_wake(group_key: str, local: dict) -> bool: + """Whether this node should wake a sleeper for the group: every healthy + member anywhere is full with work queued, nothing is already loading, and of + the nodes holding a sleeper this one has the lowest id, so the others don't + wake one too. `local` is this node's own local_load_by_model() entry. + + Reads the whole group because the node holding the sleeper usually has an + idle gate; the saturated node is the one with nothing left to wake. An older + peer reports no counts: taken as one healthy member, which only ever makes + this less eager. An unreachable peer is no evidence either way and is left out.""" + if local.get("free") or local.get("starting"): + return False # settled without asking any peer + entries = [(cl.get_node_id(), local)] + if cl.is_cluster_enabled(): + for node in get_storage().list_nodes(): + nid = node.get("node_id") + if nid == entries[0][0] or not _is_online(node): + continue + if not (node.get("advertise_url") or "").strip(): + continue + entry = _peer_load_map(node).get(group_key) + if entry: + entries.append((nid, entry)) + loads = [entry for _, entry in entries] + if any(e.get("free") or e.get("starting") for e in loads): + return False + if not sum(e.get("queued") or 0 for e in loads): + return False + if not sum(e.get("healthy", 1) or 0 for e in loads): + return False # nothing is up to be saturated; a request wakes one itself + return min(nid for nid, e in entries if e.get("sleeping")) == entries[0][0] def _find_free_peer(model_name: str): diff --git a/api/settings.py b/api/settings.py index 6ce8fd2..48a9bcb 100644 --- a/api/settings.py +++ b/api/settings.py @@ -53,6 +53,7 @@ def snapshot_subprocess_settings() -> None: bp = Blueprint("settings", __name__) DEFAULT_GLOBAL_SPEED_LIMIT_MBPS = 0.0 +DEFAULT_EAGER_WAKE_POLLS = 3 DEFAULT_RETRY_COUNT_PER_FAILED_DOWNLOAD = 3 DEFAULT_AUTO_UPDATE_SCAN_INTERVAL_HOURS = 24 DEFAULT_RECORDING_MODE = "off" @@ -122,6 +123,11 @@ def _normalize_settings_patch(settings: dict) -> dict: normalized.get("global_speed_limit_mbps"), default=DEFAULT_GLOBAL_SPEED_LIMIT_MBPS, ) + if "eager_wake_enabled" in normalized: + normalized["eager_wake_enabled"] = _coerce_bool(normalized.get("eager_wake_enabled"), default=True) + if "eager_wake_polls" in normalized: + normalized["eager_wake_polls"] = _coerce_min_int( + normalized.get("eager_wake_polls"), default=DEFAULT_EAGER_WAKE_POLLS, minimum=1) if "auto_retry_failed_downloads" in normalized: normalized["auto_retry_failed_downloads"] = _coerce_bool( normalized.get("auto_retry_failed_downloads"), @@ -253,6 +259,10 @@ def _sanitize_settings(settings: dict) -> dict: safe.get("global_speed_limit_mbps", DEFAULT_GLOBAL_SPEED_LIMIT_MBPS)), default=DEFAULT_GLOBAL_SPEED_LIMIT_MBPS, ) + safe["eager_wake_enabled"] = bool(effective_from_settings(settings, "eager_wake_enabled", True)) + safe["eager_wake_polls"] = _coerce_min_int( + effective_from_settings(settings, "eager_wake_polls", DEFAULT_EAGER_WAKE_POLLS), + default=DEFAULT_EAGER_WAKE_POLLS, minimum=1) safe.pop("nodes", None) return safe diff --git a/core/monitoring.py b/core/monitoring.py index 8238dd6..86bb3f5 100644 --- a/core/monitoring.py +++ b/core/monitoring.py @@ -676,12 +676,155 @@ def _cluster_heartbeat_loop(): time.sleep(CLUSTER_HEARTBEAT_INTERVAL_S) +# --- Eager wake of sleeping queue group members -------------------------------- +# Dispatch ranks sleepers last, and awake gates queue rather than 429, so without +# this a sleeper would only see traffic after a whole queue overflowed. This wakes +# one as soon as a group stays saturated, so the capacity is warm when it's needed. +# On its own thread: it may ask peers (2s timeouts), which doesn't belong in the +# health tick, and the wake itself blocks until healthy so it gets a thread too. +EAGER_WAKE_INTERVAL_S = 5 +_EAGER_WAKE_DEFAULT_POLLS = 3 + +_eager_wake_streaks: dict[str, int] = {} # group key -> consecutive pressured polls +_eager_wake_refused: set[str] = set() # groups whose VRAM refusal is already logged +_eager_wakes_in_flight: set[str] = set() +_eager_wake_lock = threading.Lock() + + +def _eager_wake_sleepers() -> dict[str, list[dict]]: + """Sleeping members that would add capacity if woken, by group key. A member + with no gate is unlimited, and its group can never saturate. One sharing a gate + with an awake sibling adds none: the gate is what's full, not the instance.""" + from api.cluster import effective_group_key + from proxy import get_gate + + with instances_lock: + snap = [dict(i) for i in instances.values()] + with _eager_wake_lock: + waking = set(_eager_wakes_in_flight) + awake_gates = {id(get_gate(i["id"])) for i in snap + if i.get("status") in ("healthy", "starting") and get_gate(i["id"])} + out: dict[str, list[dict]] = {} + for inst in snap: + cfg = inst.get("config") or {} + if inst.get("status") != "sleeping" or not cfg.get("share_queue") or inst["id"] in waking: + continue + gate = get_gate(inst["id"]) + if gate is None or id(gate) in awake_gates: + continue + out.setdefault(effective_group_key(inst.get("model_path", ""), cfg), []).append(inst) + return out + + +def _eager_wake_fits_vram(inst: dict) -> bool: + """Whether the member's weights fit this host's free VRAM. Waking oversubscribed + would crash-loop the container. Unknown (no GPU stats, a virtual model with no + file) counts as fitting: refusing would leave a saturated group with no way up.""" + from api.models import estimate_model_vram, get_cached_gguf_metadata + from core.gpu import query_gpus + + try: + gpus = query_gpus() + if not gpus: + logger.debug("Eager wake: no GPU stats, not checking VRAM for %s", inst["id"]) + return True + path = inst.get("model_path", "") + cfg = inst.get("config") or {} + meta = get_cached_gguf_metadata(path) or {} + arch = meta.get("general.architecture") + needed = estimate_model_vram(os.path.getsize(path), int(cfg.get("n_gpu_layers", -1)), + int(meta.get(f"{arch}.block_count") or 0) or None) + return needed <= sum(g.get("memory_free_mb") or 0 for g in gpus) * 1024 * 1024 + except Exception as e: + logger.info("Eager wake: could not check VRAM for %s, waking anyway: %s", inst["id"], e) + return True + + +def _start_eager_wake(inst_id: str, group_key: str) -> None: + with _eager_wake_lock: + _eager_wakes_in_flight.add(inst_id) + + def _run(): + from api.instances import relaunch_inactive_instance + try: + if relaunch_inactive_instance(inst_id): + logger.info("Eager wake: %s is up for saturated group %s", inst_id, group_key) + else: + logger.warning("Eager wake: %s failed for group %s", inst_id, group_key) + except Exception as e: + logger.warning("Eager wake: %s error: %s", inst_id, e) + finally: + with _eager_wake_lock: + _eager_wakes_in_flight.discard(inst_id) + + threading.Thread(target=_run, daemon=True, name=f"eager-wake-{inst_id[:8]}").start() + + +def _eager_wake_tick() -> None: + """One pass: at most one wake per group. A group must stay saturated for + `eager_wake_polls` polls in a row, so a blip doesn't pay a cold load. Re-reads + settings each pass. The cheap check runs first: most nodes have no sleepers, and + those never touch storage or peers.""" + global _eager_wake_streaks + sleepers = _eager_wake_sleepers() + if not sleepers: + _eager_wake_streaks = {} + return + + from api.cluster import group_wants_wake, local_load_by_model + from core.node_settings import effective_from_settings + from storage import get_storage + + settings = get_storage().get_settings() + if not effective_from_settings(settings, "eager_wake_enabled", True): + _eager_wake_streaks = {} + return + try: + polls = max(1, int(effective_from_settings(settings, "eager_wake_polls", _EAGER_WAKE_DEFAULT_POLLS))) + except (TypeError, ValueError): + polls = _EAGER_WAKE_DEFAULT_POLLS + + load = local_load_by_model() + streaks: dict[str, int] = {} + for key, members in sleepers.items(): + if not group_wants_wake(key, load.get(key) or {}): + _eager_wake_refused.discard(key) + continue + streak = _eager_wake_streaks.get(key, 0) + 1 + if streak < polls: + streaks[key] = streak + continue + # A primary before a fallback, as dispatch would rank them once awake. + member = min(members, key=lambda i: bool((i.get("config") or {}).get("share_queue_fallback"))) + if not _eager_wake_fits_vram(member): + if key not in _eager_wake_refused: + _eager_wake_refused.add(key) + logger.warning("Eager wake: group %s is saturated but %s does not fit free VRAM", + key, member["id"]) + streaks[key] = streak + continue + _eager_wake_refused.discard(key) + _start_eager_wake(member["id"], key) + _eager_wake_streaks = streaks + + +def _eager_wake_loop(): + while True: + time.sleep(EAGER_WAKE_INTERVAL_S) + try: + _eager_wake_tick() + except Exception as e: + # A degraded backend or a peer read failing skips this pass, nothing more. + logger.warning("eager wake error: %s", e) + + def start_background_poller(): logger.info( "Background poller started (cleanup=%ds, orphan-scan=%ds, poll=5s, heartbeat=%ds)", _CLEANUP_INTERVAL, _ORPHAN_SCAN_INTERVAL, CLUSTER_HEARTBEAT_INTERVAL_S, ) threading.Thread(target=_cluster_heartbeat_loop, daemon=True).start() + threading.Thread(target=_eager_wake_loop, daemon=True, name="eager-wake").start() thread = threading.Thread(target=_background_poller, daemon=True) thread.start() return thread diff --git a/core/node_settings.py b/core/node_settings.py index 98b01c1..a5a1161 100644 --- a/core/node_settings.py +++ b/core/node_settings.py @@ -26,6 +26,10 @@ "db_mirror_enabled", # Download bandwidth is a property of the host's link, not the cluster. "global_speed_limit_mbps", + # Whether this host wakes its sleeping queue group members under load, and + # after how many consecutive polls. Waking spends this host's GPU. + "eager_wake_enabled", + "eager_wake_polls", ) diff --git a/tests/test_eager_wake.py b/tests/test_eager_wake.py new file mode 100644 index 0000000..dcbfc23 --- /dev/null +++ b/tests/test_eager_wake.py @@ -0,0 +1,448 @@ +# Copyright (c) llamaMan. Licensed under the Elastic License 2.0 - see LICENSE. + +"""#111 PR3: dispatch ranks sleepers last and awake gates queue rather than 429, +so a sleeper would otherwise only see traffic after a whole queue overflowed. +A pass beside the heartbeat wakes one when its group stays saturated.""" + +import os +import threading +import unittest +from unittest.mock import Mock, patch + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +os.environ.setdefault("MODELS_DIR", os.path.join(REPO_ROOT, "test-models")) +os.environ.setdefault("DATA_DIR", os.path.join(REPO_ROOT, "test-data")) +os.environ.setdefault("LOGS_DIR", os.path.join(REPO_ROOT, "test-logs")) +os.environ.setdefault("LLAMAMAN_NODE_NAME", "test-node") + +import api.cluster as ca +import core.monitoring as mon +import proxy +from core.state import instances, instances_lock + +SELF = ca.cl.get_node_id() +# Sorts before and after this node's id in the stampede election. +LOWER, HIGHER = "0-" + SELF, SELF + "-z" + + +def _saturated(queued=3, sleeping=0, healthy=1): + return {"active": 2, "queued": queued, "free": 0, "max_concurrent": 2, "fallback": False, + "healthy": healthy, "starting": 0, "sleeping": sleeping} + + +def _node(node_id): + return {"node_id": node_id, "node_name": node_id, "advertise_url": f"http://{node_id}:5000"} + + +class _Case(unittest.TestCase): + + def setUp(self): + with instances_lock: + saved = dict(instances) + instances.clear() + self.gates = [] + self.settings = {} + self.nodes = {} # node_id -> that peer's load map + self.storage = Mock() + self.storage.get_settings.side_effect = lambda: self.settings + self.storage.list_nodes.side_effect = lambda: [_node(n) for n in self.nodes] + self.wake = Mock(return_value=True) + mon._eager_wake_streaks = {} + mon._eager_wake_refused.clear() + mon._eager_wakes_in_flight.clear() + + def restore(): + for inst_id in self.gates: + proxy.remove_gate(inst_id) + with instances_lock: + instances.clear() + instances.update(saved) + self.addCleanup(restore) + for target, value in ( + ("api.cluster.get_storage", lambda: self.storage), + ("storage.get_storage", lambda: self.storage), + ("core.node_settings.get_storage", lambda: self.storage), + ("api.cluster._is_online", lambda _n: True), + ("api.cluster._peer_load_map", lambda node: self.nodes[node["node_id"]]), + ("api.cluster.cl.is_cluster_enabled", lambda: True), + ("api.instances.relaunch_inactive_instance", self.wake), + ("core.gpu.query_gpus", Mock(return_value=None)), + ): + patcher = patch(target, value) + patcher.start() + self.addCleanup(patcher.stop) + + def add(self, inst_id, status, busy=0, queued=0, group="g", fallback=False, path=None, shared=False): + path = path or f"/models/{inst_id}.gguf" + proxy.create_gate(inst_id, 2, 10, model_path=path, share_queue=shared) + self.gates.append(inst_id) + gate = proxy.get_gate(inst_id) + for _ in range(busy): + self.assertTrue(gate.acquire(timeout=1)) + gate.queued += queued + self.addCleanup(lambda: [gate.release() for _ in range(busy)]) + with instances_lock: + instances[inst_id] = { + "id": inst_id, "status": status, "model_path": path, + "config": {"share_queue": True, "share_queue_group": group, + "share_queue_fallback": fallback, "max_concurrent": 2}, + } + + def tick(self, times=1): + for _ in range(times): + mon._eager_wake_tick() + for t in threading.enumerate(): + if t.name.startswith("eager-wake-"): + t.join(5) + + def woken(self): + return [c.args[0] for c in self.wake.call_args_list] + + +class DecisionTests(_Case): + + def test_a_saturated_peer_wakes_the_sleeper_on_the_idle_node(self): + # The main case: this node's gate is idle, the saturated node has nothing to wake. + self.add("asleep", "sleeping") + self.nodes = {HIGHER: {"g": _saturated()}} + self.tick(3) + self.assertEqual(self.woken(), ["asleep"]) + + def test_this_nodes_own_saturation_counts(self): + self.add("up", "healthy", busy=2, queued=1) + self.add("asleep", "sleeping") + self.tick(3) + self.assertEqual(self.woken(), ["asleep"]) + + def test_a_full_member_with_nothing_queued_is_not_pressure(self): + self.add("asleep", "sleeping") + self.nodes = {HIGHER: {"g": _saturated(queued=0)}} + self.tick(5) + self.assertEqual(self.woken(), []) + + def test_a_free_slot_anywhere_is_not_pressure(self): + self.add("asleep", "sleeping") + self.nodes = {HIGHER: {"g": _saturated()}, + "other": {"g": {**_saturated(queued=0), "free": 1}}} + self.tick(5) + self.assertEqual(self.woken(), []) + + def test_a_member_already_loading_holds_off_another_wake(self): + self.add("asleep", "sleeping") + self.nodes = {HIGHER: {"g": {**_saturated(), "starting": 1}}} + self.tick(5) + self.assertEqual(self.woken(), []) + + def test_nothing_healthy_is_not_pressure(self): + # A request wakes a sleeper itself then. + self.add("asleep", "sleeping") + self.nodes = {HIGHER: {"g": _saturated(healthy=0, sleeping=1)}} + self.tick(5) + self.assertEqual(self.woken(), []) + + def test_a_different_group_on_the_peer_is_not_pressure(self): + self.add("asleep", "sleeping", group="chat") + self.nodes = {HIGHER: {"chat-pool": _saturated()}} # substring must not count + self.tick(5) + self.assertEqual(self.woken(), []) + + def test_an_older_peer_counts_as_one_healthy_member(self): + self.add("asleep", "sleeping") + old = {"active": 2, "queued": 3, "free": 0, "max_concurrent": 2, "fallback": False} + self.nodes = {HIGHER: {"g": old}} + self.tick(3) + self.assertEqual(self.woken(), ["asleep"]) + + def test_an_unreachable_peer_is_no_evidence(self): + self.add("asleep", "sleeping") + self.nodes = {HIGHER: {}} + self.tick(5) + self.assertEqual(self.woken(), []) + + def test_single_node_needs_no_cluster(self): + self.add("up", "healthy", busy=2, queued=1) + self.add("asleep", "sleeping") + with patch("api.cluster.cl.is_cluster_enabled", return_value=False): + self.tick(3) + self.assertEqual(self.woken(), ["asleep"]) + self.storage.list_nodes.assert_not_called() + + +class StampedeTests(_Case): + + def test_only_the_lowest_node_with_a_sleeper_wakes(self): + self.add("asleep", "sleeping") + self.nodes = {LOWER: {"g": _saturated(healthy=0, sleeping=1)}, + "busy": {"g": _saturated()}} + self.tick(5) + self.assertEqual(self.woken(), []) + + def test_this_node_wakes_when_it_is_the_lowest(self): + self.add("asleep", "sleeping") + self.nodes = {HIGHER: {"g": _saturated(sleeping=1)}} + self.tick(3) + self.assertEqual(self.woken(), ["asleep"]) + + def test_one_wake_per_group_per_pass(self): + self.add("a", "sleeping") + self.add("b", "sleeping") + self.nodes = {HIGHER: {"g": _saturated()}} + self.tick(3) + self.assertEqual(len(self.woken()), 1) + + def test_two_groups_wake_independently(self): + self.add("a", "sleeping", group="g1") + self.add("b", "sleeping", group="g2") + self.nodes = {HIGHER: {"g1": _saturated(), "g2": _saturated()}} + self.tick(3) + self.assertCountEqual(self.woken(), ["a", "b"]) + + def test_a_member_being_woken_is_not_woken_again(self): + self.add("asleep", "sleeping") + self.nodes = {HIGHER: {"g": _saturated()}} + release = threading.Event() + self.wake.side_effect = lambda _id: release.wait(5) + self.addCleanup(release.set) + for _ in range(6): + mon._eager_wake_tick() + self.assertEqual(self.wake.call_count, 1) + release.set() + + +class EligibilityTests(_Case): + + def test_a_gateless_sleeper_is_skipped(self): + with instances_lock: + instances["free"] = {"id": "free", "status": "sleeping", "model_path": "/models/f.gguf", + "config": {"share_queue": True, "share_queue_group": "g"}} + self.nodes = {HIGHER: {"g": _saturated()}} + self.tick(5) + self.assertEqual(self.woken(), []) + + def test_a_sleeper_sharing_a_gate_with_an_awake_sibling_is_skipped(self): + # It adds no gate capacity: the gate is what's full. + self.add("up", "healthy", busy=2, queued=1, path="/models/same.gguf", shared=True) + self.add("asleep", "sleeping", path="/models/same.gguf", shared=True) + self.tick(5) + self.assertEqual(self.woken(), []) + + def test_a_primary_wakes_before_a_fallback(self): + self.add("spare", "sleeping", fallback=True) + self.add("primary", "sleeping") + self.nodes = {HIGHER: {"g": _saturated()}} + self.tick(3) + self.assertEqual(self.woken(), ["primary"]) + + def test_a_member_without_share_queue_is_skipped(self): + self.add("asleep", "sleeping") + instances["asleep"]["config"]["share_queue"] = False + self.nodes = {HIGHER: {"g": _saturated()}} + self.tick(5) + self.assertEqual(self.woken(), []) + + +class HysteresisTests(_Case): + + def setUp(self): + super().setUp() + self.add("asleep", "sleeping") + self.nodes = {HIGHER: {"g": _saturated()}} + + def test_a_blip_does_not_wake(self): + self.tick(2) + self.assertEqual(self.woken(), []) + + def test_a_periodic_burst_never_wakes(self): + # Waking on each would pay cold loads repeatedly, worse than not waking. + for _ in range(4): + self.nodes = {HIGHER: {"g": _saturated()}} + self.tick(2) + self.nodes = {HIGHER: {"g": _saturated(queued=0)}} + self.tick(1) + self.assertEqual(self.woken(), []) + + def test_the_poll_count_is_a_live_setting(self): + self.settings = {"eager_wake_polls": 1} + self.tick(1) + self.assertEqual(self.woken(), ["asleep"]) + + def test_it_can_be_turned_off(self): + self.settings = {"eager_wake_enabled": False} + self.tick(5) + self.assertEqual(self.woken(), []) + + def test_a_bad_poll_count_falls_back(self): + self.settings = {"eager_wake_polls": "soon"} + self.tick(2) + self.assertEqual(self.woken(), []) + self.tick(1) + self.assertEqual(self.woken(), ["asleep"]) + + def test_settings_are_per_node(self): + self.settings = {"nodes": {SELF: {"eager_wake_enabled": False}}, "eager_wake_enabled": True} + self.tick(5) + self.assertEqual(self.woken(), []) + + +class VramTests(_Case): + + def setUp(self): + super().setUp() + self.add("asleep", "sleeping") + self.nodes = {HIGHER: {"g": _saturated()}} + self.settings = {"eager_wake_polls": 1} + self.size = patch("core.monitoring.os.path.getsize", return_value=8 * 1024 ** 3) + self.size.start() + self.addCleanup(self.size.stop) + meta = patch("api.models.get_cached_gguf_metadata", return_value={}) + meta.start() + self.addCleanup(meta.stop) + + def _gpus(self, *free_gb): + return patch("core.gpu.query_gpus", + return_value=[{"memory_free_mb": gb * 1024} for gb in free_gb]) + + def test_a_model_that_doesnt_fit_stays_asleep_and_is_logged_once(self): + with self._gpus(4), self.assertLogs("llamaman", level="WARNING") as logs: + self.tick(4) + self.assertEqual(self.woken(), []) + self.assertEqual(len([m for m in logs.output if "does not fit" in m]), 1) + + def test_a_model_that_fits_wakes(self): + with self._gpus(16): + self.tick() + self.assertEqual(self.woken(), ["asleep"]) + + def test_free_memory_across_gpus_counts(self): + with self._gpus(4, 4): + self.tick() + self.assertEqual(self.woken(), ["asleep"]) + + def test_it_wakes_once_memory_frees_up(self): + with self._gpus(4): + self.tick(2) + with self._gpus(16): + self.tick() + self.assertEqual(self.woken(), ["asleep"]) + + def test_a_cpu_only_member_needs_no_vram(self): + instances["asleep"]["config"]["n_gpu_layers"] = 0 + with self._gpus(0): + self.tick() + self.assertEqual(self.woken(), ["asleep"]) + + def test_partial_offload_counts_only_its_share(self): + instances["asleep"]["config"]["n_gpu_layers"] = 10 + meta = {"general.architecture": "x", "x.block_count": 40} + with self._gpus(4), patch("api.models.get_cached_gguf_metadata", return_value=meta): + self.tick() + self.assertEqual(self.woken(), ["asleep"]) + + def test_no_gpu_stats_fails_open(self): + with patch("core.gpu.query_gpus", return_value=None): + self.tick() + self.assertEqual(self.woken(), ["asleep"]) + + def test_a_model_with_no_file_fails_open(self): + with self._gpus(1), patch("core.monitoring.os.path.getsize", side_effect=OSError("virtual")): + self.tick() + self.assertEqual(self.woken(), ["asleep"]) + + +class SettingsApiTests(unittest.TestCase): + """Reachable through the settings API, per node, with bad values normalized.""" + + def setUp(self): + from flask import Flask + + import api.settings as settings_api + self.saved = {} + self.storage = Mock() + self.storage.get_settings.side_effect = lambda: self.saved + + def merge(patch): + nodes = patch.get("nodes") or {} + for node_id, values in nodes.items(): + self.saved.setdefault("nodes", {}).setdefault(node_id, {}).update(values) + self.saved.update({k: v for k, v in patch.items() if k != "nodes"}) + return self.saved + + self.storage.merge_settings.side_effect = merge + for target in ("api.settings.get_storage", "core.node_settings.get_storage"): + patcher = patch(target, lambda: self.storage) + patcher.start() + self.addCleanup(patcher.stop) + app = Flask(__name__) + app.register_blueprint(settings_api.bp) + self.client = app.test_client() + + def _post(self, body): + return self.client.post("/api/settings", json=body) + + def test_defaults_are_on_after_three_polls(self): + body = self.client.get("/api/settings").get_json() + self.assertIs(body["eager_wake_enabled"], True) + self.assertEqual(body["eager_wake_polls"], 3) + + def test_values_are_stored_for_this_node_only(self): + self.assertEqual(self._post({"eager_wake_enabled": False, "eager_wake_polls": 6}).status_code, 200) + self.assertEqual(self.saved["nodes"][SELF], {"eager_wake_enabled": False, "eager_wake_polls": 6}) + self.assertNotIn("eager_wake_enabled", self.saved) + body = self.client.get("/api/settings").get_json() + self.assertIs(body["eager_wake_enabled"], False) + self.assertEqual(body["eager_wake_polls"], 6) + + def test_bad_values_are_normalized(self): + self._post({"eager_wake_enabled": "false", "eager_wake_polls": 0}) + self.assertIs(self.saved["nodes"][SELF]["eager_wake_enabled"], False) + self.assertEqual(self.saved["nodes"][SELF]["eager_wake_polls"], 1) + + +class ResilienceTests(_Case): + + def test_nothing_asleep_reads_neither_storage_nor_peers(self): + self.add("up", "healthy") + self.tick() + self.storage.get_settings.assert_not_called() + self.storage.list_nodes.assert_not_called() + + def test_a_group_with_a_free_local_slot_asks_no_peer(self): + self.add("up", "healthy") + self.add("asleep", "sleeping") + self.tick() + self.storage.list_nodes.assert_not_called() + + def test_a_failed_wake_does_not_block_the_next(self): + self.add("asleep", "sleeping") + self.nodes = {HIGHER: {"g": _saturated()}} + self.settings = {"eager_wake_polls": 1} + self.wake.side_effect = [False, True] + self.tick() + self.tick() + self.assertEqual(self.woken(), ["asleep", "asleep"]) + + def test_a_raising_wake_clears_the_in_flight_mark(self): + self.add("asleep", "sleeping") + self.nodes = {HIGHER: {"g": _saturated()}} + self.settings = {"eager_wake_polls": 1} + self.wake.side_effect = RuntimeError("boom") + self.tick() + self.assertEqual(mon._eager_wakes_in_flight, set()) + + def test_a_storage_failure_only_skips_the_pass(self): + self.add("asleep", "sleeping") + self.storage.get_settings.side_effect = RuntimeError("database unreachable") + calls = [] + + def stop_after_two(_seconds): + calls.append(1) + if len(calls) > 2: + raise SystemExit + with patch("core.monitoring.time.sleep", stop_after_two), \ + self.assertRaises(SystemExit), self.assertLogs("llamaman", level="WARNING"): + mon._eager_wake_loop() + self.assertEqual(len(calls), 3) # went round again after the failures + + +if __name__ == "__main__": + unittest.main() From e80cf48531bdb8ef6deabb755a78bd9415bea756 Mon Sep 17 00:00:00 2001 From: nullata Date: Sun, 1 Nov 2026 18:14:54 +0200 Subject: [PATCH 5/5] fix: make queue group listings and routing errors honest about peers (#111) Listings and routing now share one rule, so groups on view-only and offline peers are no longer advertised. A peer that fails a load probe stays routable from its snapshot but ranks last. When no node can take a request, the client gets a 429 or 503 naming each node and why, not "model not found". /v1/embeddings now routes across the cluster. Documents queue group behavior in CLUSTERING.md. --- api/cluster.py | 187 +++++++++++++--- api/llamaman.py | 23 +- docs/en/CLUSTERING.md | 54 +++++ tests/test_cluster.py | 8 +- tests/test_honest_routing.py | 422 +++++++++++++++++++++++++++++++++++ 5 files changed, 656 insertions(+), 38 deletions(-) create mode 100644 tests/test_honest_routing.py diff --git a/api/cluster.py b/api/cluster.py index ae44881..1575135 100644 --- a/api/cluster.py +++ b/api/cluster.py @@ -14,7 +14,7 @@ import os import threading -from flask import Blueprint, Response, jsonify, request +from flask import Blueprint, Response, g, has_request_context, jsonify, request from config import REQUEST_TIMEOUT, logger from core import cluster as cl @@ -368,6 +368,18 @@ def effective_group_key(model_path: str, config: dict | None) -> str: return alias or model_name_from_path(model_path) +def peer_is_routable(node: dict) -> bool: + """A peer inference can be forwarded to: heartbeating, with a URL to reach it + on. Listings and routing share this, so a view-only or offline peer's groups + aren't advertised under a name that can't be served. Member status stays each + caller's business: a listing has only the snapshot, routing has live load.""" + return _is_online(node) and bool((node.get("advertise_url") or "").strip()) + + +def _is_group_member(config: dict | None) -> bool: + return bool((config or {}).get("share_queue")) + + def cluster_group_models() -> list[dict]: """Distinct `share_queue_group` aliases currently served somewhere in the cluster, for advertising in the model-listing APIs. @@ -381,8 +393,8 @@ def cluster_group_models() -> list[dict]: per-file `/api/tags` listing never mentions it, so a client has no way to discover the name it should send. This surfaces it, but only when it means something: clustering enabled, the alias actually set, and at least one - non-stopped instance (on any node) serving it - which is exactly when a - request for the alias can be routed rather than 404'd. + non-stopped instance on this node or a routable peer - which is exactly when + a request for the alias can be routed rather than 404'd. """ if not cl.is_cluster_enabled(): return [] @@ -394,7 +406,7 @@ def cluster_group_models() -> list[dict]: with instances_lock: for inst in instances.values(): alias = ((inst.get("config") or {}).get("share_queue_group") or "").strip() - if alias: + if alias and _is_group_member(inst.get("config")): seen.append((alias, inst.get("status") or "", inst.get("model_path"))) try: @@ -405,10 +417,12 @@ def cluster_group_models() -> list[dict]: for node in nodes: if node.get("node_id") == self_id: continue # this node's live instances are already counted above + if not peer_is_routable(node): + continue snapshot = node.get("snapshot") or {} for inst in snapshot.get("instances") or []: alias = ((inst.get("config") or {}).get("share_queue_group") or "").strip() - if alias: + if alias and _is_group_member(inst.get("config")): seen.append((alias, inst.get("status") or "", None)) groups: dict[str, dict] = {} @@ -583,6 +597,26 @@ def _peer_can_serve(node: dict, model_name: str) -> bool: for inst in snapshot.get("instances") or []) +def _snapshot_candidate(node: dict, model_name: str) -> dict | None: + """A candidate for a peer whose live load couldn't be read, from its snapshot. + A failed probe says nothing about which groups it hosts, so a blip mustn't + make a served group vanish. `unknown` ranks it behind every peer that answered: + at an assumed load of 0 a dead peer would otherwise attract the traffic.""" + if not _peer_can_serve(node, model_name): + return None + members = [inst for inst in (node.get("snapshot") or {}).get("instances") or [] + if _is_group_member(inst.get("config")) + and inst.get("status") not in ("stopped", "stopping") + and _inst_matches_request(inst, model_name)] + if not members: + return None + tier = min(_member_tier(inst.get("status")) for inst in members) + fallback = all((inst.get("config") or {}).get("share_queue_fallback") for inst in members + if _member_tier(inst.get("status")) == tier) + return {"node": node, "load": _inflight_get(node.get("node_id")), "is_self": False, + "fallback": fallback, "tier": tier, "unknown": True} + + def _group_candidates(model_name: str) -> list[dict]: """Group members with their CURRENT backlog (active + queued) and whether they're serving as fallback-only. Self is read live from local gates; peers @@ -599,11 +633,14 @@ def _group_candidates(model_name: str) -> list[dict]: "load": load, "is_self": True, "fallback": fallback, "tier": tier}) for node in get_storage().list_nodes(): nid = node.get("node_id") - if nid == self_id or not _is_online(node): + if nid == self_id or not peer_is_routable(node): continue - if not (node.get("advertise_url") or "").strip(): - continue # can't forward to a node with no advertise URL live = _peer_live_load(node, model_name) + if live is PEER_UNREACHABLE: + candidate = _snapshot_candidate(node, model_name) + if candidate: + candidates.append(candidate) + continue if not live or not _peer_can_serve(node, model_name): continue load = (live.get("active") or 0) + (live.get("queued") or 0) + _inflight_get(nid) @@ -613,6 +650,67 @@ def _group_candidates(model_name: str) -> list[dict]: return candidates +# Why each peer turned down this request, kept on the request so that if nobody +# takes it the client hears that rather than "model not found". +_REFUSED_FULL = "queue full" +_REFUSED_UNREACHABLE = "unreachable" + + +def _note_refusal(node_id: str, reason: str) -> None: + if not hasattr(g, "forward_refusals"): + g.forward_refusals = {} + g.forward_refusals[node_id] = reason + + +def group_unroutable_error(model_name: str) -> dict | None: + """When `model_name` is a group other nodes serve but none of them can take + this request: {code, message, http_status}, naming each node and why. None + when it isn't one, and for a forwarded request (its entry node answers). + 429 if a peer is merely full, which a client can usefully retry.""" + if not cl.is_cluster_enabled() or not has_request_context() or _request_hops() >= 1: + return None + from core.engines import virtual_model_key + from core.model_alias import canonical_name + canonical = canonical_name(model_name) + canonical = virtual_model_key(canonical) or canonical + req = canonical.split(":")[0].lower() + refusals = getattr(g, "forward_refusals", {}) + try: + nodes = get_storage().list_nodes() or [] + except Exception: + nodes = [] + self_id = cl.get_node_id() + reasons = [] + full = False + for node in nodes: + nid = node.get("node_id") + if nid == self_id: + continue + hosts = any(_is_group_member(inst.get("config")) + and inst.get("status") not in ("stopped", "stopping") + and effective_group_key(inst.get("model_path", ""), inst.get("config")) == req + for inst in (node.get("snapshot") or {}).get("instances") or []) + if not hosts and nid not in refusals: + continue + reason = refusals.get(nid) + if reason is None: + if not _is_online(node): + reason = "offline" + elif not (node.get("advertise_url") or "").strip(): + reason = "view-only, no CLUSTER_ADVERTISE_URL" + else: + reason = "not ready" + full = full or reason == _REFUSED_FULL + reasons.append(f"{node.get('node_name') or nid} ({reason})") + if not reasons: + return None + message = (f"model '{model_name}' is served by other nodes, but none could take " + f"this request: {', '.join(sorted(reasons))}") + if full: + return {"code": "group_full", "message": message, "http_status": 429} + return {"code": "group_unavailable", "message": message, "http_status": 503} + + def _forward_inference(node: dict, path: str, body: bytes, content_type: str | None, hops: int = 1): """Stream an inference request to a peer's compat endpoint. Returns a Flask @@ -668,20 +766,25 @@ def _forward_inference(node: dict, path: str, body: bytes, content_type: str | N name, REQUEST_TIMEOUT, e) msg = (f"peer {name} accepted the request but did not respond within " f"REQUEST_TIMEOUT ({REQUEST_TIMEOUT}s); it may still be processing") - return Response(_json.dumps({"error": {"message": msg}}), + # Ollama's surface carries the error as a plain string, OpenAI's nested. + error = msg if request.path.startswith("/api/") else {"message": msg} + return Response(_json.dumps({"error": error}), status=504, mimetype="application/json") except Exception as e: _inflight_dec(nid) logger.warning("cluster dispatch to %s failed: %s", name, e) + _note_refusal(nid, _REFUSED_UNREACHABLE) return None if resp.status_code == 429: # peer's gate is full - try elsewhere resp.close() _inflight_dec(nid) + _note_refusal(nid, _REFUSED_FULL) return None if resp.status_code == 503 and resp.headers.get(RETRY_ELSEWHERE_HEADER): logger.info("cluster forward to %s: peer could not serve it, trying elsewhere", name) resp.close() _inflight_dec(nid) + _note_refusal(nid, "could not serve it") return None out_headers = [(k, v) for k, v in resp.headers.items() @@ -712,6 +815,7 @@ def _forward_inference(node: dict, path: str, body: bytes, content_type: str | N resp.close() except Exception: pass + _note_refusal(nid, _REFUSED_UNREACHABLE) return None logger.info("forward %s: body read %d bytes, returning response", name, len(body_bytes)) @@ -753,7 +857,8 @@ def _order_candidates(candidates: list[dict]) -> list[dict]: Sleeping candidates come after everything awake (_CANDIDATE_ORDER): their gates read empty, so on load alone they'd win every tie and any backlog, - and each of those requests would pay a cold load. + and each of those requests would pay a cold load. A peer whose load couldn't + be read comes after all of them: it may well be dead. In-flight counts only rise after a request acquires its gate, which happens after this decision, so a simultaneous burst sees every node tied at the @@ -776,9 +881,12 @@ def _sort_tier(tier: list[dict]) -> list[dict]: return tied[start:] + tied[:start] + rest ordered = [] - for fallback, tier in _CANDIDATE_ORDER: - ordered += _sort_tier([c for c in candidates - if bool(c.get("fallback")) == fallback and c.get("tier", 0) == tier]) + for unknown in (False, True): + for fallback, tier in _CANDIDATE_ORDER: + ordered += _sort_tier([c for c in candidates + if bool(c.get("unknown")) == unknown + and bool(c.get("fallback")) == fallback + and c.get("tier", 0) == tier]) return ordered @@ -893,31 +1001,56 @@ def local_load_by_model() -> dict: return out +class _Unreachable(dict): + """Falsy and empty like a peer with nothing to report, so code that only wants + real capacity needn't care, while `is PEER_UNREACHABLE` tells the two apart: a + peer hosting nothing and one that didn't answer mean different things.""" + + +PEER_UNREACHABLE = _Unreachable() +_unreachable_peers: set[str] = set() + + def _peer_load_map(node: dict) -> dict: """A peer's whole local-load map (briefly cached, so one query serves any - model), or {} when unreachable.""" + model), or PEER_UNREACHABLE on a timeout, a non-200 or a bad body.""" nid = node.get("node_id") now = _time.monotonic() with _load_cache_lock: cached = _load_cache.get(nid) data = cached[1] if cached and now - cached[0] < _LOAD_CACHE_TTL else None if data is None: + why = None try: resp = cl.cluster_request(node, "GET", "/api/cluster/local-load", timeout=2) - data = resp.json() if resp.status_code == 200 else {} - except Exception: - data = {} + if resp.status_code == 200: + data = resp.json() + else: + why = f"HTTP {resp.status_code}" + except Exception as e: + why = str(e) + if not isinstance(data, dict): + why = why or "unexpected response" + data = PEER_UNREACHABLE with _load_cache_lock: _load_cache[nid] = (now, data) + changed = (why is not None) != (nid in _unreachable_peers) + (_unreachable_peers.add if why is not None else _unreachable_peers.discard)(nid) + # Once per change: this runs on every routing decision. + if changed and why is not None: + logger.warning("cluster: cannot read live load from %s: %s", node.get("node_name") or nid, why) + elif changed: + logger.info("cluster: live load from %s is readable again", node.get("node_name") or nid) return data def _peer_live_load(node: dict, model_name: str): """Live load for `model_name` on a peer (briefly cached). Returns the - per-model dict or None on miss/unreachable. Matching is fuzzy/case-insensitive - so a quant-suffixed request (gpt-oss-20b-Q4_K_M) still finds the - lowercase-keyed entry.""" - return _match_model_load(_peer_load_map(node), model_name) + per-model dict, None when the peer reports nothing for it, or PEER_UNREACHABLE. + Matching is fuzzy/case-insensitive so a quant-suffixed request + (gpt-oss-20b-Q4_K_M) still finds the lowercase-keyed entry.""" + data = _peer_load_map(node) + return data if data is PEER_UNREACHABLE else _match_model_load(data, model_name) def group_wants_wake(group_key: str, local: dict) -> bool: @@ -936,9 +1069,7 @@ def group_wants_wake(group_key: str, local: dict) -> bool: if cl.is_cluster_enabled(): for node in get_storage().list_nodes(): nid = node.get("node_id") - if nid == entries[0][0] or not _is_online(node): - continue - if not (node.get("advertise_url") or "").strip(): + if nid == entries[0][0] or not peer_is_routable(node): continue entry = _peer_load_map(node).get(group_key) if entry: @@ -973,9 +1104,7 @@ def _find_free_peer(model_name: str): best_fallback = None for node in get_storage().list_nodes(): nid = node.get("node_id") - if nid == self_id or not _is_online(node): - continue - if not (node.get("advertise_url") or "").strip(): + if nid == self_id or not peer_is_routable(node): continue load = _peer_live_load(node, model_name) if not load or not _peer_can_serve(node, model_name): @@ -1011,9 +1140,7 @@ def _find_evacuation_peer(model_name: str): best = None # (rank in _CANDIDATE_ORDER, backlog, node) for node in get_storage().list_nodes(): nid = node.get("node_id") - if nid == self_id or not _is_online(node): - continue - if not (node.get("advertise_url") or "").strip(): + if nid == self_id or not peer_is_routable(node): continue load = _peer_live_load(node, model_name) if not load or not _peer_can_serve(node, model_name): diff --git a/api/llamaman.py b/api/llamaman.py index 014efc7..fe0381b 100644 --- a/api/llamaman.py +++ b/api/llamaman.py @@ -178,6 +178,7 @@ def _iter_group_members_across_cluster(name: str): Falls back silently on any storage/read error so a peer outage never breaks /api/show or the badge; the caller sees fewer members, not an exception. """ + from api.cluster import peer_is_routable from core import cluster as cl req = name.split(":")[0].lower() @@ -194,7 +195,7 @@ def _iter_group_members_across_cluster(name: str): self_id = cl.get_node_id() for inst in local_snapshot: alias = ((inst.get("config") or {}).get("share_queue_group") or "").strip() - if not alias or alias.lower() != req: + if not alias or alias.lower() != req or not (inst.get("config") or {}).get("share_queue"): continue if inst.get("status") in ("stopped", "stopping"): continue @@ -214,12 +215,12 @@ def _iter_group_members_across_cluster(name: str): nodes = [] for node in nodes: node_id = node.get("node_id") - if not node_id or node_id == self_id: - continue + if not node_id or node_id == self_id or not peer_is_routable(node): + continue # an unroutable peer's members can't serve the name, so don't shape it snapshot = node.get("snapshot") or {} for inst in snapshot.get("instances") or []: alias = ((inst.get("config") or {}).get("share_queue_group") or "").strip() - if not alias or alias.lower() != req: + if not alias or alias.lower() != req or not (inst.get("config") or {}).get("share_queue"): continue if inst.get("status") in ("stopped", "stopping"): continue @@ -622,6 +623,14 @@ def _ensure_model_running( return None, stopped_err model = _find_model_by_name(model_name) + # A group other nodes serve, none of which took this: say so, rather than + # "not found", or launching a local file the name merely substring-matches. + if not _names_file_exactly(model, model_name): + from api.cluster import group_unroutable_error + unroutable = group_unroutable_error(model_name) + if unroutable: + return None, ModelUnavailable(unroutable["code"], unroutable["message"], + http_status=unroutable["http_status"], retry_elsewhere=False) if model is None: return None, f"model '{model_name}' not found" @@ -2080,6 +2089,12 @@ def llamaman_v1_embeddings(): if not model_name: return jsonify({"error": {"message": "model is required"}}), 400 + # Cluster: an embedding group routes like any other. + from api.cluster import dispatch_inference + forwarded = dispatch_inference(model_name) + if forwarded is not None: + return forwarded + _openai_evict = _openai_can_evict_admin_instances() inst, err = _ensure_model_running( model_name, allow_eviction=_openai_evict, can_evict_admin=_openai_evict diff --git a/docs/en/CLUSTERING.md b/docs/en/CLUSTERING.md index d013fc3..c93d421 100644 --- a/docs/en/CLUSTERING.md +++ b/docs/en/CLUSTERING.md @@ -31,3 +31,57 @@ A few settings are scoped per node because they're host-specific: tracked **Dock > **Security:** the cluster secret lets any peer drive actions on this node. Run node-to-node traffic over a trusted network or behind TLS. Cluster-related environment variables: [Clustering variables](CONFIGURATION.md#clustering). + +## Queue groups + +A queue group pools instances under one **Queue group name** so a client can send that name to any node. The table shows what happens to each member from another node's point of view: + +| Member state | Listed in `/api/tags` and `/v1/models` | Gets routed traffic | +|---|---|---| +| Healthy | Yes | First choice | +| Starting (loading) | Yes | After healthy members | +| Sleeping | Yes | Last, and only after every awake member, including fallbacks. The request wakes it. | +| Stopping or stopped | No | Never | +| On a node with no `CLUSTER_ADVERTISE_URL` (view-only) | No | Never | +| On an offline node (no heartbeat for 45s) | No | Never | + +**`CLUSTER_ADVERTISE_URL` is required to receive routed work.** Without it a node can still send requests to its peers, but none can reach it. + +**Sleep and stop mean different things here.** An idle timeout puts an instance to sleep, and a sleeping member wakes when traffic needs it. A stopped member stays stopped: an operator stop, an eviction and a crash all end there, and no request from another node restarts it. Asking the node that holds it gets a `503`, unless the name is also that member's own file, which still wakes it. + +### Waking under load + +Awake members queue requests rather than refuse them, so traffic alone would only reach a sleeper after a whole queue overflowed. llamaMan therefore wakes one early. When every healthy member in the group is full, requests are queued and nothing is already loading, for 3 polls in a row (about 15 seconds), one sleeping member wakes. Across the cluster, only the lowest-named node holding a sleeper does this, and at most one member per group per poll. + +The wake is skipped, with one log line, if the model's weights don't fit in the node's free VRAM. The check adds up free memory across all GPUs and counts weights only, so a model that passes can still fail to load. If VRAM can't be read, the wake goes ahead. + +Both settings are per node, through `POST /api/settings`: + +| Setting | Default | Meaning | +|---|---|---| +| `eager_wake_enabled` | `true` | Whether this node wakes its sleepers under load | +| `eager_wake_polls` | `3` | Consecutive saturated polls (5 seconds each) before waking | + +### When a group can't be served + +If other nodes host the group but none can take a request, the client gets an error naming each node and why, not "model not found": + +| Status | Code (OpenAI routes) | Meaning | +|---|---|---| +| `429` | `group_full` | At least one peer's queue is full. Retrying can work. | +| `503` | `group_unavailable` | The peers are offline, view-only, unreachable or not ready. | + +The owning node returns these `503` codes for its own members, and an entry node tries its next member when it gets one: + +| Code | Meaning | +|---|---| +| `model_stopping` | The member is shutting down | +| `group_stopped` | Every member on this node is stopped | +| `wake_failed` | The wake failed | +| `wake_timeout` | The member didn't become healthy in time | + +### Troubleshooting a group that isn't visible + +- **The JSON backend needs one shared `DATA_DIR`.** Nodes find each other through the registry, so separate directories mean each node sees no peers. Use MariaDB unless the directory really is shared. +- **A degraded database hides peers on purpose.** With the DB mirror serving reads, a node sees only itself and serves locally. +- **A failed load probe doesn't hide a group.** A peer that doesn't answer stays routable from its snapshot (up to 45 seconds old), but ranks behind every peer that did answer. The log records when probes to a peer start failing and when they recover. diff --git a/tests/test_cluster.py b/tests/test_cluster.py index fe8f40c..27ea1ce 100644 --- a/tests/test_cluster.py +++ b/tests/test_cluster.py @@ -213,7 +213,7 @@ def tearDown(self): def _add_local(self, iid, group, status="healthy", path="/models/a.gguf", ctx=None): - cfg = {"share_queue_group": group} + cfg = {"share_queue": True, "share_queue_group": group} if ctx is not None: cfg["ctx_size"] = ctx with self._instances_lock: @@ -224,11 +224,11 @@ def _add_local(self, iid, group, status="healthy", path="/models/a.gguf", def _add_peer(self, node_id, group, status="healthy", path="/peer/x.gguf", ctx=None): - cfg = {"share_queue_group": group} + cfg = {"share_queue": True, "share_queue_group": group} if ctx is not None: cfg["ctx_size"] = ctx self.storage.register_node( - {"node_id": node_id, "node_name": node_id, "advertise_url": "", + {"node_id": node_id, "node_name": node_id, "advertise_url": f"http://{node_id}:5000", "vendor": "", "llama_image": ""}, snapshot={"instances": [{ "id": f"i-{node_id}", "model_name": "x", "model_path": path, @@ -332,7 +332,7 @@ def test_api_show_answers_for_queue_group_name(self): self._add_local("i1", "chat-14b", path="/models/qwen2.5-14b.gguf") with self._instances_lock: self._instances["i1"]["config"] = { - "share_queue_group": "chat-14b", "ctx_size": 32768, + "share_queue": True, "share_queue_group": "chat-14b", "ctx_size": 32768, } fake_meta = {"general.architecture": "qwen2", diff --git a/tests/test_honest_routing.py b/tests/test_honest_routing.py new file mode 100644 index 0000000..8916794 --- /dev/null +++ b/tests/test_honest_routing.py @@ -0,0 +1,422 @@ +# Copyright (c) llamaMan. Licensed under the Elastic License 2.0 - see LICENSE. + +"""#111 Phase 2: listings and routing agree on which peers count, a failed probe +isn't mistaken for a peer hosting nothing, and when nobody can take a request the +client hears why rather than "model not found".""" + +import json +import os +import unittest +from unittest.mock import Mock, patch + +from flask import Flask + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +os.environ.setdefault("MODELS_DIR", os.path.join(REPO_ROOT, "test-models")) +os.environ.setdefault("DATA_DIR", os.path.join(REPO_ROOT, "test-data")) +os.environ.setdefault("LOGS_DIR", os.path.join(REPO_ROOT, "test-logs")) +os.environ.setdefault("LLAMAMAN_NODE_NAME", "test-node") + +import api.cluster as ca +import api.llamaman as llamaman +from core.state import instances, instances_lock + +SELF = ca.cl.get_node_id() + + +def _inst(status="healthy", group="chat-pool", fallback=False, share_queue=True, path="/peer/m.gguf"): + return {"status": status, "model_path": path, + "config": {"share_queue": share_queue, "share_queue_group": group, + "share_queue_fallback": fallback, "ctx_size": 4096}} + + +def _peer(name, *insts, url=True, online=True): + return {"node_id": name, "node_name": name, "online": online, + "advertise_url": f"http://{name}:5000" if url else "", + "snapshot": {"system": {"features": ["alias_wake"]}, "instances": list(insts)}} + + +def _live(healthy=1, active=0, queued=0, free=1, sleeping=0): + return {"active": active, "queued": queued, "free": free, "max_concurrent": 2, "fallback": False, + "healthy": healthy, "starting": 0, "sleeping": sleeping} + + +class _Case(unittest.TestCase): + + def setUp(self): + with instances_lock: + saved = dict(instances) + instances.clear() + + def restore(): + with instances_lock: + instances.clear() + instances.update(saved) + self.addCleanup(restore) + ca._load_cache.clear() + ca._unreachable_peers.clear() + self.nodes = [] + self.storage = Mock() + self.storage.list_nodes.side_effect = lambda: self.nodes + self.addCleanup(ca._load_cache.clear) + self.addCleanup(ca._unreachable_peers.clear) + for target, value in ( + ("api.cluster.get_storage", lambda: self.storage), + ("api.llamaman.get_storage", lambda: self.storage), + ("api.cluster._is_online", lambda n: n.get("online", True)), + ("api.cluster._inflight_get", lambda _n: 0), + ("api.cluster.cl.is_cluster_enabled", lambda: True), + ("core.cluster.is_cluster_enabled", lambda: True), + ): + patcher = patch(target, value) + patcher.start() + self.addCleanup(patcher.stop) + + def app(self): + app = Flask(__name__) + app.register_blueprint(llamaman.bp) + return app + + +class AdvertisingTests(_Case): + + def _names(self): + return [g["name"] for g in ca.cluster_group_models()] + + def test_a_routable_peers_group_is_listed(self): + self.nodes = [_peer("a", _inst())] + self.assertEqual(self._names(), ["chat-pool"]) + + def test_a_view_only_peers_group_is_not_listed(self): + self.nodes = [_peer("a", _inst(), url=False)] + self.assertEqual(self._names(), []) + + def test_an_offline_peers_group_is_not_listed(self): + self.nodes = [_peer("a", _inst(), online=False)] + self.assertEqual(self._names(), []) + + def test_a_group_without_share_queue_is_not_listed(self): + self.nodes = [_peer("a", _inst(share_queue=False))] + self.assertEqual(self._names(), []) + instances["x"] = {"id": "x", **_inst(share_queue=False)} + self.assertEqual(self._names(), []) + + def test_a_sleeping_peer_member_is_still_listed(self): + self.nodes = [_peer("a", _inst("sleeping"))] + self.assertEqual(self._names(), ["chat-pool"]) + + def test_a_stopped_peer_member_is_not_listed(self): + self.nodes = [_peer("a", _inst("stopped"))] + self.assertEqual(self._names(), []) + + def test_a_local_member_is_listed_with_no_peers(self): + instances["x"] = {"id": "x", **_inst(path="/models/x.gguf")} + self.assertEqual(self._names(), ["chat-pool"]) + + def test_min_ctx_ignores_a_peer_that_cannot_serve(self): + small = _inst() + small["config"]["ctx_size"] = 1024 + self.nodes = [_peer("a", _inst()), _peer("view", small, url=False), + _peer("gone", small, online=False)] + members = list(llamaman._iter_group_members_across_cluster("chat-pool")) + self.assertEqual([m["node_id"] for m in members], ["a"]) + + +class LoadProbeTests(_Case): + + NODE = {"node_id": "a", "node_name": "a", "advertise_url": "http://a:5000"} + + def _probe(self, **kwargs): + with patch("core.cluster.cluster_request", **kwargs) as req: + return ca._peer_live_load(self.NODE, "chat-pool"), req + + def test_a_timeout_is_unreachable(self): + live, _ = self._probe(side_effect=TimeoutError("slow")) + self.assertIs(live, ca.PEER_UNREACHABLE) + self.assertFalse(live) + + def test_a_non_200_is_unreachable(self): + live, _ = self._probe(return_value=Mock(status_code=403)) + self.assertIs(live, ca.PEER_UNREACHABLE) + + def test_a_bad_body_is_unreachable(self): + live, _ = self._probe(return_value=Mock(status_code=200, json=Mock(return_value=[]))) + self.assertIs(live, ca.PEER_UNREACHABLE) + + def test_no_entry_is_not_unreachable(self): + live, _ = self._probe(return_value=Mock(status_code=200, json=Mock(return_value={}))) + self.assertIsNone(live) + + def test_an_entry_is_returned(self): + entry = _live() + live, _ = self._probe(return_value=Mock(status_code=200, json=Mock(return_value={"chat-pool": entry}))) + self.assertEqual(live, entry) + + def test_a_failure_is_cached_like_a_success(self): + self._probe(side_effect=TimeoutError("slow")) + _, req = self._probe(side_effect=TimeoutError("slow")) + req.assert_not_called() + + def test_it_logs_once_per_change_of_state(self): + with self.assertLogs("llamaman", level="INFO") as logs: + for _ in range(3): + ca._load_cache.clear() + self._probe(side_effect=TimeoutError("slow")) + ca._load_cache.clear() + self._probe(return_value=Mock(status_code=200, json=Mock(return_value={}))) + self.assertEqual(len([m for m in logs.output if "cannot read live load" in m]), 1) + self.assertEqual(len([m for m in logs.output if "readable again" in m]), 1) + + +class UnreachablePeerRoutingTests(_Case): + + def setUp(self): + super().setUp() + self.loads = {} + patcher = patch("api.cluster._peer_live_load", lambda node, _m: self.loads[node["node_id"]]) + patcher.start() + self.addCleanup(patcher.stop) + + def test_a_snapshot_member_stays_routable(self): + # The blip that made a served group briefly "not found". + self.nodes = [_peer("a", _inst())] + self.loads = {"a": ca.PEER_UNREACHABLE} + candidates = ca._group_candidates("chat-pool") + self.assertEqual(len(candidates), 1) + self.assertTrue(candidates[0]["unknown"]) + + def test_it_ranks_behind_every_peer_that_answered(self): + self.nodes = [_peer("dead", _inst()), _peer("busy", _inst()), _peer("asleep", _inst("sleeping"))] + self.loads = {"dead": ca.PEER_UNREACHABLE, "busy": _live(active=50, free=0), + "asleep": _live(healthy=0, sleeping=1, free=0)} + ordered = ca._order_candidates(ca._group_candidates("chat-pool")) + self.assertEqual([c["node"]["node_id"] for c in ordered], ["busy", "asleep", "dead"]) + + def test_a_peer_not_hosting_the_group_is_not_a_candidate(self): + self.nodes = [_peer("a", _inst(group="other"))] + self.loads = {"a": ca.PEER_UNREACHABLE} + self.assertEqual(ca._group_candidates("chat-pool"), []) + + def test_a_stopped_snapshot_member_is_not_a_candidate(self): + self.nodes = [_peer("a", _inst("stopped"))] + self.loads = {"a": ca.PEER_UNREACHABLE} + self.assertEqual(ca._group_candidates("chat-pool"), []) + + def test_an_older_peer_needs_a_healthy_snapshot_member(self): + node = _peer("a", _inst("sleeping")) + node["snapshot"]["system"]["features"] = [] + self.nodes = [node] + self.loads = {"a": ca.PEER_UNREACHABLE} + self.assertEqual(ca._group_candidates("chat-pool"), []) + + def test_it_stays_out_of_work_stealing_and_evacuation(self): + self.nodes = [_peer("a", _inst())] + self.loads = {"a": ca.PEER_UNREACHABLE} + self.assertIsNone(ca._find_free_peer("chat-pool")) + self.assertIsNone(ca._find_evacuation_peer("chat-pool")) + + def test_it_is_no_evidence_for_eager_wake(self): + self.nodes = [_peer("a", _inst())] + with patch("api.cluster._peer_load_map", return_value=ca.PEER_UNREACHABLE): + self.assertFalse(ca.group_wants_wake("chat-pool", {"sleeping": 1})) + + +class UnroutableErrorTests(_Case): + + def _error(self, name="chat-pool", refusals=None, headers=None): + from flask import g + with self.app().test_request_context("/v1/chat/completions", method="POST", headers=headers or {}): + if refusals: + g.forward_refusals = refusals + return ca.group_unroutable_error(name) + + def test_each_node_is_named_with_its_reason(self): + self.nodes = [_peer("gone", _inst(), online=False), _peer("view", _inst(), url=False)] + err = self._error() + self.assertEqual(err["http_status"], 503) + self.assertEqual(err["code"], "group_unavailable") + self.assertIn("gone (offline)", err["message"]) + self.assertIn("view (view-only, no CLUSTER_ADVERTISE_URL)", err["message"]) + + def test_a_full_peer_is_429(self): + self.nodes = [_peer("a", _inst()), _peer("gone", _inst(), online=False)] + err = self._error(refusals={"a": ca._REFUSED_FULL}) + self.assertEqual(err["http_status"], 429) + self.assertEqual(err["code"], "group_full") + self.assertIn("a (queue full)", err["message"]) + + def test_a_refused_forward_is_reported_as_such(self): + self.nodes = [_peer("a", _inst())] + err = self._error(refusals={"a": ca._REFUSED_UNREACHABLE}) + self.assertEqual(err["http_status"], 503) + self.assertIn("a (unreachable)", err["message"]) + + def test_a_partial_name_that_was_forwarded_counts(self): + # Routing is fuzzy, so a refusal means it did match something. + self.nodes = [_peer("a", _inst())] + self.assertIn("a (queue full)", self._error("chat", {"a": ca._REFUSED_FULL})["message"]) + + def test_an_unrelated_name_is_none(self): + self.nodes = [_peer("a", _inst())] + self.assertIsNone(self._error("llama-3")) + + def test_a_partial_name_nobody_tried_is_none(self): + self.nodes = [_peer("a", _inst(), online=False)] + self.assertIsNone(self._error("chat")) + + def test_only_stopped_members_is_none(self): + self.nodes = [_peer("a", _inst("stopped"))] + self.assertIsNone(self._error()) + + def test_this_node_is_not_reported(self): + self.nodes = [_peer(SELF, _inst())] + self.assertIsNone(self._error()) + + def test_a_forwarded_request_is_left_to_its_entry_node(self): + self.nodes = [_peer("gone", _inst(), online=False)] + self.assertIsNone(self._error(headers={"X-Cluster-Dispatch": "1"})) + + def test_clustering_off_is_none(self): + self.nodes = [_peer("gone", _inst(), online=False)] + with patch("api.cluster.cl.is_cluster_enabled", return_value=False): + self.assertIsNone(self._error()) + + def test_outside_a_request_is_none(self): + self.nodes = [_peer("gone", _inst(), online=False)] + self.assertIsNone(ca.group_unroutable_error("chat-pool")) + + def test_a_stem_only_pool_counts(self): + self.nodes = [_peer("gone", _inst(group=""), online=False)] + self.assertIsNotNone(self._error("m")) + + +class SurfaceTests(_Case): + """Entry node C, hosting nothing, on every surface.""" + + OPENAI = {"model": "chat-pool", "messages": [{"role": "user", "content": "hi"}]} + ROUTES = ( + ("/api/chat", OPENAI), + ("/v1/chat/completions", OPENAI), + ("/v1/completions", {"model": "chat-pool", "prompt": "hi"}), + ("/v1/embeddings", {"model": "chat-pool", "input": "hi"}), + ) + + def setUp(self): + super().setUp() + self.library = [] + for target, value in ( + ("api.llamaman._library", lambda: self.library), + ("core.model_alias.resolve_to_path", Mock(return_value=None)), + ("core.model_alias.canonical_name", lambda n: n), + ("core.engines.virtual_model_key", lambda _n: None), + ("api.llamaman._openai_can_evict_admin_instances", lambda: False), + ): + patcher = patch(target, value) + patcher.start() + self.addCleanup(patcher.stop) + + def _post(self, path, body, probe): + with patch("core.cluster.cluster_request", **probe): + return self.app().test_client().post(path, json=body) + + def _message(self, response): + error = response.get_json()["error"] + return error if isinstance(error, str) else error["message"] + + def test_every_peer_full_is_429_everywhere(self): + self.nodes = [_peer("a", _inst())] + + def request(_node, method, _path, **_kw): + if method == "GET": + return Mock(status_code=200, json=Mock(return_value={"chat-pool": _live(free=0)})) + return Mock(status_code=429, headers={}) + + for path, body in self.ROUTES: + with self.subTest(path=path): + ca._load_cache.clear() + r = self._post(path, body, {"side_effect": request}) + self.assertEqual(r.status_code, 429, r.get_data(as_text=True)) + self.assertIn("a (queue full)", self._message(r)) + + def test_only_a_view_only_member_is_503_everywhere(self): + self.nodes = [_peer("view", _inst(), url=False)] + for path, body in self.ROUTES: + with self.subTest(path=path): + r = self._post(path, body, {"side_effect": AssertionError("not contacted")}) + self.assertEqual(r.status_code, 503, r.get_data(as_text=True)) + self.assertIn("view-only", self._message(r)) + + def test_each_surface_keeps_its_shape(self): + self.nodes = [_peer("view", _inst(), url=False)] + r = self._post("/api/chat", self.OPENAI, {}) + self.assertIsInstance(r.get_json()["error"], str) + r = self._post("/v1/chat/completions", self.OPENAI, {}) + self.assertEqual(r.get_json()["error"]["code"], "group_unavailable") + + def test_a_dead_peer_is_tried_and_reported(self): + self.nodes = [_peer("dead", _inst())] + r = self._post("/v1/chat/completions", self.OPENAI, {"side_effect": ConnectionError("down")}) + self.assertEqual(r.status_code, 503) + self.assertIn("dead (unreachable)", self._message(r)) + + def test_it_does_not_launch_a_file_the_name_substring_matches(self): + self.nodes = [_peer("view", _inst(), url=False)] + self.library = [{"path": "/models/chat-pool-unrelated.gguf", "name": "x"}] + with patch("api.instances.launch_instance") as launch: + r = self._post("/v1/chat/completions", self.OPENAI, {}) + self.assertEqual(r.status_code, 503) + launch.assert_not_called() + + def test_a_file_with_exactly_that_name_still_runs_here(self): + self.nodes = [_peer("view", _inst(), url=False)] + self.library = [{"path": "/models/chat-pool.gguf", "name": "x"}] + running = {"id": "local", "status": "healthy"} + with patch.object(llamaman, "_find_running_instance_for_model", return_value=running): + inst, err = llamaman._ensure_model_running("chat-pool") + self.assertIsNone(err) + self.assertEqual(inst["id"], "local") + + def test_an_unknown_model_is_still_not_found(self): + r = self._post("/v1/chat/completions", {**self.OPENAI, "model": "llama-3"}, {}) + self.assertEqual(r.status_code, 503) + self.assertEqual(r.get_json(), {"error": {"message": "model 'llama-3' not found"}}) + + +class TimeoutShapeTests(_Case): + + def _timeout(self, path): + import requests + node = {"node_id": "a", "node_name": "a"} + with self.app().test_request_context(path, method="POST"), \ + patch("core.cluster.cluster_request", side_effect=requests.ReadTimeout("slow")): + out = ca._forward_inference(node, path, b"{}", None) + self.assertEqual(out.status_code, 504) + return json.loads(out.get_data())["error"] + + def test_ollama_gets_a_plain_string(self): + self.assertIn("did not respond", self._timeout("/api/chat")) + + def test_openai_gets_the_nested_shape(self): + self.assertIn("did not respond", self._timeout("/v1/chat/completions")["message"]) + + +class EmbeddingRoutingTests(_Case): + + def test_an_embedding_group_is_forwarded_to_its_peer(self): + self.nodes = [_peer("a", _inst())] + peer = Mock(status_code=200, headers={"Content-Type": "application/json"}, + content=b'{"data": []}') + + def request(_node, method, _path, **_kw): + if method == "GET": + return Mock(status_code=200, json=Mock(return_value={"chat-pool": _live()})) + return peer + + with patch("core.cluster.cluster_request", side_effect=request): + r = self.app().test_client().post("/v1/embeddings", json={"model": "chat-pool", "input": "hi"}) + self.assertEqual(r.status_code, 200) + self.assertEqual(r.get_json(), {"data": []}) + + +if __name__ == "__main__": + unittest.main()