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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: keep cancelled fine-tuning jobs in paginated results (#16633)
Max-Reisinger8e0a10298936
diff --git a/studio/backend/routes/openai_fine_tuning.py b/studio/backend/routes/openai_fine_tuning.pyindex 51a491276b2..8053fe2cfbd 100644--- a/studio/backend/routes/openai_fine_tuning.py+++ b/studio/backend/routes/openai_fine_tuning.py@@ -12,8 +12,11 @@ import osimport reimport secretsimport weakref+from collections import deque+from collections.abc import Iteratorfrom dataclasses import dataclassfrom datetime import datetime, timezone+from itertools import chain, groupbyfrom pathlib import Pathfrom typing import Any, Literal, Optional@@ -1111,19 +1114,61 @@ def _paged(rows: list[dict[str, Any]], after: Optional[str], limit: int) -> dictreturn {"object": "list", "data": rows[:limit], "has_more": len(rows) > limit}-def _runs_after(after: Optional[str], count: int) -> list[dict[str, Any]]:- runs: list[dict[str, Any]] = []- found, offset = after is None, 0- while len(runs) < count:+def _iter_runs() -> Iterator[dict[str, Any]]:+ offset = 0+ while True:batch = list_runs(200, offset)["runs"]if not batch:- break- for run in batch:- if found:- runs.append(run)- found = found or run["id"] == after+ return+ yield from batchoffset += len(batch)- return runs[:count]+++def _run_created(run: dict[str, Any]) -> int:+ return _ALIAS_CREATED.get(_RUN_ALIAS.get(run["id"])) or _unix(run.get("started_at")) or 0+++def _ordered_jobs(+ pending: list[dict[str, Any]], live: dict[str, dict[str, Any]]+) -> Iterator[tuple[dict[str, Any], bool]]:+ # By creation time, queue entries first on ties: a started job keeps its place across pages.+ remaining = deque(sorted(pending, key = lambda job: job["created_at"], reverse = True))+ # Batch members share started_at: order them by creation time, as the live batch lists them.+ runs = groupby(_iter_runs(), key = lambda run: run.get("started_at"))+ runs = chain.from_iterable(sorted(g, key = _run_created, reverse = True) for _, g in runs)+ # A live run can acquire its history row between the status and history reads.+ history = ((run, True) for run in runs if run["id"] not in live)+ for row, is_run in chain(((job, False) for job in live.values()), history):+ created_at = _run_created(row) if is_run else row["created_at"]+ while remaining and remaining[0]["created_at"] >= created_at:+ yield remaining.popleft(), False+ yield row, is_run+ yield from ((job, False) for job in remaining)+++def _list_job_page(+ pending: list[dict[str, Any]],+ live: dict[str, dict[str, Any]],+ after: Optional[str],+ after_run: Optional[str],+ limit: int,+ via_api_key: bool,+) -> dict[str, Any]:+ jobs, seen = [], set()+ for row, is_run in _ordered_jobs(pending, live):+ # A job that starts mid-request: listed once, its queue id still matches the cursor.+ public_id = (_RUN_ALIAS.get(row["id"]) or _job_id(row["id"])) if is_run else row["id"]+ if public_id in seen:+ continue+ seen.add(public_id)+ if after:+ if public_id == after or (is_run and row["id"] == after_run):+ after = None+ continue+ if len(jobs) == limit:+ return {"object": "list", "data": jobs, "has_more": True}+ jobs.append(_for_caller(_job_from_run(row), via_api_key) if is_run else row)+ return {"object": "list", "data": jobs, "has_more": False}@router.get("/fine_tuning/jobs")@@ -1134,41 +1179,27 @@ async def list_fine_tuning_jobs(via_api_key: bool = Depends(authenticated_via_api_key),):await asyncio.to_thread(_load_aliases)- own = [e for e in _ALIASES.values() if _own_alias(e.alias)]- # Newest first, as the history lists runs; insertion order breaks same-second ties.- pending = [(e, _for_caller(_queued_job(e), via_api_key)) for e in reversed(own)]- pending_ids = [job["id"] for _, job in pending]- if after in pending_ids:- pending, after = pending[pending_ids.index(after) + 1 :], None- elif after:- pending = []after_run = await _resolve(after) if after else None- runs = await asyncio.to_thread(_runs_after, after_run, limit + 1)status = await _current_status(current_subject, via_api_key)live_id = _status_field(status, "job_id") if status is not None else None-- live = []+ live = {}if live_id and _status_field(status, "phase") != "idle":- live = [- r- for r in reversed(_BATCHES.get(live_id, [live_id]))- if await asyncio.to_thread(get_run, r) is None- ]- if after_run in live:- live = live[live.index(after_run) + 1 :]- runs = await asyncio.to_thread(_runs_after, None, limit + 1)- elif after_run:- live = []- jobs = [_for_caller(await asyncio.to_thread(_job_from_run, run), via_api_key) for run in runs]- jobs = [await _job(r, current_subject, via_api_key) for r in live] + jobs-- newest = max((job["created_at"] for job in jobs), default = 0)- jobs = [- job- for e, job in pending- if e.status in ("queued", "starting") or job["created_at"] > newest- ] + jobs- return {"object": "list", "data": jobs[:limit], "has_more": len(jobs) > limit}+ for run_id in reversed(_BATCHES.get(live_id, [live_id])):+ if await asyncio.to_thread(get_run, run_id) is None:+ job = await _job(run_id, current_subject, via_api_key)+ live[run_id] = job+ if run_id == after_run:+ after = job["id"]++ # After the awaits, so a job that started meanwhile is listed as its run.+ pending = [+ _for_caller(_queued_job(entry), via_api_key)+ for entry in reversed(_ALIASES.values())+ if _own_alias(entry.alias) is not None+ ]+ return await asyncio.to_thread(+ _list_job_page, pending, live, after, after_run, limit, via_api_key+ )@router.get("/fine_tuning/jobs/{job_id}")diff --git a/studio/backend/tests/test_openai_fine_tuning.py b/studio/backend/tests/test_openai_fine_tuning.pyindex b9ba1d3b20a..723c613c788 100644--- a/studio/backend/tests/test_openai_fine_tuning.py+++ b/studio/backend/tests/test_openai_fine_tuning.py@@ -1758,3 +1758,132 @@ def test_a_job_cancelled_during_the_batch_model_probe_never_starts(assert "ab"[cancelled] not in startedassert statuses[cancelled] == "cancelled"assert calls["stop"] == []++[email protected]("persisted", [False, True])+def test_a_cancelled_queued_job_is_still_listed_after_a_newer_job_starts(+ queue, monkeypatch, tmp_path, persisted+):+ client, _calls, _live, gpu = queue++ async def flow():+ uploaded = await client.files.create(file = ("chats.jsonl", CHATS), purpose = "fine-tune")+ monkeypatch.setattr(openai_fine_tuning, "_now", lambda: 1_700_000_000)+ old = await _create(client, uploaded.id)+ await client.fine_tuning.jobs.cancel(old.id)+ before = await client.fine_tuning.jobs.list()+ gpu["busy"] = False+ newer = await _create(client, uploaded.id)+ if persisted:+ _finished_run(tmp_path, tmp_path / "chats.jsonl")+ after = [job.id async for job in client.fine_tuning.jobs.list(limit = 1)]+ retrieved = await client.fine_tuning.jobs.retrieve(old.id)+ return old, newer, before, after, retrieved++ old, newer, before, after, retrieved = _run(flow())+ assert [(job.id, job.status) for job in before.data] == [(old.id, "cancelled")]+ assert retrieved.status == "cancelled"+ assert after == [newer.id, old.id]+++def test_a_job_that_starts_during_a_list_request_is_listed_once(queue, monkeypatch):+ client, _calls, live, gpu = queue+ status_read = training_routes.get_training_status++ async def start_mid_request(current_subject, via_api_key):+ if openai_fine_tuning._QUEUE:+ gpu["busy"] = False+ await openai_fine_tuning._drain_once()+ return await status_read(current_subject = current_subject, via_api_key = via_api_key)++ async def flow():+ uploaded = await client.files.create(file = ("chats.jsonl", CHATS), purpose = "fine-tune")+ job = await _create(client, uploaded.id)+ monkeypatch.setattr(training_routes, "get_training_status", start_mid_request)+ page = await client.fine_tuning.jobs.list(limit = 1)+ return job, page++ job, page = _run(flow())+ assert [(j.id, j.status) for j in page.data] == [(job.id, "validating_files")]+ assert page.has_more is False+++def test_a_cursor_on_a_job_that_starts_during_the_request_still_pages(queue, monkeypatch):+ client, _calls, _live, gpu = queue+ status_read = training_routes.get_training_status++ def history_row(run_id, started_at):+ studio_db.create_run(+ id = run_id,+ model_name = "unsloth/Qwen3-0.6B",+ dataset_name = "chats.jsonl",+ config_json = json.dumps({"model_name": "unsloth/Qwen3-0.6B"}),+ started_at = started_at,+ total_steps = 4,+ )++ async def start_mid_request(current_subject, via_api_key):+ if openai_fine_tuning._QUEUE:+ gpu["busy"] = False+ await openai_fine_tuning._drain_once()+ history_row("job_20261021_101500_ab12cd34", "2026-11-04T00:00:00+00:00")+ return await status_read(current_subject = current_subject, via_api_key = via_api_key)++ async def flow():+ uploaded = await client.files.create(file = ("chats.jsonl", CHATS), purpose = "fine-tune")+ history_row("job_20261001_000000_old", "2026-10-01T00:00:00+00:00")+ job = await _create(client, uploaded.id)+ first = await client.fine_tuning.jobs.list(limit = 1)+ monkeypatch.setattr(training_routes, "get_training_status", start_mid_request)+ second = await client.fine_tuning.jobs.list(after = job.id, limit = 1)+ return job, first, second++ job, first, second = _run(flow())+ assert [j.id for j in first.data] == [job.id]+ assert [j.id for j in second.data] == ["ftjob_20261001_000000_old"]+++def test_a_newer_cancelled_job_is_not_skipped_when_an_older_one_starts_between_pages(+ queue, monkeypatch+):+ client, _calls, _live, gpu = queue+ clock = {"t": 1_700_000_000}+ monkeypatch.setattr(openai_fine_tuning, "_now", lambda: clock["t"])++ async def flow():+ uploaded = await client.files.create(file = ("chats.jsonl", CHATS), purpose = "fine-tune")+ older = await _create(client, uploaded.id)+ clock["t"] += 10+ newer = await _create(client, uploaded.id)+ await client.fine_tuning.jobs.cancel(newer.id)+ first = await client.fine_tuning.jobs.list(limit = 1)+ gpu["busy"] = False+ await openai_fine_tuning._drain_once()+ rest = [j.id async for j in client.fine_tuning.jobs.list(after = first.data[0].id, limit = 1)]+ return older, newer, [j.id for j in first.data] + rest++ older, newer, walked = _run(flow())+ assert sorted(walked) == sorted([older.id, newer.id])+++def test_a_batch_lists_in_the_same_order_before_and_after_its_history_rows_exist(monkeypatch):+ started = "2026-11-04T00:00:00+00:00"+ monkeypatch.setattr(+ openai_fine_tuning, "_RUN_ALIAS", {"run_a": "ftjob_qa", "run_c": "ftjob_qc"}+ )+ monkeypatch.setattr(openai_fine_tuning, "_ALIAS_CREATED", {"ftjob_qa": 100, "ftjob_qc": 300})+ waiting = [{"id": "ftjob_qb", "created_at": 200}]+ live = {+ "run_c": {"id": "ftjob_qc", "created_at": 300},+ "run_a": {"id": "ftjob_qa", "created_at": 100},+ }++ def order(rows, live_rows):+ monkeypatch.setattr(openai_fine_tuning, "_iter_runs", lambda: iter(rows))+ return [+ openai_fine_tuning._RUN_ALIAS.get(row["id"], row["id"]) if is_run else row["id"]+ for row, is_run in openai_fine_tuning._ordered_jobs(waiting, live_rows)+ ]++ persisted = [{"id": "run_a", "started_at": started}, {"id": "run_c", "started_at": started}]+ assert order([], live) == order(persisted, {}) == ["ftjob_qc", "ftjob_qb", "ftjob_qa"]