Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions components.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ components:
enabled: "{{ ((auth_type | default('jwt')) == 'litellm_vkey' or (litellm_enabled | default(false) | bool)) and (langfuse_enabled | default(true) | bool) }}"
depends_on: [litellm, postgresql]

# teardown both: its own teardown also removes models deployed later from
# Headlamp, which carry no ownership labels.
# Its own teardown runs first: models deployed later (model-manager, Headlamp) carry
# no ownership labels and keep the labelled model-store PVC in use.
- name: llm_services
layer: inference
teardown: both
teardown_tasks: teardown.yaml
enabled: "{{ kserve_enabled | default(true) | bool }}"
depends_on: [kserve]

Expand Down
37 changes: 35 additions & 2 deletions model_manager/core/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ def _spawn_reconciler(m: Model, timeout: int) -> tuple[Path, bool]:
model finds it running and starts none (two would race on LiteLLM deregister/register).
Returns the log path and whether a reconciler was started.
"""
log = Path(os.environ.get("MM_RECONCILE_LOG_DIR") or tempfile.gettempdir()) / f"model-manager-reconcile-{m.name}.log"
log = _reconcile_log(m.name)
try: # O_NOFOLLOW: never write through a symlink planted at this predictable path
fd = os.open(log, os.O_WRONLY | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600)
except OSError as e:
Expand All @@ -360,6 +360,33 @@ def _spawn_reconciler(m: Model, timeout: int) -> tuple[Path, bool]:
return log, True


def _reconcile_log(name: str) -> Path:
return Path(os.environ.get("MM_RECONCILE_LOG_DIR") or tempfile.gettempdir()) / f"model-manager-reconcile-{name}.log"


def _retire_reconciler(m: Model) -> None:
"""Stop a waiting reconciler of m from registering it: a --wait deploy or undeploy takes over."""
log = _reconcile_log(m.name)
try:
fd = os.open(log, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
except OSError:
return
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError: # still running: it stops once its log is gone
log.unlink(missing_ok=True)
Comment on lines +376 to +377
finally:
os.close(fd)


def _retired(name: str, own: os.stat_result) -> bool:
try:
st = os.stat(_reconcile_log(name))
except OSError:
return True
return (st.st_dev, st.st_ino) != (own.st_dev, own.st_ino)


def _check_gpu(m: Model) -> None:
"""A device: gpu runtime must name the resource its pod requests and a GPU count. Whether the cluster
has those GPUs free is the GPU pre-flight's call (GpuRuntime.preflight), on any cluster."""
Expand Down Expand Up @@ -633,6 +660,7 @@ def render(model: Model) -> str:

timeout = int(o.wait_timeout or text(pick(m.rt, "wait_timeout")) or 900) # model load + warmup is slow
if o.wait:
_retire_reconciler(m) # this deploy registers m itself
info(f"Waiting for {m.name} to become Ready (timeout: {timeout}s)...")
problem = _wait_ready(m, timeout)
if not problem:
Expand All @@ -642,6 +670,7 @@ def render(model: Model) -> str:
else:
time.sleep(3)
if workload_ready(m) == "True":
_retire_reconciler(m)
on_ready(m)
else:
log, started = _spawn_reconciler(m, timeout)
Expand Down Expand Up @@ -676,10 +705,13 @@ def reconcile(o: Options, target: str) -> None:
"""Internal: run detached by a no-wait deploy (see _spawn_reconciler)."""
_, name, namespace, kind = (o.positional + ["", "", ""])[:4]
m, timeout = Model(name=name, namespace=namespace, kind=kind), int(o.wait_timeout or 900)
own = os.fstat(sys.stdout.fileno()) # its log; _retire_reconciler unlinks it
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if _retired(name, own):
return None
if workload_ready(m) == "True":
return on_ready(m)
return None if _retired(name, own) else on_ready(m)
time.sleep(10)
warn(f"{name} not Ready within {timeout}s — gave up before reconciling routing.")
warn(f" Reconcile with: ./model-manager deploy {name}")
Expand Down Expand Up @@ -798,6 +830,7 @@ def undeploy(o: Options, target: str) -> None:

def _remove(m: Model, wait: bool, timeout: int) -> None:
"""Delete m, its chat template and routes; with `wait`, until its pods are gone."""
_retire_reconciler(m)
k8s.delete(m.kind, m.name, m.namespace)
k8s.delete("configmap", f"{m.name}-chat-template", m.namespace, quiet=True)
routing.deregister(m)
Expand Down
7 changes: 4 additions & 3 deletions model_manager/core/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,10 @@ def _env(m: Model, catalog: Catalog, cli_args: list[str], cli_env: list[str], ba
for k, v in sorted(merged.items())]
if m.runtime == "openvino": # OVMS fetches inside the serving pod, so it needs proxy + token there
items += [f" - name: {k}\n value: {quote(v)}" for k, v in proxy_env(catalog)]
if os.environ.get("HF_TOKEN"):
items.append(" - name: HF_TOKEN\n valueFrom:\n secretKeyRef:\n"
" name: hf-token\n key: token")
# The IIM launcher refuses a gated model without HF_TOKEN, even with the weights on /mnt/models
if m.runtime in ("openvino", "intel-inference-microservices") and os.environ.get("HF_TOKEN"):
items.append(" - name: HF_TOKEN\n valueFrom:\n secretKeyRef:\n"
" name: hf-token\n key: token")
return _list(items)


Expand Down
8 changes: 6 additions & 2 deletions model_manager/core/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,12 @@ def litellm_register(m: Model) -> None:
payload["model_info"] = {"mode": mode}
info(f"Registering {m.name} with LiteLLM (api_base={url})")
for attempt in (1, 2, 3): # the proxy may still be rolling out when the model turns Ready
if _litellm("POST", f"{base}/model/new", payload) is not None and _litellm_ids(m.name, base):
return ok("Registered with LiteLLM")
if _litellm("POST", f"{base}/model/new", payload) is not None:
for _ in range(6): # another proxy worker may list it a little later: re-read, never add it twice
if _litellm_ids(m.name, base):
return ok("Registered with LiteLLM")
time.sleep(5)
return warn(f"Registered {m.name} with LiteLLM, but /model/info does not list it yet.")
if attempt < 3:
warn(f"LiteLLM registration attempt {attempt} failed — retrying")
time.sleep(attempt * 5)
Expand Down
47 changes: 47 additions & 0 deletions model_manager/tests/test_units.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,17 @@ def test_hf_token_only_on_stdin(kubectl, monkeypatch):
assert any(stdin == "hf_secret" for _, stdin in kubectl)


@pytest.mark.parametrize("argv, token, served", [((), "hf_secret", True), ((), "", False),
(("--server", "vllm"), "hf_secret", False)])
def test_hf_token_reaches_iim_serving_pod(monkeypatch, argv, token, served):
monkeypatch.setenv("HF_TOKEN", token)
_, doc = _render(monkeypatch, "llama-3-2-3b", *argv)
envs = [e for c in doc["spec"]["template"]["containers"] for e in c.get("env") or [] if e["name"] == "HF_TOKEN"]
assert envs == ([{"name": "HF_TOKEN", "valueFrom": {"secretKeyRef": {"name": "hf-token", "key": "token"}}}]
if served else [])
assert "hf_secret" not in json.dumps(doc)


def test_litellm_key_only_on_stdin(kubectl, monkeypatch):
monkeypatch.setattr(routing, "_litellm_key", lambda: "sk-master")
routing._litellm("GET", "http://litellm/model/info")
Expand Down Expand Up @@ -199,6 +210,29 @@ def test_one_reconciler_per_model(monkeypatch, tmp_path):
assert cli._spawn_reconciler(m, 5)[1] # lock released once the reconciler exits


@pytest.mark.parametrize("retire", [False, True])
def test_retired_reconciler_does_not_register(monkeypatch, tmp_path, retire):
held, registered = [], []
monkeypatch.setattr(cli.subprocess, "Popen", lambda *a, stdout, **k: held.append(os.dup(stdout.fileno())))
monkeypatch.setenv("MM_RECONCILE_LOG_DIR", str(tmp_path))
m = Model(name="m", namespace="n", kind="LLMInferenceService")
assert cli._spawn_reconciler(m, 5)[1]
if retire: # a --wait deploy or undeploy of m
cli._retire_reconciler(m)
monkeypatch.setattr(cli.sys, "stdout", os.fdopen(held[0], "w")) # the reconciler's stdout is its log
monkeypatch.setattr(cli, "workload_ready", lambda _: "True")
monkeypatch.setattr(cli, "on_ready", registered.append)
cli.reconcile(cli.parse_args(["_reconcile", "m", "n", "LLMInferenceService"]), "")
assert len(registered) == (0 if retire else 1)


def test_retire_keeps_a_finished_reconcilers_log(monkeypatch, tmp_path):
monkeypatch.setenv("MM_RECONCILE_LOG_DIR", str(tmp_path))
(tmp_path / "model-manager-reconcile-m.log").write_text("done\n") # no reconciler holds its lock
cli._retire_reconciler(Model(name="m", namespace="n"))
assert (tmp_path / "model-manager-reconcile-m.log").exists()


def test_proxy_precedence(monkeypatch, tmp_path):
for var in ("MM_HTTPS_PROXY", "HTTPS_PROXY", "https_proxy"):
monkeypatch.delenv(var, raising=False)
Expand Down Expand Up @@ -388,6 +422,19 @@ def test_litellm_register_payload(monkeypatch, category, runtime, provider_model
assert payload.get("model_info") == ({"mode": mode} if mode else None)


def test_litellm_register_rereads_instead_of_adding_twice(monkeypatch):
sent, listed = [], iter([[], [], ["id"]]) # a proxy worker that has not picked the new entry up yet
monkeypatch.setattr(routing, "litellm_enabled", lambda: True)
monkeypatch.setattr(routing, "_litellm_base", lambda: "http://litellm")
monkeypatch.setattr(routing, "litellm_deregister", lambda name: None)
monkeypatch.setattr(routing, "_internal_url", lambda m: "http://backend/v1")
monkeypatch.setattr(routing, "_litellm_ids", lambda name, base: next(listed))
monkeypatch.setattr(routing, "_litellm", lambda method, url, payload=None: sent.append(url) or "{}")
monkeypatch.setattr(routing.time, "sleep", lambda _: None)
routing.litellm_register(Model(name="m", namespace="n", category="llm", runtime="vllm", rt=RT["vllm"]))
assert sent == ["http://litellm/model/new"]


FIXTURE_CATALOG = Path(__file__).resolve().parent / "fixtures" / "models.yaml"


Expand Down
2 changes: 2 additions & 0 deletions roles/llm_services/vars/kubernetes.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
# Loaded by the Toolkit Manager teardown_tasks include (vars/<cluster_distribution>.yaml); teardown needs none.
2 changes: 2 additions & 0 deletions roles/llm_services/vars/openshift.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
# Loaded by the Toolkit Manager teardown_tasks include (vars/<cluster_distribution>.yaml); teardown needs none.