Skip to content
Merged
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
26 changes: 23 additions & 3 deletions sdk/src/unplug/core/runtime/model_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,14 @@ def prepare_active_model_spec(config: GuardConfig) -> ModelSpec | None:
if path and store.is_valid_checkpoint(Path(path)):
return spec

if path:
# A path is set and is not a valid checkpoint, so the operator named one
# and got it wrong. resolve_spec_path already refuses to answer that from
# the cache; downloading or resolving a tier here would substitute a
# different model for the one they asked for, which is the same silent
# swap by another route. Hand back the bad path and let the caller fail.
return spec

if not config.auto_download_model:
return spec

Expand Down Expand Up @@ -124,9 +132,21 @@ def load_active_model_provider(
if not path or not Path(path).is_dir():
if config.require_ml:
tier = config.active_model or "unknown"
msg = (
f"Model tier {tier!r} is not available locally. Run: unplug-models download {tier}"
)
if path:
# Naming the path matters more than naming the tier here. Now that
# a bad path is refused rather than answered from the cache, this
# is the error an operator gets when they mistype one, and "tier
# 'tiny' is not available locally" sends them to re-download a
# model they already have.
msg = (
f"Model tier {tier!r} was configured with path {path!r}, which is not "
"a usable checkpoint. Fix the path or unset it to use the model cache."
)
else:
msg = (
f"Model tier {tier!r} is not available locally. "
f"Run: unplug-models download {tier}"
)
raise ModelError(msg)
return None
registry = build_model_registry()
Expand Down
29 changes: 25 additions & 4 deletions sdk/src/unplug/ml/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,19 +295,40 @@ def list_status(self) -> list[dict[str, Any]]:
return rows

def resolve_spec_path(self, spec: ModelSpec, tier: str | None = None) -> ModelSpec:
"""Fill spec.path from env override, explicit path, or cache."""
"""Fill spec.path from env override, explicit path, or cache.

The cache is only consulted when no checkpoint was asked for by name.
An operator who pins a path or sets ``UNPLUG_MODEL_PATH`` has named the
weights they want scanning their traffic, so a bad value there must not
be quietly answered with a different model out of the cache (#149).
Leaving the unusable path in place lets the caller decide what to do:
download it when ``auto_download_model`` is set, or fail.
"""
env_path = os.environ.get("UNPLUG_MODEL_PATH")
if env_path:
env = Path(env_path)
if self.is_valid_checkpoint(env):
return spec.model_copy(update={"path": env_path})
_log.warning(
"UNPLUG_MODEL_PATH=%s is set but is not a valid checkpoint "
"(need config.json and model.safetensors or pytorch_model.bin); ignoring.",
"(need config.json and model.safetensors or pytorch_model.bin). "
"Not falling back to the model cache: unset it to use the cache.",
env_path,
)

if spec.path and self.is_valid_checkpoint(Path(spec.path)):
# The bad path is written onto the spec, not dropped. Returning the spec
# unchanged leaves path unset, which downstream reads as "nothing was
# asked for" and answers from the cache or a download: the substitution
# this warning promises is not happening.
return spec.model_copy(update={"path": env_path})

if spec.path:
if self.is_valid_checkpoint(Path(spec.path)):
return spec
_log.warning(
"Configured model path %s is not a valid checkpoint. "
"Not falling back to the model cache.",
spec.path,
)
return spec

cached = self.resolve_local_path(tier or spec.name)
Expand Down
180 changes: 179 additions & 1 deletion sdk/tests/unit/ml/test_model_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,184 @@ def test_invalid_unplug_model_path_logs_warning(
spec = load_catalog().tiers["tiny"].to_model_spec()
with caplog.at_level(logging.WARNING, logger="unplug.ml.store"):
resolved = store.resolve_spec_path(spec, tier="tiny")
assert resolved.path is None
assert resolved.path == str(bad)
assert "UNPLUG_MODEL_PATH" in caplog.text
assert str(bad) in caplog.text


def _populate_cache(tmp_path: Path) -> tuple[ModelStore, Path]:
"""A store whose cache holds a usable tiny checkpoint."""
store = ModelStore(cache_root=tmp_path / "cache")
ckpt = tmp_path / "cache" / "tiny" / "checkpoint"
_write_checkpoint(ckpt, config='{"model": "cached"}')
store.write_manifest(
ModelManifest(
tier="tiny",
repo_id="Unplug-AI/test",
revision=load_catalog().tiers["tiny"].revision,
path=str(ckpt),
config_digest=_config_digest(ckpt),
)
)
assert store.resolve_local_path("tiny") == ckpt
return store, ckpt


def test_unusable_configured_path_is_not_replaced_by_cache(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A pinned checkpoint that goes bad must not be answered with another model (#149)."""
monkeypatch.delenv("UNPLUG_MODEL_PATH", raising=False)
store, cached = _populate_cache(tmp_path)
pinned = tmp_path / "pinned"
pinned.mkdir()
(pinned / "config.json").write_text("not-json", encoding="utf-8")

spec = load_catalog().tiers["tiny"].to_model_spec(path=str(pinned))
resolved = store.resolve_spec_path(spec, tier="tiny")

assert resolved.path == str(pinned)
assert resolved.path != str(cached)


def test_invalid_env_model_path_is_not_replaced_by_cache(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
store, cached = _populate_cache(tmp_path)
bad = tmp_path / "bad_env"
bad.mkdir()
(bad / "config.json").write_text("{}", encoding="utf-8")
monkeypatch.setenv("UNPLUG_MODEL_PATH", str(bad))

spec = load_catalog().tiers["tiny"].to_model_spec()
resolved = store.resolve_spec_path(spec, tier="tiny")

assert resolved.path != str(cached)
# The bad path stays on the spec. Asserting None here passed while
# prepare_active_model_spec read the empty path as "nothing was asked for"
# and downloaded the tier anyway, so the substitution survived this test.
assert resolved.path == str(bad)


def test_cache_still_resolves_when_no_path_was_configured(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The cache is still the answer when nobody named a checkpoint."""
monkeypatch.delenv("UNPLUG_MODEL_PATH", raising=False)
store, cached = _populate_cache(tmp_path)

spec = load_catalog().tiers["tiny"].to_model_spec()
resolved = store.resolve_spec_path(spec, tier="tiny")

assert resolved.path == str(cached)


def test_auto_download_does_not_substitute_for_a_bad_configured_path(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The refusal has to survive the auto-download step, not just resolve_spec_path.

auto_download_model is on by default, and prepare_active_model_spec used to
reach ensure_tier whenever the path was unusable. The warning said it was not
falling back to the cache while it did exactly that.
"""
from unplug.core.runtime.model_runtime import prepare_active_model_spec

monkeypatch.delenv("UNPLUG_MODEL_PATH", raising=False)
monkeypatch.setenv("UNPLUG_MODEL_CACHE", str(tmp_path / "cache"))
_, cached = _populate_cache(tmp_path)
bad = tmp_path / "missing_explicit"

cfg = merge_catalog_models(GuardConfig(active_model="tiny", auto_download_model=True))
models = dict(cfg.models)
models["tiny"] = models["tiny"].model_copy(update={"path": str(bad)})
resolved = prepare_active_model_spec(cfg.model_copy(update={"models": models}))

assert resolved is not None
assert resolved.path == str(bad)
assert resolved.path != str(cached)


def test_auto_download_does_not_substitute_for_a_bad_env_path(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
from unplug.core.runtime.model_runtime import prepare_active_model_spec

monkeypatch.setenv("UNPLUG_MODEL_CACHE", str(tmp_path / "cache"))
_, cached = _populate_cache(tmp_path)
bad = tmp_path / "missing_env"
monkeypatch.setenv("UNPLUG_MODEL_PATH", str(bad))

cfg = merge_catalog_models(GuardConfig(active_model="tiny", auto_download_model=True))
resolved = prepare_active_model_spec(cfg)

assert resolved is not None
assert resolved.path == str(bad)
assert resolved.path != str(cached)


def test_auto_download_still_uses_the_cache_when_no_path_was_named(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Refusing a bad path must not break the ordinary cache hit."""
from unplug.core.runtime.model_runtime import prepare_active_model_spec

monkeypatch.delenv("UNPLUG_MODEL_PATH", raising=False)
monkeypatch.setenv("UNPLUG_MODEL_CACHE", str(tmp_path / "cache"))
_, cached = _populate_cache(tmp_path)

cfg = merge_catalog_models(GuardConfig(active_model="tiny", auto_download_model=True))
resolved = prepare_active_model_spec(cfg)

assert resolved is not None
assert resolved.path == str(cached)


def test_require_ml_error_names_the_offending_path(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The operator needs to see which path was rejected, not just the tier.

Now that a bad path fails instead of being answered from the cache, this is
the error a mistyped path produces, and "tier 'tiny' is not available
locally, run unplug-models download tiny" sends them to re-download a model
they already have.
"""
from unplug.core.runtime.model_runtime import load_active_model_provider

monkeypatch.delenv("UNPLUG_MODEL_PATH", raising=False)
monkeypatch.setenv("UNPLUG_MODEL_CACHE", str(tmp_path / "empty"))
bad = tmp_path / "typo_in_this_path"

cfg = merge_catalog_models(
GuardConfig(active_model="tiny", require_ml=True, auto_download_model=False)
)
models = dict(cfg.models)
models["tiny"] = models["tiny"].model_copy(update={"path": str(bad)})
cfg = cfg.model_copy(update={"models": models})

with pytest.raises(ModelError) as excinfo:
load_active_model_provider(cfg)
assert str(bad) in str(excinfo.value)


def test_require_ml_error_still_says_download_when_no_path_was_named(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delenv("UNPLUG_MODEL_PATH", raising=False)
monkeypatch.setenv("UNPLUG_MODEL_CACHE", str(tmp_path / "empty"))
from unplug.core.runtime.model_runtime import load_active_model_provider

cfg = merge_catalog_models(
GuardConfig(active_model="tiny", require_ml=True, auto_download_model=False)
)
with pytest.raises(ModelError, match="download"):
load_active_model_provider(cfg)