Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

42.9 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

from __future__ import annotations

import json
import secrets
import tempfile
import zipfile
from pathlib import Path

import pytest
from fastapi import HTTPException

import math

from core.data_recipe.export import (
    RecipeDatasetExportError,
    _json_dumps_row,
    _sanitize_json_value,
    build_dataset_download,
)


def _write_parquet_rows(parquet_dir: Path, rows: list[dict]) -> None:
    pytest.importorskip("pyarrow")
    pytest.importorskip("pandas")
    import pandas as pd

    parquet_dir.mkdir(parents = True, exist_ok = True)
    pd.DataFrame(rows).to_parquet(parquet_dir / "batch_00000.parquet", index = False)


def test_build_dataset_download_jsonl_from_artifact(tmp_path: Path, monkeypatch):
    artifact_root = tmp_path / "recipe-datasets"
    dataset_path = artifact_root / "job-123"
    parquet_dir = dataset_path / "parquet-files"
    _write_parquet_rows(parquet_dir, [{"question": "Q1", "answer": "A1"}])

    monkeypatch.setattr(
        "core.data_recipe.export._resolve_recipe_artifact_path",
        lambda artifact_path: dataset_path,
    )

    file_path, media_type, download_name = build_dataset_download(
        artifact_path = str(dataset_path),
        export_format = "jsonl",
        filename_stem = "my-run",
    )
    try:
        assert media_type == "application/x-ndjson"
        assert download_name == "my-run.jsonl"
        lines = file_path.read_text(encoding = "utf-8").strip().splitlines()
        assert json.loads(lines[0])["question"] == "Q1"
    finally:
        file_path.unlink(missing_ok = True)


def test_json_dumps_row_replaces_non_finite_numbers_with_null():
    row = {"score": float("nan"), "ratio": float("inf"), "label": "ok"}
    payload = json.loads(_json_dumps_row(row))
    assert payload == {"score": None, "ratio": None, "label": "ok"}


def test_sanitize_json_value_handles_numpy_nan():
    numpy = pytest.importorskip("numpy")
    assert _sanitize_json_value(numpy.float64("nan")) is None
    assert _sanitize_json_value(numpy.float64("inf")) is None
    assert math.isclose(_sanitize_json_value(numpy.float64(1.5)), 1.5)


def test_build_dataset_download_preserves_row_order_within_shard(tmp_path: Path, monkeypatch):
    pytest.importorskip("pyarrow")
    pytest.importorskip("pandas")
    import pandas as pd

    artifact_root = tmp_path / "recipe-datasets"
    dataset_path = artifact_root / "job-order"
    parquet_dir = dataset_path / "parquet-files"
    parquet_dir.mkdir(parents = True, exist_ok = True)
    pd.DataFrame(
        [
            {"sequence": "first"},
            {"sequence": "second"},
            {"sequence": "third"},
        ]
    ).to_parquet(parquet_dir / "batch_00000.parquet", index = False)

    monkeypatch.setattr(
        "core.data_recipe.export._resolve_recipe_artifact_path",
        lambda artifact_path: dataset_path,
    )

    file_path, _, _ = build_dataset_download(
        artifact_path = str(dataset_path),
        export_format = "jsonl",
        filename_stem = "ordered",
    )
    try:
        lines = file_path.read_text(encoding = "utf-8").strip().splitlines()
        sequences = [json.loads(line)["sequence"] for line in lines]
        assert sequences == ["first", "second", "third"]
    finally:
        file_path.unlink(missing_ok = True)


def test_build_dataset_download_exports_every_row_once_across_shards(tmp_path: Path, monkeypatch):
    """Sorted shards and row-group iteration must emit every artifact row exactly once."""
    pytest.importorskip("pyarrow")
    pytest.importorskip("pandas")
    import pandas as pd

    dataset_path = tmp_path / "recipe-datasets" / "job-big"
    parquet_dir = dataset_path / "parquet-files"
    parquet_dir.mkdir(parents = True)
    shard_size = 40_000
    for shard, start in enumerate(range(0, 2 * shard_size, shard_size)):
        pd.DataFrame({"i": range(start, start + shard_size)}).to_parquet(
            parquet_dir / f"batch_{shard:05d}.parquet",
            index = False,
            row_group_size = 5_000,
        )

    monkeypatch.setattr(
        "core.data_recipe.export._resolve_recipe_artifact_path",
        lambda artifact_path: dataset_path,
    )

    file_path, _, _ = build_dataset_download(
        artifact_path = str(dataset_path),
        export_format = "jsonl",
        filename_stem = "big",
    )
    try:
        exported = [
            json.loads(line)["i"] for line in file_path.read_text(encoding = "utf-8").splitlines()
        ]
    finally:
        file_path.unlink(missing_ok = True)
    assert exported == list(range(2 * shard_size))


def test_build_dataset_download_leaves_no_temp_file_when_export_fails(tmp_path: Path, monkeypatch):
    dataset_path = tmp_path / "recipe-datasets" / "job-fails"
    _write_parquet_rows(dataset_path / "parquet-files", [{"col": "value"}])
    monkeypatch.setattr(
        "core.data_recipe.export._resolve_recipe_artifact_path",
        lambda artifact_path: dataset_path,
    )
    monkeypatch.setattr(
        "core.data_recipe.export._write_jsonl_from_parquet",
        lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("export blew up")),
    )

    # Private tempdir: siblings on other xdist workers leave .jsonl files in the shared one.
    system_temp = tmp_path / "system-temp"
    system_temp.mkdir()
    monkeypatch.setattr(tempfile, "tempdir", str(system_temp))
    assert Path(tempfile.gettempdir()) == system_temp, "the export must allocate under our dir"

    with pytest.raises(RuntimeError):
        build_dataset_download(
            artifact_path = str(dataset_path),
            export_format = "jsonl",
            filename_stem = "leaky",
        )
    assert sorted(system_temp.iterdir()) == [], (
        "the failed export left its temporary file behind: "
        f"{sorted(p.name for p in system_temp.iterdir())}"
    )


def test_build_dataset_download_parquet_zip_includes_images(tmp_path: Path, monkeypatch):
    artifact_root = tmp_path / "recipe-datasets"
    dataset_path = artifact_root / "job-images"
    parquet_dir = dataset_path / "parquet-files"
    images_dir = dataset_path / "images" / "nested"
    _write_parquet_rows(parquet_dir, [{"image": "images/nested/pic.png"}])
    images_dir.mkdir(parents = True, exist_ok = True)
    (images_dir / "pic.png").write_bytes(b"png-bytes")

    monkeypatch.setattr(
        "core.data_recipe.export._resolve_recipe_artifact_path",
        lambda artifact_path: dataset_path,
    )

    file_path, _, _ = build_dataset_download(
        artifact_path = str(dataset_path),
        export_format = "parquet",
        filename_stem = "with-images",
    )
    try:
        with zipfile.ZipFile(file_path) as archive:
            names = archive.namelist()
            image_bytes = archive.read("images/nested/pic.png")
        assert "batch_00000.parquet" in names
        assert "images/nested/pic.png" in names
        assert image_bytes == b"png-bytes"
    finally:
        file_path.unlink(missing_ok = True)


def test_build_dataset_download_parquet_zip_from_artifact(tmp_path: Path, monkeypatch):
    artifact_root = tmp_path / "recipe-datasets"
    dataset_path = artifact_root / "job-456"
    parquet_dir = dataset_path / "parquet-files"
    _write_parquet_rows(parquet_dir, [{"col": "value"}])

    monkeypatch.setattr(
        "core.data_recipe.export._resolve_recipe_artifact_path",
        lambda artifact_path: dataset_path,
    )

    file_path, media_type, download_name = build_dataset_download(
        artifact_path = str(dataset_path),
        export_format = "parquet",
        filename_stem = "parquet-run",
    )
    try:
        assert media_type == "application/zip"
        assert download_name == "parquet-run.parquet.zip"
        with zipfile.ZipFile(file_path) as archive:
            names = archive.namelist()
        assert names == ["batch_00000.parquet"]
    finally:
        file_path.unlink(missing_ok = True)


def test_build_dataset_download_missing_parquet_raises(tmp_path: Path, monkeypatch):
    dataset_path = tmp_path / "empty-artifact"
    dataset_path.mkdir()
    monkeypatch.setattr(
        "core.data_recipe.export._resolve_recipe_artifact_path",
        lambda artifact_path: dataset_path,
    )

    with pytest.raises(RecipeDatasetExportError, match = "parquet"):
        build_dataset_download(
            artifact_path = str(dataset_path),
            export_format = "jsonl",
            filename_stem = "missing",
        )


def test_download_job_dataset_route_uses_artifact_path(monkeypatch, tmp_path: Path):
    pytest.importorskip("fastapi")
    from fastapi import BackgroundTasks

    jobs_route = pytest.importorskip(
        "routes.data_recipe.jobs",
        reason = "studio backend routes unavailable",
    )

    captured: dict[str, str] = {}

    def fake_build_dataset_download(**kwargs):
        captured.update(kwargs)
        jsonl_path = tmp_path / "out.jsonl"
        jsonl_path.write_text('{"ok": true}\n', encoding = "utf-8")
        return jsonl_path, "application/x-ndjson", "run.jsonl"

    class _FakeManager:
        def get_status(self, job_id: str):
            return {
                "status": "completed",
                "artifact_path": "/tmp/artifacts/job-1",
            }

    monkeypatch.setattr(jobs_route, "build_dataset_download", fake_build_dataset_download)
    monkeypatch.setattr(jobs_route, "get_job_manager", lambda: _FakeManager())
    monkeypatch.setattr(
        jobs_route,
        "download_filename",
        lambda *, artifact_path, export_format, stem: f"{stem}.jsonl",
    )

    response = jobs_route.download_job_dataset(
        "job-1",
        background_tasks = BackgroundTasks(),
        export_format = "jsonl",
        artifact_path = None,
        filename = "My Run",
    )
    assert captured["artifact_path"] == "/tmp/artifacts/job-1"
    assert captured["filename_stem"] == "My Run"
    assert response.filename == "run.jsonl"


def test_download_job_dataset_route_rejects_incomplete_run(monkeypatch):
    pytest.importorskip("fastapi")
    from fastapi import BackgroundTasks

    jobs_route = pytest.importorskip("routes.data_recipe.jobs")

    class _FakeManager:
        def get_status(self, job_id: str):
            return {"status": "running", "artifact_path": "/tmp/artifacts/job-1"}

    monkeypatch.setattr(jobs_route, "get_job_manager", lambda: _FakeManager())

    with pytest.raises(HTTPException) as exc_info:
        jobs_route.download_job_dataset(
            "job-1",
            background_tasks = BackgroundTasks(),
            export_format = "jsonl",
            artifact_path = None,
            filename = None,
        )
    assert exc_info.value.status_code == 409


def test_build_in_memory_job_dataset_download_pages_all_rows(monkeypatch, tmp_path: Path):
    pytest.importorskip("fastapi")
    from fastapi import BackgroundTasks

    jobs_route = pytest.importorskip("routes.data_recipe.jobs")

    class _FakeManager:
        def __init__(self):
            self.rows = [{"index": index} for index in range(12_500)]
            self.calls: list[tuple[int, int]] = []

        def get_status(self, job_id: str):
            return {"status": "completed", "artifact_path": None}

        def get_dataset(
            self,
            job_id: str,
            *,
            limit: int,
            offset: int = 0,
        ):
            self.calls.append((limit, offset))
            page = self.rows[offset : offset + limit]
            return {"dataset": page, "total": len(self.rows)}

    fake_manager = _FakeManager()
    monkeypatch.setattr(jobs_route, "get_job_manager", lambda: fake_manager)

    response = jobs_route.download_job_dataset(
        "job-big",
        background_tasks = BackgroundTasks(),
        export_format = "jsonl",
        artifact_path = None,
        filename = "big-run",
    )
    try:
        assert response.filename == "big-run.jsonl"
        assert fake_manager.calls == [
            (jobs_route._IN_MEMORY_DOWNLOAD_PAGE_SIZE, 0),
            (jobs_route._IN_MEMORY_DOWNLOAD_PAGE_SIZE, 10_000),
        ]
        lines = Path(response.path).read_text(encoding = "utf-8").strip().splitlines()
        assert len(lines) == 12_500
        assert json.loads(lines[-1]) == {"index": 12_499}
    finally:
        Path(response.path).unlink(missing_ok = True)


def _download_app(monkeypatch, tmp_path: Path, jobs_route):
    """The real /api/data-recipe mount, with an auth database of its own."""
    from fastapi import FastAPI

    from auth import storage

    monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth.db")
    monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")
    monkeypatch.setattr(storage, "_bootstrap_password", None)
    storage._reset_api_key_hash_cache()
    storage.create_initial_user(
        username = storage.DEFAULT_ADMIN_USERNAME,
        password = "human-password-123",
        jwt_secret = secrets.token_urlsafe(64),
    )

    from auth.authentication import create_access_token
    from routes.data_recipe import router as data_recipe_router

    def fake_build_dataset_download(**_kwargs):
        jsonl_path = tmp_path / "out.jsonl"
        jsonl_path.write_text('{"ok": true}\n', encoding = "utf-8")
        return jsonl_path, "application/x-ndjson", "run.jsonl"

    class _FakeManager:
        def get_status(self, job_id: str):
            return {"status": "completed", "artifact_path": "/tmp/artifacts/job-1"}

    monkeypatch.setattr(jobs_route, "build_dataset_download", fake_build_dataset_download)
    monkeypatch.setattr(jobs_route, "get_job_manager", lambda: _FakeManager())
    monkeypatch.setattr(
        jobs_route,
        "download_filename",
        lambda *, artifact_path, export_format, stem: f"{stem}.jsonl",
    )

    app = FastAPI()
    app.include_router(data_recipe_router, prefix = "/api/data-recipe")
    return app, create_access_token(storage.DEFAULT_ADMIN_USERNAME)


def test_download_link_is_minted_over_the_bearer_and_used_without_one(monkeypatch, tmp_path: Path):
    """Download history would keep a session token, so the URL carries a signed capability."""
    pytest.importorskip("fastapi")
    from fastapi.testclient import TestClient

    jobs_route = pytest.importorskip("routes.data_recipe.jobs")
    app, token = _download_app(monkeypatch, tmp_path, jobs_route)
    client = TestClient(app)

    minted = client.get(
        "/api/data-recipe/jobs/job-1/download-url",
        headers = {"Authorization": f"Bearer {token}"},
    )
    assert minted.status_code == 200
    url = "/api/data-recipe" + minted.json()["path"]
    assert token not in url

    assert client.get(url).status_code == 200
    assert (
        client.get(
            "/api/data-recipe/jobs/job-1/download",
            headers = {"Authorization": f"Bearer {token}"},
        ).status_code
        == 200
    )


def test_minting_a_download_link_needs_the_bearer(monkeypatch, tmp_path: Path):
    pytest.importorskip("fastapi")
    from fastapi.testclient import TestClient

    jobs_route = pytest.importorskip("routes.data_recipe.jobs")
    app, _token = _download_app(monkeypatch, tmp_path, jobs_route)

    assert TestClient(app).get("/api/data-recipe/jobs/job-1/download-url").status_code == 401


def test_download_route_refuses_an_unsigned_or_repointed_link(monkeypatch, tmp_path: Path):
    pytest.importorskip("fastapi")
    from fastapi.testclient import TestClient
    from urllib.parse import parse_qs, urlparse

    jobs_route = pytest.importorskip("routes.data_recipe.jobs")
    app, token = _download_app(monkeypatch, tmp_path, jobs_route)
    client = TestClient(app)

    assert client.get("/api/data-recipe/jobs/job-1/download").status_code == 401
    assert (
        client.get(
            "/api/data-recipe/jobs/job-1/download",
            params = {"token": "not-a-real-token"},
        ).status_code
        == 401
    )
    assert (
        client.get(
            "/api/data-recipe/jobs/job-1/download",
            params = {"token": token},
        ).status_code
        == 401
    )

    url = client.get(
        "/api/data-recipe/jobs/job-1/download-url",
        params = {"artifact_path": "/recipes/mine"},
        headers = {"Authorization": f"Bearer {token}"},
    ).json()["path"]
    signed = parse_qs(urlparse(url).query)["token"][0]
    assert (
        client.get(
            "/api/data-recipe/jobs/job-1/download",
            params = {"artifact_path": "/recipes/someone-else", "token": signed},
        ).status_code
        == 401
    )


def test_download_link_expires(monkeypatch, tmp_path: Path):
    pytest.importorskip("fastapi")
    from fastapi.testclient import TestClient

    jobs_route = pytest.importorskip("routes.data_recipe.jobs")
    app, token = _download_app(monkeypatch, tmp_path, jobs_route)
    client = TestClient(app)

    url = (
        "/api/data-recipe"
        + client.get(
            "/api/data-recipe/jobs/job-1/download-url",
            headers = {"Authorization": f"Bearer {token}"},
        ).json()["path"]
    )
    assert client.get(url).status_code == 200

    real_time = jobs_route.time.time
    monkeypatch.setattr(
        jobs_route.time,
        "time",
        lambda: real_time() + jobs_route._DOWNLOAD_LINK_TTL + 1,
    )
    assert client.get(url).status_code == 401


def _write_appledouble_companion(path: Path) -> None:
    from utils.paths.path_utils import _MAGIC
    path.write_bytes(_MAGIC + b"\x00" * 60)


def test_build_dataset_download_ignores_appledouble_companions(tmp_path: Path, monkeypatch):
    """AppleDouble companions are neither readable shards nor downloadable image files."""
    dataset_path = tmp_path / "recipe-datasets" / "job-macos"
    parquet_dir = dataset_path / "parquet-files"
    _write_parquet_rows(parquet_dir, [{"i": 0}, {"i": 1}])
    _write_appledouble_companion(parquet_dir / "._batch_00000.parquet")
    images_dir = dataset_path / "images"
    images_dir.mkdir(parents = True)
    (images_dir / "pic.png").write_bytes(b"png-bytes")
    _write_appledouble_companion(images_dir / "._pic.png")

    monkeypatch.setattr(
        "core.data_recipe.export._resolve_recipe_artifact_path",
        lambda artifact_path: dataset_path,
    )

    from core.data_recipe.export import _write_jsonl_from_parquet

    streamed = tmp_path / "streamed.jsonl"
    _write_jsonl_from_parquet(
        parquet_dir = parquet_dir,
        destination = streamed,
    )
    assert [json.loads(line)["i"] for line in streamed.read_text().splitlines()] == [0, 1]

    file_path, _, _ = build_dataset_download(
        artifact_path = str(dataset_path),
        export_format = "parquet",
        filename_stem = "macos",
    )
    try:
        with zipfile.ZipFile(file_path) as archive:
            names = archive.namelist()
    finally:
        file_path.unlink(missing_ok = True)
    assert names == ["batch_00000.parquet", "images/pic.png"]


def test_build_dataset_download_keeps_a_real_file_named_like_a_companion(
    tmp_path: Path, monkeypatch
):
    """The name alone does not decide it: a genuine shard called ._batch.parquet is still a shard."""
    dataset_path = tmp_path / "recipe-datasets" / "job-dotunder"
    parquet_dir = dataset_path / "parquet-files"
    _write_parquet_rows(parquet_dir, [{"i": 0}])
    (parquet_dir / "batch_00000.parquet").rename(parquet_dir / "._batch_00000.parquet")

    monkeypatch.setattr(
        "core.data_recipe.export._resolve_recipe_artifact_path",
        lambda artifact_path: dataset_path,
    )

    file_path, _, _ = build_dataset_download(
        artifact_path = str(dataset_path),
        export_format = "jsonl",
        filename_stem = "dotunder",
    )
    try:
        assert [json.loads(line)["i"] for line in file_path.read_text().splitlines()] == [0]
    finally:
        file_path.unlink(missing_ok = True)


def test_jsonl_reader_preserves_a_high_precision_decimal_number(tmp_path: Path, monkeypatch):
    """A durable JSONL export must not round a parquet decimal through binary float."""
    pyarrow = pytest.importorskip("pyarrow")
    import pyarrow.parquet as pyarrow_parquet
    from decimal import Decimal

    from core.data_recipe.export import _write_jsonl_from_parquet

    parquet_dir = tmp_path / "parquet-files"
    parquet_dir.mkdir(parents = True)
    expected = Decimal("0.1234567890123456789012345678")
    pyarrow_parquet.write_table(
        pyarrow.table({"price": pyarrow.array([expected], type = pyarrow.decimal128(28, 28))}),
        parquet_dir / "batch_00000.parquet",
    )

    streamed = tmp_path / "streamed.jsonl"
    _write_jsonl_from_parquet(
        parquet_dir = parquet_dir,
        destination = streamed,
    )

    assert json.loads(streamed.read_text().strip(), parse_float = Decimal) == {"price": expected}


def test_to_jsonable_maps_pandas_missing_sentinels_to_none():
    """NaT isoformat()s to "NaT" and NA hits the str() fallback as "<NA>", either of which writes
    a real value where the dataset had none."""
    pd = pytest.importorskip("pandas")
    from core.data_recipe.jsonable import to_jsonable, to_preview_jsonable

    for sentinel in (pd.NA, pd.NaT):
        assert to_jsonable(sentinel) is None
        assert to_preview_jsonable(sentinel) is None


def test_to_jsonable_maps_non_finite_numbers_to_none():
    np = pytest.importorskip("numpy")
    from core.data_recipe.jsonable import to_jsonable, to_preview_jsonable

    for value in (float("nan"), float("inf"), -math.inf, np.float64("nan"), np.float32("nan")):
        assert to_jsonable(value) is None
        assert to_preview_jsonable(value) is None
    assert to_jsonable(np.float32(0.5)) == 0.5
    assert to_jsonable(1.5) == 1.5


def test_job_dataset_route_returns_a_missing_number_as_null(monkeypatch):
    pd = pytest.importorskip("pandas")
    from fastapi import FastAPI
    from fastapi.testclient import TestClient

    from core.data_recipe.jsonable import to_preview_jsonable_row

    jobs_route = pytest.importorskip(
        "routes.data_recipe.jobs",
        reason = "studio backend routes unavailable",
    )

    frame = pd.DataFrame({"question": ["Q1", "Q2"], "score": [1.0, None]})
    rows = to_preview_jsonable_row(frame.to_dict(orient = "records"))

    class _FakeManager:
        def get_dataset(
            self,
            job_id: str,
            *,
            limit: int,
            offset: int = 0,
        ):
            return {"dataset": rows[offset : offset + limit], "total": len(rows)}

    monkeypatch.setattr(jobs_route, "get_job_manager", lambda: _FakeManager())
    app = FastAPI()
    app.include_router(jobs_route.router)

    response = TestClient(app, raise_server_exceptions = False).get("/jobs/job-1/dataset")

    assert response.status_code == 200
    assert response.json()["dataset"] == [
        {"question": "Q1", "score": 1.0},
        {"question": "Q2", "score": None},
    ]


def test_build_dataset_download_writes_a_missing_timestamp_as_null(tmp_path: Path, monkeypatch):
    pytest.importorskip("pyarrow")
    pd = pytest.importorskip("pandas")

    dataset_path = tmp_path / "recipe-datasets" / "job-nat"
    parquet_dir = dataset_path / "parquet-files"
    parquet_dir.mkdir(parents = True)
    pd.DataFrame(
        {
            "seen_at": pd.to_datetime(["2020-01-01", None]),
            "score": pd.array([1, None], dtype = "Int64"),
        }
    ).to_parquet(parquet_dir / "batch_00000.parquet", index = False)

    monkeypatch.setattr(
        "core.data_recipe.export._resolve_recipe_artifact_path",
        lambda artifact_path: dataset_path,
    )

    file_path, _, _ = build_dataset_download(
        artifact_path = str(dataset_path),
        export_format = "jsonl",
        filename_stem = "nat",
    )
    try:
        rows = [json.loads(line) for line in file_path.read_text(encoding = "utf-8").splitlines()]
    finally:
        file_path.unlink(missing_ok = True)
    assert rows[0]["seen_at"].startswith("2020-01-01")
    assert rows[1] == {"seen_at": None, "score": None}


def test_jsonl_export_ships_the_images_its_rows_reference(tmp_path: Path, monkeypatch):
    """Rows carry relative image paths, so a bare JSONL loses every image."""
    dataset_path = tmp_path / "recipe-datasets" / "job-multimodal"
    _write_parquet_rows(dataset_path / "parquet-files", [{"image": "images/nested/pic.png"}])
    nested = dataset_path / "images" / "nested"
    nested.mkdir(parents = True)
    (nested / "pic.png").write_bytes(b"png-bytes")

    monkeypatch.setattr(
        "core.data_recipe.export._resolve_recipe_artifact_path",
        lambda artifact_path: dataset_path,
    )

    from core.data_recipe.export import download_filename

    assert (
        download_filename(artifact_path = str(dataset_path), export_format = "jsonl", stem = "run")
        == "run.jsonl.zip"
    )

    file_path, media_type, download_name = build_dataset_download(
        artifact_path = str(dataset_path),
        export_format = "jsonl",
        filename_stem = "run",
    )
    try:
        assert media_type == "application/zip"
        assert download_name == "run.jsonl.zip"
        with zipfile.ZipFile(file_path) as archive:
            names = sorted(archive.namelist())
            rows = archive.read("run.jsonl").decode("utf-8")
            assert archive.read("images/nested/pic.png") == b"png-bytes"
    finally:
        file_path.unlink(missing_ok = True)
    assert names == ["images/nested/pic.png", "run.jsonl"]
    assert json.loads(rows.strip()) == {"image": "images/nested/pic.png"}


def test_jsonl_export_stays_a_plain_file_without_images(tmp_path: Path, monkeypatch):
    dataset_path = tmp_path / "recipe-datasets" / "job-text-only"
    _write_parquet_rows(dataset_path / "parquet-files", [{"text": "hello"}])
    monkeypatch.setattr(
        "core.data_recipe.export._resolve_recipe_artifact_path",
        lambda artifact_path: dataset_path,
    )

    from core.data_recipe.export import download_filename

    assert (
        download_filename(artifact_path = str(dataset_path), export_format = "jsonl", stem = "run")
        == "run.jsonl"
    )
    file_path, media_type, download_name = build_dataset_download(
        artifact_path = str(dataset_path),
        export_format = "jsonl",
        filename_stem = "run",
    )
    try:
        assert (media_type, download_name) == ("application/x-ndjson", "run.jsonl")
    finally:
        file_path.unlink(missing_ok = True)


def _schema_transform_artifact(tmp_path: Path, monkeypatch) -> Path:
    dataset_path = tmp_path / "recipe-datasets" / "job-schema-transform"
    _write_parquet_rows(dataset_path / "parquet-files", [{"question": "Q1", "answer": "A1"}])
    _write_parquet_rows(
        dataset_path / "processors-files" / "chat_format",
        [
            {
                "messages": [
                    {"role": "user", "content": "Q1"},
                    {"role": "assistant", "content": "A1"},
                ]
            }
        ],
    )
    monkeypatch.setattr(
        "core.data_recipe.export._resolve_recipe_artifact_path",
        lambda artifact_path: dataset_path,
    )
    return dataset_path


def test_jsonl_export_includes_schema_transform_output(tmp_path: Path, monkeypatch):
    dataset_path = _schema_transform_artifact(tmp_path, monkeypatch)

    from core.data_recipe.export import download_filename

    assert (
        download_filename(artifact_path = str(dataset_path), export_format = "jsonl", stem = "run")
        == "run.jsonl.zip"
    )
    file_path, media_type, download_name = build_dataset_download(
        artifact_path = str(dataset_path),
        export_format = "jsonl",
        filename_stem = "run",
    )
    try:
        assert (media_type, download_name) == ("application/zip", "run.jsonl.zip")
        with zipfile.ZipFile(file_path) as archive:
            names = sorted(archive.namelist())
            rows = archive.read("run.jsonl").decode("utf-8")
            transformed = archive.read("processors/chat_format.jsonl").decode("utf-8")
    finally:
        file_path.unlink(missing_ok = True)
    assert names == ["processors/chat_format.jsonl", "run.jsonl"]
    assert json.loads(rows.strip()) == {"question": "Q1", "answer": "A1"}
    assert json.loads(transformed.strip()) == {
        "messages": [
            {"role": "user", "content": "Q1"},
            {"role": "assistant", "content": "A1"},
        ]
    }


def test_parquet_export_includes_schema_transform_output(tmp_path: Path, monkeypatch):
    dataset_path = _schema_transform_artifact(tmp_path, monkeypatch)

    file_path, _, _ = build_dataset_download(
        artifact_path = str(dataset_path),
        export_format = "parquet",
        filename_stem = "run",
    )
    try:
        with zipfile.ZipFile(file_path) as archive:
            names = sorted(archive.namelist())
    finally:
        file_path.unlink(missing_ok = True)
    assert names == ["batch_00000.parquet", "processors/chat_format/batch_00000.parquet"]


@pytest.mark.parametrize(
    ("export_format", "expected"),
    [
        (
            "jsonl",
            [
                "images/a.png",
                "processors/alpaca.jsonl",
                "processors/chat_format.jsonl",
                "run.jsonl",
            ],
        ),
        (
            "parquet",
            [
                "batch_00000.parquet",
                "images/a.png",
                "processors/alpaca/batch_00000.parquet",
                "processors/chat_format/batch_00000.parquet",
            ],
        ),
    ],
)
def test_export_includes_every_schema_transform_beside_images(
    tmp_path: Path, monkeypatch, export_format: str, expected: list[str]
):
    dataset_path = _schema_transform_artifact(tmp_path, monkeypatch)
    _write_parquet_rows(dataset_path / "processors-files" / "alpaca", [{"instruction": "Q1"}])
    (dataset_path / "images").mkdir()
    (dataset_path / "images" / "a.png").write_bytes(b"png")

    file_path, _, _ = build_dataset_download(
        artifact_path = str(dataset_path),
        export_format = export_format,
        filename_stem = "run",
    )
    try:
        with zipfile.ZipFile(file_path) as archive:
            assert sorted(archive.namelist()) == expected
            if export_format == "jsonl":
                alpaca = archive.read("processors/alpaca.jsonl").decode("utf-8")
                assert json.loads(alpaca.strip()) == {"instruction": "Q1"}
    finally:
        file_path.unlink(missing_ok = True)


def test_jsonl_export_stays_plain_when_no_transform_wrote_shards(tmp_path: Path, monkeypatch):
    dataset_path = tmp_path / "recipe-datasets" / "job-empty-transform"
    _write_parquet_rows(dataset_path / "parquet-files", [{"question": "Q1"}])
    (dataset_path / "processors-files" / "empty").mkdir(parents = True)
    (dataset_path / "processors-files" / "preview.parquet").write_bytes(b"not a folder")
    monkeypatch.setattr(
        "core.data_recipe.export._resolve_recipe_artifact_path",
        lambda artifact_path: dataset_path,
    )

    from core.data_recipe.export import download_filename

    assert (
        download_filename(artifact_path = str(dataset_path), export_format = "jsonl", stem = "run")
        == "run.jsonl"
    )
    file_path, media_type, download_name = build_dataset_download(
        artifact_path = str(dataset_path),
        export_format = "jsonl",
        filename_stem = "run",
    )
    file_path.unlink(missing_ok = True)
    assert (media_type, download_name) == ("application/x-ndjson", "run.jsonl")


def test_jsonl_reader_preserves_columns_named_like_old_reader_helpers(tmp_path: Path):
    from core.data_recipe.export import _write_jsonl_from_parquet

    parquet_dir = tmp_path / "parquet-files"
    _write_parquet_rows(parquet_dir, [{"filename": "a.png", "text": "x"}])

    destination = tmp_path / "out.jsonl"
    _write_jsonl_from_parquet(parquet_dir, destination)
    assert json.loads(destination.read_text().strip()) == {"filename": "a.png", "text": "x"}


def test_minting_refuses_a_run_whose_shards_are_gone(tmp_path: Path, monkeypatch):
    """A historical run's artifact path comes from the client, and nothing confirmed it still held
    anything: the link minted fine and the browser then failed invisibly against it."""
    dataset_path = tmp_path / "recipe-datasets" / "job-swept"
    (dataset_path / "parquet-files").mkdir(parents = True)
    monkeypatch.setattr(
        "core.data_recipe.export._resolve_recipe_artifact_path",
        lambda artifact_path: dataset_path,
    )

    from core.data_recipe.export import download_filename

    with pytest.raises(RecipeDatasetExportError, match = "parquet"):
        download_filename(artifact_path = str(dataset_path), export_format = "jsonl", stem = "swept")


def test_minting_is_refused_for_a_keyless_caller(monkeypatch, tmp_path: Path):
    """Keyless callers cannot mint one: the capability outlives the setting that admitted them."""
    pytest.importorskip("fastapi")
    from fastapi.testclient import TestClient

    jobs_route = pytest.importorskip("routes.data_recipe.jobs")
    app, token = _download_app(monkeypatch, tmp_path, jobs_route)

    app.dependency_overrides[jobs_route.request_admitted_without_credential] = lambda: True
    refused = TestClient(app).get(
        "/api/data-recipe/jobs/job-1/download-url",
        headers = {"Authorization": f"Bearer {token}"},
    )
    assert refused.status_code == 403
    app.dependency_overrides.clear()


def test_download_link_outlasts_the_native_save_dialog():
    """The save chooser opens before the request, so _DOWNLOAD_LINK_TTL must outlast it."""
    jobs_route = pytest.importorskip("routes.data_recipe.jobs")

    assert jobs_route._DOWNLOAD_LINK_TTL >= 15 * 60


def test_jsonl_reader_streams_a_merged_shard_by_row_group(tmp_path: Path):
    """merge_batches collapses a whole run into one file, so a shard is not a safe unit to read."""
    pytest.importorskip("pandas")
    pyarrow_parquet = pytest.importorskip("pyarrow.parquet")
    import pandas as pd

    from core.data_recipe.export import _JSONL_EXPORT_BATCH_ROWS, _write_jsonl_from_parquet

    parquet_dir = tmp_path / "parquet-files"
    parquet_dir.mkdir(parents = True)
    rows = _JSONL_EXPORT_BATCH_ROWS * 2 + 5
    pd.DataFrame({"i": range(rows)}).to_parquet(
        parquet_dir / "batch_00000.parquet",
        index = False,
        row_group_size = 1_000,
    )
    assert pyarrow_parquet.ParquetFile(parquet_dir / "batch_00000.parquet").num_row_groups > 1

    destination = tmp_path / "out.jsonl"
    _write_jsonl_from_parquet(parquet_dir, destination)
    exported = [json.loads(line)["i"] for line in destination.read_text().splitlines()]
    assert exported == list(range(rows))


def test_jsonl_reader_preserves_arrow_value_types(tmp_path: Path):
    pyarrow = pytest.importorskip("pyarrow")
    import pyarrow.parquet as pyarrow_parquet
    from datetime import date, datetime
    from decimal import Decimal

    from core.data_recipe.export import _write_jsonl_from_parquet

    parquet_dir = tmp_path / "parquet-files"
    parquet_dir.mkdir(parents = True)
    pyarrow_parquet.write_table(
        pyarrow.table(
            {
                "i64": pyarrow.array([1, None], pyarrow.int64()),
                "day": pyarrow.array([date(2020, 1, 1), None], pyarrow.date32()),
                "at": pyarrow.array([datetime(2020, 1, 1, 12, 30), None], pyarrow.timestamp("us")),
                "price": pyarrow.array([Decimal("1.20"), None], pyarrow.decimal128(10, 2)),
                "tags": pyarrow.array([[1, 2], None], pyarrow.list_(pyarrow.int64())),
            }
        ),
        parquet_dir / "batch_00000.parquet",
    )

    destination = tmp_path / "out.jsonl"
    _write_jsonl_from_parquet(
        parquet_dir = parquet_dir,
        destination = destination,
    )

    first = json.loads(destination.read_text().splitlines()[0])
    assert first["i64"] == 1
    assert first["day"] == "2020-01-01"
    assert first["price"] == 1.2


def test_jsonl_reader_preserves_hugging_face_image_struct_bytes(tmp_path: Path):
    """Image(decode=False) rows keep their reversible Arrow bytes/path representation."""
    pyarrow = pytest.importorskip("pyarrow")
    import base64
    import io
    import pyarrow.parquet as pyarrow_parquet
    from PIL import Image

    from core.data_recipe.export import _write_jsonl_from_parquet

    buffer = io.BytesIO()
    Image.new("RGBA", (2, 2), (10, 20, 30, 40)).save(buffer, format = "PNG")
    original = buffer.getvalue()
    image_type = pyarrow.struct([("bytes", pyarrow.binary()), ("path", pyarrow.string())])
    parquet_dir = tmp_path / "parquet-files"
    parquet_dir.mkdir(parents = True)
    pyarrow_parquet.write_table(
        pyarrow.table(
            {
                "image": pyarrow.array(
                    [{"bytes": original, "path": "images/source.png"}],
                    type = image_type,
                ),
                "label": pyarrow.array(["keep-me"]),
            }
        ),
        parquet_dir / "batch_00000.parquet",
    )

    destination = tmp_path / "out.jsonl"
    _write_jsonl_from_parquet(
        parquet_dir = parquet_dir,
        destination = destination,
    )

    row = json.loads(destination.read_text().strip())
    assert row["label"] == "keep-me"
    assert row["image"]["path"] == "images/source.png"
    assert base64.b64decode(row["image"]["bytes"]) == original


def test_a_row_is_not_mistaken_for_an_image(tmp_path: Path):
    """to_preview_jsonable's image detection matches any mapping with bytes or path, and a row is
    one, so passing whole rows replaced every column (labels included) with a JPEG preview."""
    pyarrow = pytest.importorskip("pyarrow")
    import pyarrow.parquet as pyarrow_parquet
    from PIL import Image

    from core.data_recipe.export import _write_jsonl_from_parquet

    picture = tmp_path / "pic.png"
    Image.new("RGB", (8, 8), (255, 0, 0)).save(picture)

    for columns in (
        {"path": pyarrow.array([str(picture)]), "label": pyarrow.array(["keep-me"])},
        {"bytes": pyarrow.array([picture.read_bytes()]), "label": pyarrow.array(["keep-me"])},
    ):
        parquet_dir = tmp_path / f"shard-{'path' if 'path' in columns else 'bytes'}"
        parquet_dir.mkdir()
        pyarrow_parquet.write_table(pyarrow.table(columns), parquet_dir / "batch_00000.parquet")

        destination = tmp_path / "out.jsonl"
        _write_jsonl_from_parquet(
            parquet_dir = parquet_dir,
            destination = destination,
        )
        row = json.loads(destination.read_text().splitlines()[0])
        assert row["label"] == "keep-me"
        assert sorted(row) == sorted(columns)


def test_to_preview_jsonable_row_converts_each_column(tmp_path: Path):
    from PIL import Image

    from core.data_recipe.jsonable import to_preview_jsonable_row

    picture = tmp_path / "pic.png"
    Image.new("RGB", (4, 4), (0, 255, 0)).save(picture)

    row = {"path": str(picture), "label": "keep-me"}
    assert to_preview_jsonable_row(row) == row
    assert to_preview_jsonable_row([row, row]) == [row, row]
    cell = to_preview_jsonable_row({"image": {"path": str(picture)}})["image"]
    assert cell["type"] == "image" and cell["mime"] == "image/jpeg"


def test_a_column_named_file_row_number_also_survives(tmp_path: Path):
    from core.data_recipe.export import _write_jsonl_from_parquet

    parquet_dir = tmp_path / "parquet-files"
    _write_parquet_rows(parquet_dir, [{"file_row_number": 7, "filename": "a.png", "label": "x"}])
    destination = tmp_path / "out.jsonl"
    _write_jsonl_from_parquet(parquet_dir, destination)
    assert json.loads(destination.read_text().strip()) == {
        "file_row_number": 7,
        "filename": "a.png",
        "label": "x",
    }


def _general_path(row):
    from core.data_recipe import export
    return export._json_dumps_value(export._sanitize_json_value(row))


def _encode_or_error(fn, row):
    try:
        return fn(row)
    except Exception as exc:
        return f"{type(exc).__name__}: {exc}"


def _random_value(rng, depth = 0):
    import datetime
    import enum
    from decimal import Decimal

    numpy = pytest.importorskip("numpy")
    pandas = pytest.importorskip("pandas")

    class Text(str):
        pass

    class Level(enum.IntEnum):
        LOW = 1

    leaves = [
        lambda: rng.choice(
            ["", "plain", "café \U0001f600", 'q"uo\\te\n\t\r\x00\x1f', "

", "\ud800"]
        ),
        lambda: rng.choice([0, -1, 2**63, -(2**70), True, False, None]),
        lambda: rng.choice(
            [0.0, -0.0, 1.5, 1e300, 5e-324, 0.1 + 0.2, float("nan"), float("inf"), -float("inf")]
        ),
        lambda: Decimal(rng.choice(["1.20", "0E-8", "-0", "1E+3", "NaN", "Infinity", "-12.3400"])),
        lambda: rng.choice([b"", b"\x00\xff", bytearray(b"ab")]),
        lambda: rng.choice(
            [
                datetime.datetime(2026, 1, 2, 3, 4, 5, 6),
                datetime.date(2026, 1, 2),
                datetime.time(1, 2),
            ]
        ),
        lambda: rng.choice(
            [
                numpy.float32(1.1),
                numpy.float64("nan"),
                numpy.int64(7),
                numpy.bool_(True),
                numpy.str_("np"),
            ]
        ),
        lambda: rng.choice([pandas.NA, pandas.NaT, pandas.Timestamp("2026-01-02 03:04:05")]),
        lambda: rng.choice([Text("sub"), Level.LOW, numpy.arange(3), (1, "t"), {"one"}]),
    ]
    if depth < 3 and rng.random() < 0.3:
        if rng.random() < 0.5:
            return [_random_value(rng, depth + 1) for _ in range(rng.randint(0, 3))]
        keys = ["k", "é", 1, True, None, "1", 1.5]
        return {rng.choice(keys): _random_value(rng, depth + 1) for _ in range(rng.randint(0, 3))}
    return rng.choice(leaves)()


@pytest.mark.parametrize("seed", range(4))
def test_json_dumps_row_writes_what_the_general_path_writes(seed):
    import random
    rng = random.Random(seed)
    for _ in range(1500):
        plain_only = rng.random() < 0.4
        row = {}
        for index in range(rng.randint(0, 8)):
            value = _random_value(rng)
            if plain_only and not _is_plain_for_test(value):
                value = rng.choice(["text", 3, 2.5, None, [1, "a"], {"n": {"m": [True]}}])
            key = (
                rng.choice([1, "1", True, None])
                if rng.random() < 0.03
                else rng.choice([f"c{index}", "café", 'k"\n'])
            )
            row[key] = value
        assert _encode_or_error(_json_dumps_row, row) == _encode_or_error(_general_path, row), row


def _is_plain_for_test(value):
    from core.data_recipe import export
    try:
        return export._is_plain_json(value)
    except export._TooDeep:
        return False


@pytest.mark.parametrize("depth", [31, 32, 33, 400, 2000])
def test_json_dumps_row_matches_the_general_path_at_any_depth(depth):
    plain = [] if depth % 2 else {}
    node = plain
    for _ in range(depth):
        child = []
        node.append(child) if isinstance(node, list) else node.update(k = child)
        node = child
    for row in ({"deep": plain}, {"deep": plain, "when": float("nan")}):
        assert _encode_or_error(_json_dumps_row, row) == _encode_or_error(_general_path, row)


def test_a_plain_row_is_written_without_the_per_value_walk(monkeypatch):
    from core.data_recipe import export

    calls = []
    monkeypatch.setattr(export, "to_jsonable", lambda value: calls.append(value) or value)
    row = {
        "question": "Qé",
        "n": 3,
        "score": 0.5,
        "ok": True,
        "tags": ["a", None],
        "meta": {"x": 1},
    }

    assert _json_dumps_row(row) == json.dumps(row, ensure_ascii = False)
    assert calls == []