unsloth/studio/backend/tests/test_preview.py
Nilay e5cf956601
Studio: shareable per-checkpoint preview links (#6486)
* checkpoint preview endpoint

* harden new preview endpoints

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* address review

* Studio preview: pin adapter, guard streaming submit, robust copy-link

Harden the public per-checkpoint preview surface:

- Pin use_adapter=True in the preview payload sanitizer. Otherwise an
  unauthenticated /p caller can POST use_adapter=false, which calls
  disable_adapter_layers() on the shared in-memory model without restoring
  it; since load_model skips reloads for the same checkpoint, every later
  visitor (the page never sends the field) keeps getting base-model output
  instead of the fine-tuned checkpoint. Forcing it on also re-enables a
  previously disabled adapter and no-ops on merged checkpoints.
- Ignore preview-page submits while a response is streaming. The send
  button was disabled but the Enter handler still called requestSubmit(),
  so a second request could start before the first reply landed in msgs and
  reorder the chat history. Both the keydown and submit handlers now honor
  the disabled button.
- Keep the cloudflare-URL polling loop alive across transient startup fetch
  errors instead of letting one rejection halt it.
- Build the copy-link from a backend preview_ref (output dir relative to
  outputs_root, gated on previewability and the two-segment /p route limit)
  so a nested output dir no longer copies a basename-only link that 404s.
  Expose preview_ref on training run summaries.

Add route-level security tests (path traversal, payload sanitization,
asset containment, CSP header, HTML title escaping, streaming lock held
until drained) and preview_ref unit tests.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio preview: Safari-safe submit and adapter pin only for LoRA

Follow-ups from cross-browser and route simulations:

- Preview page: send the message from a shared send() helper called by both
  the form submit and the Enter key, instead of form.requestSubmit(). The
  latter throws on Safari < 16 and older iOS, which broke Enter-to-send there.
  Verified across Chromium, Firefox and WebKit with Playwright.
- Only pin use_adapter=True when the resolved checkpoint is a LoRA adapter
  (adapter_config.json present); for a merged checkpoint strip it to None.
  A merged model has no adapter to toggle, so forcing it on only produced a
  per-request "not a PeftModel" warning. The cross-request base-model
  contamination fix still holds for LoRA previews.

Add a merged-checkpoint test asserting use_adapter is stripped to None.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio preview: trim verbose comments

Tighten comments across the preview routes, page, checkpoint helpers, and tests
to short single-line notes; drop ones that just restate the code. No behavior
change (verified comment/docstring-only with comment_tools.py check).

* Harden preview routes for PR #6486

- Return a generic 400 detail on a rejected preview path so the public /p
  route never echoes the absolute install path (the real reason is logged
  server-side instead).
- Strip confirm_tool_calls, session_id and rag_scope in the preview payload
  sanitizer so the public surface stays inert regardless of the tool gate.
- Use Path.is_relative_to for the asset containment check, matching the rest
  of the codebase.
- Add img-src 'self' and font-src 'self' to the preview page CSP.
- Preview page: on a mid-stream error keep the streamed text, flag the break,
  and restore the prompt so the user can retry; drop the unused --font-sans var.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Lee Jackson <130007945+Imagineer99@users.noreply.github.com>
Co-authored-by: Daniel Han <danielhanchen@gmail.com>
2026-06-24 06:31:53 -07:00

134 lines
4.5 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import json
from pathlib import Path
import sys
import types as _types
import pytest
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
_loggers_stub = _types.ModuleType("loggers")
_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
sys.modules.setdefault("loggers", _loggers_stub)
from utils.models.checkpoints import (
list_preview_targets,
preview_ref,
resolve_preview_checkpoint,
)
def _make_run(outputs: Path) -> tuple[Path, Path]:
run = outputs / "unsloth_SmolLM-135M_1775412608"
run.mkdir(parents = True)
(run / "adapter_config.json").write_text(
json.dumps({"base_model_name_or_path": "HuggingFaceTB/SmolLM-135M"})
)
ckpt = run / "checkpoint-60"
ckpt.mkdir()
(ckpt / "adapter_config.json").write_text(
json.dumps({"base_model_name_or_path": "HuggingFaceTB/SmolLM-135M"})
)
return run, ckpt
def _point_outputs_root_at(monkeypatch, outputs: Path) -> None:
from utils.paths import storage_roots as _sr
from utils.models import checkpoints as _ckpt
monkeypatch.setattr(_sr, "outputs_root", lambda: outputs)
# checkpoints imported outputs_root by name; patch that alias too (preview_ref uses it).
monkeypatch.setattr(_ckpt, "outputs_root", lambda: outputs)
def test_resolve_main_adapter_and_checkpoint(tmp_path: Path, monkeypatch):
outputs = tmp_path / "outputs"
run, ckpt = _make_run(outputs)
_point_outputs_root_at(monkeypatch, outputs)
assert resolve_preview_checkpoint(run.name) == run
assert resolve_preview_checkpoint(run.name, "checkpoint-60") == ckpt
def test_resolve_missing_raises_not_found(tmp_path: Path, monkeypatch):
outputs = tmp_path / "outputs"
_make_run(outputs)
_point_outputs_root_at(monkeypatch, outputs)
with pytest.raises(FileNotFoundError):
resolve_preview_checkpoint("does-not-exist")
(outputs / "empty").mkdir()
with pytest.raises(FileNotFoundError):
resolve_preview_checkpoint("empty")
def test_resolve_rejects_traversal(tmp_path: Path, monkeypatch):
outputs = tmp_path / "outputs"
_make_run(outputs)
_point_outputs_root_at(monkeypatch, outputs)
with pytest.raises(ValueError):
resolve_preview_checkpoint("..", "etc")
def test_list_preview_targets_flattens_with_latest_flag(tmp_path: Path, monkeypatch):
outputs = tmp_path / "outputs"
run, _ = _make_run(outputs)
_point_outputs_root_at(monkeypatch, outputs)
targets = list_preview_targets(str(outputs))
by_ref = {t["ref"]: t for t in targets}
assert by_ref[run.name]["is_latest"] is True
assert by_ref[run.name]["checkpoint"] is None
assert by_ref[f"{run.name}/checkpoint-60"]["is_latest"] is False
assert by_ref[f"{run.name}/checkpoint-60"]["checkpoint"] == "checkpoint-60"
assert all(t["base_model"] == "HuggingFaceTB/SmolLM-135M" for t in targets)
def test_preview_ref_flat_run_is_basename(tmp_path: Path, monkeypatch):
outputs = tmp_path / "outputs"
run, _ = _make_run(outputs)
_point_outputs_root_at(monkeypatch, outputs)
assert preview_ref(str(run)) == run.name
def test_preview_ref_preserves_one_level_nesting(tmp_path: Path, monkeypatch):
outputs = tmp_path / "outputs"
_point_outputs_root_at(monkeypatch, outputs)
nested = outputs / "experiments" / "run1"
nested.mkdir(parents = True)
(nested / "adapter_config.json").write_text("{}")
# /p route supports run/checkpoint, so a single level of nesting survives.
assert preview_ref(str(nested)) == "experiments/run1"
def test_preview_ref_none_for_unpreviewable_or_too_deep(tmp_path: Path, monkeypatch):
outputs = tmp_path / "outputs"
_point_outputs_root_at(monkeypatch, outputs)
# Missing / no model artifact -> not previewable.
assert preview_ref(None) is None
empty = outputs / "empty"
empty.mkdir(parents = True)
assert preview_ref(str(empty)) is None
# Too deep for the two-segment /p route -> no dead link.
deep = outputs / "a" / "b" / "run"
deep.mkdir(parents = True)
(deep / "adapter_config.json").write_text("{}")
assert preview_ref(str(deep)) is None
# Outside outputs_root -> None.
outside = tmp_path / "elsewhere"
outside.mkdir()
(outside / "adapter_config.json").write_text("{}")
assert preview_ref(str(outside)) is None