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.

Studio: persist Data Recipes and run history server-side (#7108)

Etherl4c6d5866ada2
diff --git a/studio/backend/routes/data_recipe/__init__.py b/studio/backend/routes/data_recipe/__init__.py
index b7b346e0133..410472d607a 100644
--- a/studio/backend/routes/data_recipe/__init__.py
+++ b/studio/backend/routes/data_recipe/__init__.py
@@ -18,6 +18,7 @@ if str(backend_path) not in sys.path:
from .jobs import download_router as jobs_download_router
from .jobs import router as jobs_router
+from .library import router as library_router
from .mcp import router as mcp_router
from .seed import router as seed_router
from .validate import router as validate_router
@@ -27,6 +28,7 @@ _header_authenticated.include_router(seed_router)
_header_authenticated.include_router(validate_router)
_header_authenticated.include_router(jobs_router)
_header_authenticated.include_router(mcp_router)
+_header_authenticated.include_router(library_router)
router = APIRouter()
# Kept out of the group above: the download link is fetched without a header, so it brings its
diff --git a/studio/backend/routes/data_recipe/library.py b/studio/backend/routes/data_recipe/library.py
new file mode 100644
index 00000000000..895576dafb5
--- /dev/null
+++ b/studio/backend/routes/data_recipe/library.py
@@ -0,0 +1,105 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Saved Data Recipes and their run history, stored per account in studio.db."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel, ConfigDict, Field
+
+from storage import data_recipes_db as db
+
+router = APIRouter(prefix = "/recipes")
+
+_ID = Field(min_length = 1, max_length = 128)
+# JS millisecond timestamps; also keeps values inside SQLite INTEGER.
+_TIME = Field(ge = 0, le = 2**53)
+_TIME_OPTIONAL = Field(default = None, ge = 0, le = 2**53)
+
+
+class RecipeRecord(BaseModel):
+ id: str = _ID
+ name: str = Field(max_length = 10_000)
+ payload: dict[str, Any]
+ createdAt: int = _TIME
+ updatedAt: int = _TIME
+ learningRecipeId: str | None = Field(default = None, max_length = 128)
+ learningRecipeTitle: str | None = Field(default = None, max_length = 10_000)
+
+
+class SaveRecipeRequest(RecipeRecord):
+ # The updatedAt the client last read; omitted for a brand-new recipe.
+ baseUpdatedAt: int | None = _TIME_OPTIONAL
+
+
+class ExecutionRecord(BaseModel):
+ # The run record is UI state with many optional fields; only the keys used for storage are typed.
+ model_config = ConfigDict(extra = "allow")
+ id: str = _ID
+ recipeId: str = _ID
+ createdAt: int = _TIME
+
+
+class LegacyImportRequest(BaseModel):
+ recipes: list[RecipeRecord] = Field(default_factory = list, max_length = 10_000)
+ executions: list[ExecutionRecord] = Field(default_factory = list, max_length = 50_000)
+
+
+def get_recipes():
+ return {"recipes": db.list_recipes()}
+
+
+def import_legacy_recipes(req: LegacyImportRequest):
+ return db.import_legacy(
+ [r.model_dump(exclude_none = True) for r in req.recipes],
+ [e.model_dump() for e in req.executions],
+ )
+
+
[email protected]("/{recipe_id}")
+def get_recipe(recipe_id: str):
+ record = db.get_recipe(recipe_id)
+ if record is None:
+ raise HTTPException(status_code = 404, detail = "Recipe not found")
+ return record
+
+
[email protected]("/{recipe_id}")
+def put_recipe(recipe_id: str, recipe: SaveRecipeRequest):
+ if recipe.id != recipe_id:
+ raise HTTPException(status_code = 400, detail = "ID mismatch")
+ try:
+ return db.upsert_recipe(
+ recipe.model_dump(exclude_none = True, exclude = {"baseUpdatedAt"}),
+ recipe.baseUpdatedAt,
+ )
+ except db.RecipeDeleted:
+ raise HTTPException(status_code = 410, detail = "Recipe was deleted")
+ except db.RecipeConflict:
+ raise HTTPException(
+ status_code = 409,
+ detail = "This recipe was changed in another window. Reload it to keep editing.",
+ )
+
+
[email protected]("/{recipe_id}", status_code = 204)
+def remove_recipe(recipe_id: str):
+ db.delete_recipe(recipe_id)
+
+
[email protected]("/{recipe_id}/executions")
+def get_executions(recipe_id: str):
+ return {"executions": db.list_executions(recipe_id)}
+
+
[email protected]("/{recipe_id}/executions/{execution_id}", status_code = 204)
+def put_execution(recipe_id: str, execution_id: str, execution: ExecutionRecord):
+ if execution.id != execution_id or execution.recipeId != recipe_id:
+ raise HTTPException(status_code = 400, detail = "ID mismatch")
+ if not db.upsert_execution(execution.model_dump()):
+ raise HTTPException(status_code = 404, detail = "Recipe not found")
diff --git a/studio/backend/storage/data_recipes_db.py b/studio/backend/storage/data_recipes_db.py
new file mode 100644
index 00000000000..fd4991eb848
--- /dev/null
+++ b/studio/backend/storage/data_recipes_db.py
@@ -0,0 +1,212 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Data Recipe definitions and run history in the account's studio.db."""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+import time
+from typing import Iterable
+
+from storage.studio_db import get_connection
+
+
+def _recipe_from_row(row: sqlite3.Row) -> dict:
+ record = {
+ "id": row["id"],
+ "name": row["name"],
+ "payload": json.loads(row["payload_json"]),
+ "createdAt": row["created_at"],
+ "updatedAt": row["updated_at"],
+ }
+ if row["learning_recipe_id"] is not None:
+ record["learningRecipeId"] = row["learning_recipe_id"]
+ if row["learning_recipe_title"] is not None:
+ record["learningRecipeTitle"] = row["learning_recipe_title"]
+ return record
+
+
+def _recipe_params(recipe: dict) -> tuple:
+ return (
+ recipe["id"],
+ recipe["name"],
+ json.dumps(recipe["payload"]),
+ recipe.get("learningRecipeId"),
+ recipe.get("learningRecipeTitle"),
+ int(recipe["createdAt"]),
+ int(recipe["updatedAt"]),
+ )
+
+
+def _execution_params(execution: dict) -> tuple:
+ return (
+ execution["id"],
+ execution["recipeId"],
+ int(execution["createdAt"]),
+ json.dumps(execution),
+ )
+
+
+def list_recipes() -> list[dict]:
+ conn = get_connection()
+ try:
+ rows = conn.execute("SELECT * FROM data_recipes ORDER BY updated_at DESC").fetchall()
+ return [_recipe_from_row(r) for r in rows]
+ finally:
+ conn.close()
+
+
+def get_recipe(recipe_id: str) -> dict | None:
+ conn = get_connection()
+ try:
+ row = conn.execute("SELECT * FROM data_recipes WHERE id = ?", (recipe_id,)).fetchone()
+ return _recipe_from_row(row) if row else None
+ finally:
+ conn.close()
+
+
+class RecipeDeleted(Exception):
+ pass
+
+
+class RecipeConflict(Exception):
+ pass
+
+
+def upsert_recipe(recipe: dict, base_updated_at: int | None = None) -> dict:
+ """``base_updated_at`` is the version the caller edited; a newer stored row is a conflict."""
+ conn = get_connection()
+ try:
+ cur = conn.execute(
+ """
+ INSERT INTO data_recipes
+ (id, name, payload_json, learning_recipe_id, learning_recipe_title,
+ created_at, updated_at)
+ SELECT ?, ?, ?, ?, ?, ?, ?
+ WHERE NOT EXISTS (SELECT 1 FROM data_recipe_tombstones WHERE id = ?1)
+ ON CONFLICT(id) DO UPDATE SET
+ name = excluded.name,
+ payload_json = excluded.payload_json,
+ learning_recipe_id = excluded.learning_recipe_id,
+ learning_recipe_title = excluded.learning_recipe_title,
+ updated_at = excluded.updated_at
+ WHERE ?8 IS NULL OR data_recipes.updated_at = ?8
+ """,
+ (*_recipe_params(recipe), base_updated_at),
+ )
+ row = conn.execute("SELECT * FROM data_recipes WHERE id = ?", (recipe["id"],)).fetchone()
+ conn.commit()
+ if cur.rowcount:
+ return _recipe_from_row(row)
+ if row is None:
+ raise RecipeDeleted(recipe["id"])
+ raise RecipeConflict(recipe["id"])
+ finally:
+ conn.close()
+
+
+def delete_recipe(recipe_id: str) -> None:
+ conn = get_connection()
+ try:
+ conn.execute("DELETE FROM data_recipes WHERE id = ?", (recipe_id,))
+ conn.execute(
+ "INSERT OR IGNORE INTO data_recipe_tombstones (id, deleted_at) VALUES (?, ?)",
+ (recipe_id, int(time.time() * 1000)),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+
+def list_executions(recipe_id: str) -> list[dict]:
+ conn = get_connection()
+ try:
+ rows = conn.execute(
+ "SELECT record_json FROM data_recipe_executions"
+ " WHERE recipe_id = ? ORDER BY created_at DESC",
+ (recipe_id,),
+ ).fetchall()
+ return [json.loads(r["record_json"]) for r in rows]
+ finally:
+ conn.close()
+
+
+_TERMINAL = ("completed", "cancelled", "error")
+
+
+def upsert_execution(execution: dict) -> bool:
+ """Returns False when the run's recipe does not exist or the id belongs to another recipe.
+
+ A snapshot older than the stored one (two tabs tracking one run) is accepted but dropped:
+ a lower lastEventId, a snapshot without analysis at the same lastEventId as one with it, or a
+ non-terminal status over a terminal one, never replaces it.
+ """
+ conn = get_connection()
+ try:
+ cur = conn.execute(
+ """
+ INSERT INTO data_recipe_executions (id, recipe_id, created_at, record_json)
+ SELECT ?, ?, ?, ?
+ WHERE EXISTS (SELECT 1 FROM data_recipes WHERE id = ?2)
+ ON CONFLICT(id) DO UPDATE SET record_json = excluded.record_json
+ WHERE data_recipe_executions.recipe_id = excluded.recipe_id
+ AND COALESCE(json_extract(excluded.record_json, '$.lastEventId'), -1)
+ >= COALESCE(json_extract(data_recipe_executions.record_json, '$.lastEventId'), -1)
+ AND NOT (
+ COALESCE(json_extract(excluded.record_json, '$.lastEventId'), -1)
+ = COALESCE(json_extract(data_recipe_executions.record_json, '$.lastEventId'), -1)
+ AND json_extract(data_recipe_executions.record_json, '$.analysis') IS NOT NULL
+ AND json_extract(excluded.record_json, '$.analysis') IS NULL
+ )
+ AND NOT (
+ json_extract(data_recipe_executions.record_json, '$.status') IN (?5, ?6, ?7)
+ AND COALESCE(json_extract(excluded.record_json, '$.status'), '')
+ NOT IN (?5, ?6, ?7)
+ )
+ """,
+ (*_execution_params(execution), *_TERMINAL),
+ )
+ stored = conn.execute(
+ "SELECT recipe_id FROM data_recipe_executions WHERE id = ?", (execution["id"],)
+ ).fetchone()
+ conn.commit()
+ return cur.rowcount > 0 or (
+ stored is not None and stored["recipe_id"] == execution["recipeId"]
+ )
+ finally:
+ conn.close()
+
+
+def import_legacy(recipes: Iterable[dict], executions: Iterable[dict]) -> dict:
+ """Insert-only: never overwrites a server record or revives a deleted recipe."""
+ conn = get_connection()
+ try:
+ recipe_count = 0
+ for recipe in recipes:
+ recipe_count += conn.execute(
+ """
+ INSERT OR IGNORE INTO data_recipes
+ (id, name, payload_json, learning_recipe_id, learning_recipe_title,
+ created_at, updated_at)
+ SELECT ?, ?, ?, ?, ?, ?, ?
+ WHERE NOT EXISTS (SELECT 1 FROM data_recipe_tombstones WHERE id = ?1)
+ """,
+ _recipe_params(recipe),
+ ).rowcount
+ execution_count = 0
+ for execution in executions:
+ execution_count += conn.execute(
+ """
+ INSERT OR IGNORE INTO data_recipe_executions
+ (id, recipe_id, created_at, record_json)
+ SELECT ?, ?, ?, ?
+ WHERE EXISTS (SELECT 1 FROM data_recipes WHERE id = ?2)
+ """,
+ _execution_params(execution),
+ ).rowcount
+ conn.commit()
+ return {"recipes": recipe_count, "executions": execution_count}
+ finally:
+ conn.close()
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index 1e0df810c53..89a139a9ac3 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -785,6 +785,42 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_prompt_lists_created_at ON prompt_lists(created_at)"
)
+ conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS data_recipes (
+ id TEXT NOT NULL PRIMARY KEY,
+ name TEXT NOT NULL,
+ payload_json TEXT NOT NULL,
+ learning_recipe_id TEXT,
+ learning_recipe_title TEXT,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+ )
+ """
+ )
+ # Deleted ids stay here so a stale tab or a re-run legacy import cannot bring them back.
+ conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS data_recipe_tombstones (
+ id TEXT NOT NULL PRIMARY KEY,
+ deleted_at INTEGER NOT NULL
+ ) WITHOUT ROWID
+ """
+ )
+ conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS data_recipe_executions (
+ id TEXT NOT NULL PRIMARY KEY,
+ recipe_id TEXT NOT NULL REFERENCES data_recipes(id) ON DELETE CASCADE,
+ created_at INTEGER NOT NULL,
+ record_json TEXT NOT NULL
+ )
+ """
+ )
+ conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_data_recipe_executions_recipe"
+ " ON data_recipe_executions(recipe_id, created_at)"
+ )
conn.execute(
"""
CREATE TABLE IF NOT EXISTS research_runs (
diff --git a/studio/backend/tests/multi_account/factories_training.py b/studio/backend/tests/multi_account/factories_training.py
index 9dceb470b4f..ef42f3553c6 100644
--- a/studio/backend/tests/multi_account/factories_training.py
+++ b/studio/backend/tests/multi_account/factories_training.py
@@ -16,6 +16,21 @@ RECIPE_JOB_ID = "f9e8d7c6b5a40312092a8b7c6d5e4f30"
BLOCK_ID = "0123456789abcdef0123456789abcdef"
FILE_ID = "fedcba9876543210fedcba9876543210"
SCAN_FOLDER_DIRNAME = "training-matrix-scan-folder"
+SAVED_RECIPE_ID = "training-matrix-recipe"
+RECIPE_EXECUTION_ID = "training-matrix-execution"
+SAVED_RECIPE_BODY = {
+ "id": SAVED_RECIPE_ID,
+ "name": EDITED,
+ "payload": {"recipe": {}},
+ "createdAt": 1000,
+ "updatedAt": 2000,
+}
+RECIPE_EXECUTION_BODY = {
+ "id": RECIPE_EXECUTION_ID,
+ "recipeId": SAVED_RECIPE_ID,
+ "createdAt": 1000,
+ "status": EDITED,
+}
PNG_1X1 = (
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmM"
@@ -35,6 +50,17 @@ _BLOCK_REASON = (
"Removing an upload block is an idempotent delete under the caller's own uploads root, so a "
"foreign account is told ok with deleted false."
)
+_SAVED_RECIPE_UPSERT_REASON = (
+ "PUT is an upsert keyed only by id inside the caller's own studio.db, so a foreign caller "
+ "writes its own row and never sees alice's; the snapshot proves hers is untouched."
+)
+_SAVED_RECIPE_DELETE_REASON = (
+ "DELETE is idempotent in the caller's own studio.db, so a foreign caller gets 204 after "
+ "tombstoning an id it never had; the snapshot proves alice's recipe survived."
+)
+_RECIPE_EXECUTIONS_READ_REASON = (
+ "Run history is read from the caller's own studio.db, so a foreign caller gets an empty list."
+)
_EVENTS_REASON = (
"The owning account's SSE stream ends only when the client disconnects, which an in-process "
"TestClient request cannot do, so the case would hang rather than return."
@@ -139,6 +165,19 @@ def seed_scan_folder(account) -> dict[str, str]:
return {"folder_id": run_as(account, install)}
+@seeder("training-saved-recipe")
+def seed_saved_recipe(account) -> dict[str, str]:
+ from storage import data_recipes_db
+ from utils.account_context import run_as
+
+ def install() -> None:
+ data_recipes_db.upsert_recipe({**SAVED_RECIPE_BODY, "name": SENTINEL})
+ data_recipes_db.upsert_execution({**RECIPE_EXECUTION_BODY, "status": SENTINEL})
+
+ run_as(account, install)
+ return {"recipe_id": SAVED_RECIPE_ID, "execution_id": RECIPE_EXECUTION_ID}
+
+
@seeder("training-recipe-job")
def seed_recipe_job(account) -> dict[str, str]:
from core.data_recipe.jobs import get_job_manager
@@ -248,6 +287,37 @@ FACTORIES = {
wrong = (400,),
reason = _PUBLISH_REASON,
),
+ "routes.data_recipe.library:GET:/recipes/{recipe_id}": Factory(
+ "training-saved-recipe", fragment = SENTINEL
+ ),
+ "routes.data_recipe.library:PUT:/recipes/{recipe_id}": Factory(
+ "training-saved-recipe",
+ SAVED_RECIPE_BODY,
+ fragment = EDITED,
+ owner = (200,),
+ wrong = (200,),
+ reason = _SAVED_RECIPE_UPSERT_REASON,
+ ),
+ "routes.data_recipe.library:DELETE:/recipes/{recipe_id}": Factory(
+ "training-saved-recipe",
+ success = 204,
+ owner = (204,),
+ wrong = (204,),
+ reason = _SAVED_RECIPE_DELETE_REASON,
+ ),
+ "routes.data_recipe.library:GET:/recipes/{recipe_id}/executions": Factory(
+ "training-saved-recipe",
+ fragment = SENTINEL,
+ absent = SENTINEL,
+ owner = (200,),
+ wrong = (200,),
+ reason = _RECIPE_EXECUTIONS_READ_REASON,
+ ),
+ "routes.data_recipe.library:PUT:/recipes/{recipe_id}/executions/{execution_id}": Factory(
+ "training-saved-recipe",
+ RECIPE_EXECUTION_BODY,
+ success = 204,
+ ),
"routes.data_recipe.seed:DELETE:/seed/unstructured-block/{block_id}": Factory(
"training-unstructured-upload",
fragment = "true",
diff --git a/studio/backend/tests/test_data_recipe_library.py b/studio/backend/tests/test_data_recipe_library.py
new file mode 100644
index 00000000000..96fb41d4cb7
--- /dev/null
+++ b/studio/backend/tests/test_data_recipe_library.py
@@ -0,0 +1,164 @@
+# 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 fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from routes.data_recipe.library import router
+
+
+def _client() -> TestClient:
+ app = FastAPI()
+ app.include_router(router)
+ return TestClient(app)
+
+
+def _recipe(
+ recipe_id = "r1",
+ name = "Recipe",
+ updated_at = 2000,
+ **payload,
+) -> dict:
+ return {
+ "id": recipe_id,
+ "name": name,
+ "payload": {"recipe": {}, **payload},
+ "createdAt": 1000,
+ "updatedAt": updated_at,
+ }
+
+
+def _execution(
+ execution_id = "e1",
+ recipe_id = "r1",
+ **extra,
+) -> dict:
+ return {"id": execution_id, "recipeId": recipe_id, "createdAt": 1000, **extra}
+
+
+def test_recipe_round_trip_keeps_payload_and_learning_fields():
+ client = _client()
+ providers = [{"name": "p", "api_key": "sk-inline", "api_key_env": "OPENAI_API_KEY"}]
+ body = _recipe(model_providers = providers)
+ body["learningRecipeId"] = "text-to-sql"
+ assert client.put("/recipes/r1", json = body).status_code == 200
+
+ stored = client.get("/recipes/r1").json()
+ assert stored["payload"]["model_providers"] == providers
+ assert stored["learningRecipeId"] == "text-to-sql"
+ assert "learningRecipeTitle" not in stored
+ assert [r["id"] for r in client.get("/recipes").json()["recipes"]] == ["r1"]
+
+
+def test_recipes_list_newest_first_and_update_keeps_created_at():
+ client = _client()
+ client.put("/recipes/old", json = _recipe("old", updated_at = 1000))
+ client.put("/recipes/new", json = _recipe("new", updated_at = 3000))
+ edited = {**_recipe("old", name = "Edited", updated_at = 4000), "createdAt": 9999}
+ client.put("/recipes/old", json = edited)
+
+ recipes = client.get("/recipes").json()["recipes"]
+ assert [r["id"] for r in recipes] == ["old", "new"]
+ assert recipes[0]["name"] == "Edited"
+ assert recipes[0]["createdAt"] == 1000
+
+
+def test_deleted_recipe_cannot_be_revived_by_a_stale_save_or_legacy_import():
+ client = _client()
+ client.put("/recipes/r1", json = _recipe())
+ client.put("/recipes/r1/executions/e1", json = _execution())
+ assert client.delete("/recipes/r1").status_code == 204
+
+ assert client.get("/recipes/r1").status_code == 404
+ assert client.get("/recipes/r1/executions").json() == {"executions": []}
+ assert client.put("/recipes/r1", json = _recipe()).status_code == 410
+ imported = client.post(
+ "/recipes/import", json = {"recipes": [_recipe()], "executions": [_execution()]}
+ )
+ assert imported.json() == {"recipes": 0, "executions": 0}
+ assert client.get("/recipes").json() == {"recipes": []}
+
+
+def test_execution_needs_its_recipe_and_cannot_move_to_another():
+ client = _client()
+ assert client.put("/recipes/r1/executions/e1", json = _execution()).status_code == 404
+ client.put("/recipes/r1", json = _recipe())
+ client.put("/recipes/r2", json = _recipe("r2"))
+ assert (
+ client.put("/recipes/r1/executions/e1", json = _execution(status = "running")).status_code
+ == 204
+ )
+ assert (
+ client.put("/recipes/r1/executions/e1", json = _execution(status = "completed")).status_code
+ == 204
+ )
+ assert client.put("/recipes/r1/executions/e2", json = _execution()).status_code == 400
+
+ assert (
+ client.put("/recipes/r2/executions/e1", json = _execution(recipe_id = "r2")).status_code == 404
+ )
+ assert client.get("/recipes/r1/executions").json()["executions"] == [
+ _execution(status = "completed")
+ ]
+ assert client.get("/recipes/r2/executions").json() == {"executions": []}
+
+
+def test_legacy_import_is_insert_only_and_idempotent():
+ client = _client()
+ client.put("/recipes/r1", json = _recipe(name = "Server copy", updated_at = 5000))
+ body = {
+ "recipes": [_recipe(name = "Browser copy"), _recipe("r2")],
+ "executions": [_execution(), _execution("e2", "r2"), _execution("orphan", "missing")],
+ }
+ assert client.post("/recipes/import", json = body).json() == {"recipes": 1, "executions": 2}
+ assert client.post("/recipes/import", json = body).json() == {"recipes": 0, "executions": 0}
+
+ assert client.get("/recipes/r1").json()["name"] == "Server copy"
+ assert client.get("/recipes/r2").status_code == 200
+ assert [e["id"] for e in client.get("/recipes/r2/executions").json()["executions"]] == ["e2"]
+
+
+def test_out_of_range_timestamp_is_a_validation_error_not_a_server_error():
+ client = _client()
+ huge = {**_recipe(), "createdAt": 10**20}
+ assert client.put("/recipes/r1", json = huge).status_code == 422
+ assert client.post("/recipes/import", json = {"recipes": [huge]}).status_code == 422
+
+
+def test_stale_save_is_a_conflict_and_a_current_one_wins():
+ client = _client()
+ client.put("/recipes/r1", json = _recipe(updated_at = 2000))
+ other_tab = {**_recipe(name = "Other tab", updated_at = 3000), "baseUpdatedAt": 2000}
+ assert client.put("/recipes/r1", json = other_tab).status_code == 200
+
+ stale = {**_recipe(name = "Stale tab", updated_at = 4000), "baseUpdatedAt": 2000}
+ assert client.put("/recipes/r1", json = stale).status_code == 409
+ assert client.get("/recipes/r1").json()["name"] == "Other tab"
+
+ current = {**_recipe(name = "Reloaded", updated_at = 5000), "baseUpdatedAt": 3000}
+ assert client.put("/recipes/r1", json = current).json()["name"] == "Reloaded"
+
+
+def test_older_run_snapshot_from_another_tab_does_not_replace_a_newer_one():
+ client = _client()
+ client.put("/recipes/r1", json = _recipe())
+ put = lambda **extra: client.put("/recipes/r1/executions/e1", json = _execution(**extra))
+ assert put(status = "running", lastEventId = 5).status_code == 204
+ assert put(status = "completed", lastEventId = 9).status_code == 204
+ assert put(status = "running", lastEventId = 7).status_code == 204
+ assert put(status = "running", lastEventId = 12).status_code == 204
+ assert put(status = "cancelled", lastEventId = 12).status_code == 204
+
+ stored = client.get("/recipes/r1/executions").json()["executions"][0]
+ assert (stored["status"], stored["lastEventId"]) == ("cancelled", 12)
+
+
+def test_unenriched_snapshot_at_the_same_event_keeps_the_enriched_one():
+ client = _client()
+ client.put("/recipes/r1", json = _recipe())
+ put = lambda **extra: client.put("/recipes/r1/executions/e1", json = _execution(**extra))
+ assert put(status = "completed", lastEventId = 9, analysis = {"num_records": 3}).status_code == 204
+ assert put(status = "completed", lastEventId = 9, analysis = None).status_code == 204
+
+ stored = client.get("/recipes/r1/executions").json()["executions"][0]
+ assert stored["analysis"] == {"num_records": 3}
diff --git a/studio/frontend/src/features/data-recipes/data/legacy-import.ts b/studio/frontend/src/features/data-recipes/data/legacy-import.ts
new file mode 100644
index 00000000000..90d343c4dd6
--- /dev/null
+++ b/studio/frontend/src/features/data-recipes/data/legacy-import.ts
@@ -0,0 +1,150 @@
+// 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 { accountDatabaseName } from "@/lib/account-transition";
+import { normalizeNonEmptyName } from "@/utils";
+import Dexie from "dexie";
+import { RecipeApiError, recipeRequest } from "./recipes-api";
+
+// One-time copy of the browser-only stores into studio.db. The server import is insert-only and
+// honours deletions, so a retry after a partial run (or a cleared flag) cannot clobber or revive
+// anything; the IndexedDB stores are left in place.
+const RECIPES_DB = "unsloth-data-recipes";
+const EXECUTIONS_DB = "unsloth-data-recipe-executions";
+const BATCH_BYTES = 8 * 1024 * 1024;
+
+type Row = Record<string, unknown>;
+type ImportKind = "recipes" | "executions";
+
+let pending: Promise<void> | null = null;
+
+function doneKey(): string {
+ return `${accountDatabaseName(RECIPES_DB)}:server-import.v1`;
+}
+
+export function importLegacyRecipes(): Promise<void> {
+ if (localStorage.getItem(doneKey())) return Promise.resolve();
+ pending ??= runImport().catch((error) => {
+ pending = null;
+ // biome-ignore lint/suspicious/noConsole: retried on the next load
+ console.error("Legacy Data Recipe import failed:", error);
+ });
+ return pending;
+}
+
+async function readStore(name: string, table: string): Promise<Row[]> {
+ const dbName = accountDatabaseName(name);
+ if (!(await Dexie.exists(dbName))) return [];
+ const db = new Dexie(dbName);
+ try {
+ await db.open();
+ return db.tables.some((t) => t.name === table)
+ ? await db.table<Row>(table).toArray()
+ : [];
+ } finally {
+ db.close();
+ }
+}
+
+const isId = (value: unknown): value is string =>
+ typeof value === "string" && value.length > 0 && value.length <= 128;
+const toTime = (value: unknown): number =>
+ typeof value === "number" && Number.isFinite(value) ? Math.round(value) : 0;
+
+function toRecipe(row: Row): Row | null {
+ if (!isId(row.id) || !row.payload || typeof row.payload !== "object") {
+ return null;
+ }
+ const createdAt = toTime(row.createdAt);
+ return {
+ id: row.id,
+ name: normalizeNonEmptyName(typeof row.name === "string" ? row.name : ""),
+ payload: row.payload,
+ createdAt,
+ updatedAt: toTime(row.updatedAt) || createdAt,
+ learningRecipeId: isId(row.learningRecipeId)
+ ? row.learningRecipeId
+ : undefined,
+ learningRecipeTitle:
+ typeof row.learningRecipeTitle === "string"
+ ? row.learningRecipeTitle
+ : undefined,
+ };
+}
+
+function toExecution(row: Row): Row | null {
+ if (!isId(row.id) || !isId(row.recipeId)) return null;
+ return { ...row, createdAt: toTime(row.createdAt) };
+}
+
+function* batches(rows: Row[]): Generator<Row[]> {
+ let batch: Row[] = [];
+ let size = 0;
+ for (const row of rows) {
+ const rowSize = JSON.stringify(row).length;
+ if (batch.length > 0 && size + rowSize > BATCH_BYTES) {
+ yield batch;
+ batch = [];
+ size = 0;
+ }
+ batch.push(row);
+ size += rowSize;
+ }
+ if (batch.length > 0) yield batch;
+}
+
+// Statuses that describe the records themselves; auth, throttling and server errors retry later.
+const RECORD_REJECTED = new Set([400, 413, 422]);
+
+async function submit(
+ account: string,
+ kind: ImportKind,
+ rows: Row[],
+): Promise<void> {
+ // A same-tab account switch must not push one account's browser data into the next.
+ if (accountDatabaseName(RECIPES_DB) !== account) {
+ throw new Error("Account changed during legacy Data Recipe import");
+ }
+ try {
+ await recipeRequest("/import", {
+ method: "POST",
+ body: JSON.stringify({ [kind]: rows }),
+ });
+ } catch (error) {
+ if (
+ !(error instanceof RecipeApiError) ||
+ !RECORD_REJECTED.has(error.status)
+ ) {
+ throw error;
+ }
+ if (rows.length === 1) {
+ // biome-ignore lint/suspicious/noConsole: the record stays in IndexedDB
+ console.warn(`Skipped legacy Data Recipe ${kind} record:`, error.message);
+ return;
+ }
+ for (const row of rows) await submit(account, kind, [row]);
+ }
+}
+
+async function runImport(): Promise<void> {
+ const account = accountDatabaseName(RECIPES_DB);
+ const key = doneKey();
+ const recipes = (await readStore(RECIPES_DB, "recipes"))
+ .map(toRecipe)
+ .filter((row): row is Row => row !== null);
+ const executions = recipes.length
+ ? (await readStore(EXECUTIONS_DB, "executions"))
+ .map(toExecution)
+ .filter((row): row is Row => row !== null)
+ : [];
+ // Recipes first: the server drops runs whose recipe it does not hold.
+ for (const batch of batches(recipes)) {
+ await submit(account, "recipes", batch);
+ }
+ for (const batch of batches(executions)) {
+ await submit(account, "executions", batch);
+ }
+ if (accountDatabaseName(RECIPES_DB) === account) {
+ localStorage.setItem(key, String(Date.now()));
+ }
+}
diff --git a/studio/frontend/src/features/data-recipes/data/recipes-api.ts b/studio/frontend/src/features/data-recipes/data/recipes-api.ts
new file mode 100644
index 00000000000..0ec562afe8f
--- /dev/null
+++ b/studio/frontend/src/features/data-recipes/data/recipes-api.ts
@@ -0,0 +1,47 @@
+// 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 { authFetch, getAuthSessionEpoch } from "@/features/auth";
+
+export const RECIPES_API = "/api/data-recipe/recipes";
+
+export class RecipeApiError extends Error {
+ readonly status: number;
+
+ constructor(message: string, status: number) {
+ super(message);
+ this.status = status;
+ }
+}
+
+function assertSameSession(epoch: number): void {
+ if (getAuthSessionEpoch() !== epoch) {
+ throw new Error("Signed out before the recipe was saved.");
+ }
+}
+
+export async function recipeRequest<T>(
+ path: string,
+ init?: RequestInit,
+): Promise<T> {
+ const epoch = getAuthSessionEpoch();
+ const res = await authFetch(
+ `${RECIPES_API}${path}`,
+ {
+ ...init,
+ headers: init?.body ? { "Content-Type": "application/json" } : undefined,
+ },
+ // A write retried after a refresh must not land in an account that signed in meanwhile.
+ { beforeRetry: () => assertSameSession(epoch) },
+ );
+ if (res.status === 204) return undefined as T;
+ const body = await res.json().catch(() => null);
+ if (!res.ok) {
+ const detail = (body as { detail?: unknown } | null)?.detail;
+ throw new RecipeApiError(
+ typeof detail === "string" ? detail : `Request failed (${res.status})`,
+ res.status,
+ );
+ }
+ return body as T;
+}
diff --git a/studio/frontend/src/features/data-recipes/data/recipes-db.ts b/studio/frontend/src/features/data-recipes/data/recipes-db.ts
index 3709fbaf194..743e64d5f00 100644
--- a/studio/frontend/src/features/data-recipes/data/recipes-db.ts
+++ b/studio/frontend/src/features/data-recipes/data/recipes-db.ts
@@ -2,61 +2,68 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { createEmptyRecipePayload } from "@/features/recipe-studio";
-import { accountDatabaseName } from "@/lib/account-transition";
import { normalizeNonEmptyName } from "@/utils";
-import Dexie, { type EntityTable, liveQuery } from "dexie";
import { useEffect, useState } from "react";
import type { RecipeRecord, SaveRecipeInput } from "../types";
-
-const db = new Dexie(accountDatabaseName("unsloth-data-recipes")) as Dexie & {
- recipes: EntityTable<RecipeRecord, "id">;
-};
-
-db.version(1).stores({
- recipes: "id, name, updatedAt, createdAt",
-});
+import { importLegacyRecipes } from "./legacy-import";
+import { RecipeApiError, recipeRequest } from "./recipes-api";
const recentRecipeCache = new Map<string, RecipeRecord>();
+const listeners = new Set<(recipes: RecipeRecord[]) => void>();
let cachedRecipeList: RecipeRecord[] = [];
let recipeListReady = false;
let recipeListRequest: Promise<RecipeRecord[]> | null = null;
+let mutationVersion = 0;
-export function listRecipes(): Promise<RecipeRecord[]> {
- return db.recipes.orderBy("updatedAt").reverse().toArray();
-}
-
-function cacheRecipeList(recipes: RecipeRecord[]): RecipeRecord[] {
- for (const recipe of recipes) {
- writeRecipeCache(recipe);
- }
- cachedRecipeList = recipes;
+function publishRecipeList(recipes: RecipeRecord[]): RecipeRecord[] {
+ cachedRecipeList = [...recipes].sort((a, b) => b.updatedAt - a.updatedAt);
recipeListReady = true;
- return recipes;
+ // The list is authoritative: a recipe deleted elsewhere must not reopen from the cache.
+ recentRecipeCache.clear();
+ for (const recipe of cachedRecipeList) {
+ recentRecipeCache.set(recipe.id, recipe);
+ }
+ for (const listener of listeners) {
+ listener(cachedRecipeList);
+ }
+ return cachedRecipeList;
}
-export function preloadRecipes(): Promise<RecipeRecord[]> {
- if (recipeListReady) {
- return Promise.resolve(cachedRecipeList);
- }
- if (recipeListRequest) {
- return recipeListRequest;
+async function fetchRecipeList(): Promise<RecipeRecord[]> {
+ await importLegacyRecipes();
+ for (;;) {
+ // A save or delete that lands while the GET is in flight makes its answer stale.
+ const version = mutationVersion;
+ const { recipes } = await recipeRequest<{ recipes: RecipeRecord[] }>("");
+ if (version === mutationVersion) return publishRecipeList(recipes);
}
+}
- const request = listRecipes()
- .then(cacheRecipeList)
- .finally(() => {
- recipeListRequest = null;
- });
- recipeListRequest = request;
- return request;
+export function listRecipes(): Promise<RecipeRecord[]> {
+ recipeListRequest ??= fetchRecipeList().finally(() => {
+ recipeListRequest = null;
+ });
+ return recipeListRequest;
}
-export function getRecipe(id: string): Promise<RecipeRecord | undefined> {
- return db.recipes.get(id);
+export function preloadRecipes(): Promise<RecipeRecord[]> {
+ return recipeListReady ? Promise.resolve(cachedRecipeList) : listRecipes();
}
-function writeRecipeCache(record: RecipeRecord): void {
- recentRecipeCache.set(record.id, record);
+export async function getRecipe(id: string): Promise<RecipeRecord | undefined> {
+ await importLegacyRecipes();
+ try {
+ const record = await recipeRequest<RecipeRecord>(
+ `/${encodeURIComponent(id)}`,
+ );
+ recentRecipeCache.set(id, record);
+ return record;
+ } catch (error) {
+ if (error instanceof RecipeApiError && error.status === 404) {
+ return undefined;
+ }
+ throw error;
+ }
}
export function getCachedRecipe(id: string): RecipeRecord | null {
@@ -64,7 +71,7 @@ export function getCachedRecipe(id: string): RecipeRecord | null {
}
export function primeRecipeCache(record: RecipeRecord): void {
- writeRecipeCache(record);
+ recentRecipeCache.set(record.id, record);
}
export async function saveRecipe(
@@ -72,33 +79,51 @@ export async function saveRecipe(
): Promise<RecipeRecord> {
const now = Date.now();
const id = input.id ?? crypto.randomUUID();
- const existing = input.id ? await db.recipes.get(input.id) : undefined;
- const record: RecipeRecord = {
- id,
- name: normalizeNonEmptyName(input.name),
- payload: input.payload,
- createdAt: existing?.createdAt ?? now,
- updatedAt: now,
- learningRecipeId: input.learningRecipeId ?? existing?.learningRecipeId,
- learningRecipeTitle:
- input.learningRecipeTitle ?? existing?.learningRecipeTitle,
- };
- await db.recipes.put(record);
- writeRecipeCache(record);
+ const existing = input.id
+ ? (recentRecipeCache.get(input.id) ?? (await getRecipe(input.id)))
+ : undefined;
+ let record: RecipeRecord;
+ try {
+ record = await recipeRequest<RecipeRecord>(`/${encodeURIComponent(id)}`, {
+ method: "PUT",
+ body: JSON.stringify({
+ id,
+ name: normalizeNonEmptyName(input.name),
+ payload: input.payload,
+ createdAt: existing?.createdAt ?? now,
+ updatedAt: now,
+ learningRecipeId: input.learningRecipeId ?? existing?.learningRecipeId,
+ learningRecipeTitle:
+ input.learningRecipeTitle ?? existing?.learningRecipeTitle,
+ // Another window may have saved since this copy was read: the server refuses with 409.
+ baseUpdatedAt: input.baseUpdatedAt ?? existing?.updatedAt,
+ }),
+ });
+ } catch (error) {
+ if (error instanceof RecipeApiError && error.status === 409) {
+ recentRecipeCache.delete(id);
+ }
+ throw error;
+ }
+ mutationVersion += 1;
+ recentRecipeCache.set(id, record);
if (recipeListReady) {
- cachedRecipeList = [
+ publishRecipeList([
record,
- ...cachedRecipeList.filter((recipe) => recipe.id !== record.id),
- ].sort((a, b) => b.updatedAt - a.updatedAt);
+ ...cachedRecipeList.filter((recipe) => recipe.id !== id),
+ ]);
}
return record;
}
export async function deleteRecipe(id: string): Promise<void> {
- await db.recipes.delete(id);
+ await recipeRequest<void>(`/${encodeURIComponent(id)}`, {
+ method: "DELETE",
+ });
+ mutationVersion += 1;
recentRecipeCache.delete(id);
if (recipeListReady) {
- cachedRecipeList = cachedRecipeList.filter((recipe) => recipe.id !== id);
+ publishRecipeList(cachedRecipeList.filter((recipe) => recipe.id !== id));
}
}
@@ -122,7 +147,7 @@ export function createRecipeFromLearningRecipe(input: {
});
}
-export function useRecipes(): {
+export function useRecipes(enabled = true): {
recipes: RecipeRecord[];
ready: boolean;
} {
@@ -130,19 +155,21 @@ export function useRecipes(): {
const [ready, setReady] = useState(recipeListReady);
useEffect(() => {
- const sub = liveQuery(() => listRecipes()).subscribe({
- next: (value) => {
- cacheRecipeList(value);
- setRecipes(value);
- setReady(true);
- },
- error: (error) => {
- console.error("data-recipes liveQuery:", error);
- setReady(true);
- },
+ if (!enabled) return;
+ const listener = (value: RecipeRecord[]) => {
+ setRecipes(value);
+ setReady(true);
+ };
+ listeners.add(listener);
+ listRecipes().catch((error) => {
+ // biome-ignore lint/suspicious/noConsole: the page keeps its cached list
+ console.error("Load data recipes failed:", error);
+ setReady(true);
});
- return () => sub.unsubscribe();
- }, []);
+ return () => {
+ listeners.delete(listener);
+ };
+ }, [enabled]);
return { recipes, ready };
}
diff --git a/studio/frontend/src/features/data-recipes/hooks/use-recipe-sidebar-items.ts b/studio/frontend/src/features/data-recipes/hooks/use-recipe-sidebar-items.ts
index 7cf70dc8eba..8f8fbf8a809 100644
--- a/studio/frontend/src/features/data-recipes/hooks/use-recipe-sidebar-items.ts
+++ b/studio/frontend/src/features/data-recipes/hooks/use-recipe-sidebar-items.ts
@@ -1,22 +1,9 @@
// 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 { useEffect, useState } from "react";
-import { liveQuery } from "dexie";
-import { listRecipes } from "../data/recipes-db";
+import { useRecipes } from "../data/recipes-db";
import type { RecipeRecord } from "../types";
-export function useRecipeSidebarItems(enabled: boolean) {
- const [recipes, setRecipes] = useState<RecipeRecord[]>([]);
-
- useEffect(() => {
- if (!enabled) return;
- const sub = liveQuery(() => listRecipes()).subscribe({
- next: (value) => setRecipes(value),
- error: (err) => console.error("recipe sidebar liveQuery:", err),
- });
- return () => sub.unsubscribe();
- }, [enabled]);
-
- return recipes;
+export function useRecipeSidebarItems(enabled: boolean): RecipeRecord[] {
+ return useRecipes(enabled).recipes;
}
diff --git a/studio/frontend/src/features/data-recipes/pages/edit-recipe-page.tsx b/studio/frontend/src/features/data-recipes/pages/edit-recipe-page.tsx
index 87d56874c13..93d83b459cb 100644
--- a/studio/frontend/src/features/data-recipes/pages/edit-recipe-page.tsx
+++ b/studio/frontend/src/features/data-recipes/pages/edit-recipe-page.tsx
@@ -59,22 +59,29 @@ export function EditRecipePage({ recipeId }: EditRecipePageProps): ReactElement
let active = true;
const cachedRecipe = getCachedRecipe(recipeId);
if (cachedRecipe) {
+ // A later server read would replace edits already made in the open editor.
setLoadState({ status: "ready", record: cachedRecipe });
- } else {
- setLoadState({ status: "loading" });
+ return;
}
+ setLoadState({ status: "loading" });
- void getRecipe(recipeId).then((record) => {
- if (!active) {
- return;
- }
- if (!record) {
- setLoadState({ status: "missing" });
- return;
- }
- primeRecipeCache(record);
- setLoadState({ status: "ready", record });
- });
+ getRecipe(recipeId)
+ .then((record) => {
+ if (!active) {
+ return;
+ }
+ if (!record) {
+ setLoadState({ status: "missing" });
+ return;
+ }
+ primeRecipeCache(record);
+ setLoadState({ status: "ready", record });
+ })
+ .catch((error) => {
+ // biome-ignore lint/suspicious/noConsole: the load state below is what the user sees
+ console.error("Load recipe failed:", error);
+ if (active) setLoadState({ status: "missing" });
+ });
return () => {
active = false;
};
@@ -88,13 +95,22 @@ export function EditRecipePage({ recipeId }: EditRecipePageProps): ReactElement
signalReady();
}, [loadState.status, signalReady]);
+ // The version this editor is built on, so a save over another window's newer copy is refused.
+ const editedVersion = useRef<number | undefined>(undefined);
+ const loadedRecord = loadState.status === "ready" ? loadState.record : null;
+ useEffect(() => {
+ editedVersion.current = loadedRecord?.updatedAt;
+ }, [loadedRecord]);
+
const handlePersist = useCallback(
async (input: { id: string | null; name: string; payload: RecipePayload }) => {
const record = await saveRecipe({
id: input.id ?? recipeId,
name: input.name,
payload: input.payload,
+ baseUpdatedAt: editedVersion.current,
});
+ editedVersion.current = record.updatedAt;
primeRecipeCache(record);
return { id: record.id, updatedAt: record.updatedAt };
},
diff --git a/studio/frontend/src/features/data-recipes/types.ts b/studio/frontend/src/features/data-recipes/types.ts
index d3cb14fe394..08c19d9725c 100644
--- a/studio/frontend/src/features/data-recipes/types.ts
+++ b/studio/frontend/src/features/data-recipes/types.ts
@@ -15,6 +15,8 @@ export type RecipeRecord = {
export type SaveRecipeInput = {
id?: string | null;
+ /** updatedAt of the copy being edited; defaults to the cached copy. */
+ baseUpdatedAt?: number;
name: string;
payload: RecipePayload;
learningRecipeId?: string;
diff --git a/studio/frontend/src/features/recipe-studio/data/executions-db.ts b/studio/frontend/src/features/recipe-studio/data/executions-db.ts
index 137c1122b9d..32bc315b120 100644
--- a/studio/frontend/src/features/recipe-studio/data/executions-db.ts
+++ b/studio/frontend/src/features/recipe-studio/data/executions-db.ts
@@ -1,36 +1,121 @@
// 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 { accountDatabaseName } from "@/lib/account-transition";
-import Dexie, { type EntityTable } from "dexie";
+import { authFetch, getAuthSessionEpoch } from "@/features/auth";
import type { RecipeExecutionRecord } from "../execution-types";
-const db = new Dexie(
- accountDatabaseName("unsloth-data-recipe-executions"),
-) as Dexie & {
- executions: EntityTable<RecipeExecutionRecord, "id">;
-};
-
-db.version(1).stores({
- executions: "id, recipeId, kind, status, createdAt",
-});
-
-db.version(2).stores({
- executions: "id, recipeId, kind, status, createdAt, finishedAt, jobId",
-});
+function executionsUrl(recipeId: string): string {
+ return `/api/data-recipe/recipes/${encodeURIComponent(recipeId)}/executions`;
+}
export async function listRecipeExecutions(
recipeId: string,
): Promise<RecipeExecutionRecord[]> {
- const executions = await db.executions
- .where("recipeId")
- .equals(recipeId)
- .toArray();
- return executions.sort((a, b) => b.createdAt - a.createdAt);
+ const res = await authFetch(executionsUrl(recipeId));
+ if (!res.ok) throw new Error(`Load executions failed (${res.status})`);
+ const { executions } = (await res.json()) as {
+ executions: RecipeExecutionRecord[];
+ };
+ return executions;
+}
+
+function assertSameSession(epoch: number): void {
+ if (getAuthSessionEpoch() !== epoch) {
+ // 401 so the transient retry below never resends it.
+ throw Object.assign(new Error("Signed out before the run was saved."), {
+ status: 401,
+ });
+ }
+}
+
+async function putExecution(
+ record: RecipeExecutionRecord,
+ epoch: number,
+): Promise<void> {
+ assertSameSession(epoch);
+ const res = await authFetch(
+ `${executionsUrl(record.recipeId)}/${encodeURIComponent(record.id)}`,
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(record),
+ },
+ { beforeRetry: () => assertSameSession(epoch) },
+ );
+ if (!res.ok) {
+ throw Object.assign(new Error(`Save execution failed (${res.status})`), {
+ status: res.status,
+ });
+ }
+}
+
+const RETRY_DELAYS_MS = [1000, 2000, 4000];
+
+function isTransient(error: unknown): boolean {
+ const status = (error as { status?: number }).status;
+ // No status = the request never got an answer (network, server restart).
+ return (
+ status === undefined || status === 408 || status === 429 || status >= 500
+ );
+}
+
+type Waiter = { resolve: () => void; reject: (error: unknown) => void };
+type Queue = {
+ record: RecipeExecutionRecord | null;
+ epoch: number;
+ waiters: Waiter[];
+};
+
+const queues = new Map<string, Queue>();
+
+async function drain(id: string, queue: Queue): Promise<void> {
+ let carried: Waiter[] = [];
+ let attempt = 0;
+ while (queue.record) {
+ const { record, epoch } = queue;
+ const waiters = [...carried, ...queue.waiters];
+ queue.record = null;
+ queue.waiters = [];
+ carried = [];
+ try {
+ await putExecution(record, epoch);
+ attempt = 0;
+ for (const waiter of waiters) waiter.resolve();
+ } catch (error) {
+ // The final snapshot of a finished run is never sent again, so a transient failure retries
+ // it unless a newer snapshot has arrived meanwhile.
+ if (isTransient(error) && attempt < RETRY_DELAYS_MS.length) {
+ await new Promise((r) => setTimeout(r, RETRY_DELAYS_MS[attempt]));
+ attempt += 1;
+ if (!queue.record) {
+ queue.record = record;
+ queue.epoch = epoch;
+ }
+ carried = waiters;
+ continue;
+ }
+ attempt = 0;
+ for (const waiter of waiters) waiter.reject(error);
+ }
+ }
+ queues.delete(id);
}
-export async function saveRecipeExecution(
+// Progress events save the same run many times a second: keep one write per run in flight and
+// send only the newest record after it, so a slow older PUT can never land last. Each caller
+// settles with the PUT that carried its record (or a newer one).
+export function saveRecipeExecution(
execution: RecipeExecutionRecord,
): Promise<void> {
- await db.executions.put(execution);
+ return new Promise((resolve, reject) => {
+ const running = queues.get(execution.id);
+ const queue = running ?? { record: null, epoch: 0, waiters: [] };
+ queue.record = execution;
+ queue.epoch = getAuthSessionEpoch();
+ queue.waiters.push({ resolve, reject });
+ if (!running) {
+ queues.set(execution.id, queue);
+ void drain(execution.id, queue);
+ }
+ });
}
diff --git a/studio/frontend/src/features/recipe-studio/hooks/use-recipe-persistence.ts b/studio/frontend/src/features/recipe-studio/hooks/use-recipe-persistence.ts
index f68ade47245..c1f406fd14a 100644
--- a/studio/frontend/src/features/recipe-studio/hooks/use-recipe-persistence.ts
+++ b/studio/frontend/src/features/recipe-studio/hooks/use-recipe-persistence.ts
@@ -229,6 +229,8 @@ export function useRecipePersistence({
const [workflowName, setWorkflowName] = useState("Unnamed");
const [lastSavedAt, setLastSavedAt] = useState<number | null>(null);
const [savedSignature, setSavedSignature] = useState("");
+ // Autosave does not retry the exact content that just failed (e.g. a 409 from another window).
+ const [failedSignature, setFailedSignature] = useState<string | null>(null);
const [saveLoading, setSaveLoading] = useState(false);
const [copied, setCopied] = useState(false);
const [importOpen, setImportOpen] = useState(false);
@@ -295,25 +297,30 @@ export function useRecipePersistence({
payload: currentPayload,
});
setLastSavedAt(result.updatedAt);
+ setFailedSignature(null);
setSavedSignature(buildSignature(nextName, currentPayload));
drainQueuedUploadCleanups(currentPayload);
} catch (error) {
console.error("Save recipe failed:", error);
- toastError("Save failed", "Could not save recipe.");
+ setFailedSignature(buildSignature(nextName, currentPayload));
+ toastError(
+ "Save failed",
+ error instanceof Error ? error.message : "Could not save recipe.",
+ );
} finally {
setSaveLoading(false);
}
}, [currentPayload, onPersistRecipe, recipeId, saveLoading, workflowName]);
useEffect(() => {
- if (!isDirty || saveLoading) {
+ if (!isDirty || saveLoading || failedSignature === currentSignature) {
return;
}
const timeoutId = window.setTimeout(() => {
void persistRecipe();
}, 800);
return () => window.clearTimeout(timeoutId);
- }, [isDirty, persistRecipe, saveLoading]);
+ }, [currentSignature, failedSignature, isDirty, persistRecipe, saveLoading]);
// Drain queued cleanups even when autosave is skipped: a net-zero edit (add then remove an
// unstructured seed before the 800ms debounce) keeps isDirty false, so the autosave effect never
diff --git a/studio/frontend/tests/recipe-server-persistence.test.ts b/studio/frontend/tests/recipe-server-persistence.test.ts
new file mode 100644
index 00000000000..2b7a0444d87
--- /dev/null
+++ b/studio/frontend/tests/recipe-server-persistence.test.ts
@@ -0,0 +1,271 @@
+// 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 assert from "node:assert/strict";
+import test from "node:test";
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+type Call = { url: string; method: string; body: unknown };
+
+function fakeServer(respond: (call: Call) => number) {
+ const calls: Call[] = [];
+ const release: (() => void)[] = [];
+ const authFetch = (url: string, init: RequestInit = {}) => {
+ const call = {
+ url,
+ method: init.method ?? "GET",
+ body: init.body ? JSON.parse(String(init.body)) : null,
+ };
+ calls.push(call);
+ const status = respond(call);
+ return new Promise<Response>((resolve) => {
+ release.push(() =>
+ resolve(new Response(status === 204 ? null : "{}", { status })),
+ );
+ });
+ };
+ const flush = async () => {
+ while (release.length) {
+ release.shift()?.();
+ await new Promise((r) => setTimeout(r, 0));
+ }
+ };
+ return { calls, authFetch, flush };
+}
+
+test("a run saved many times sends one write in flight and then only the newest", async () => {
+ const server = fakeServer(() => 204);
+ const { saveRecipeExecution } = loadWithStubs<{
+ saveRecipeExecution: (record: Record<string, unknown>) => Promise<void>;
+ }>(
+ new URL(
+ "../src/features/recipe-studio/data/executions-db.ts",
+ import.meta.url,
+ ),
+ {
+ "@/features/auth": {
+ authFetch: server.authFetch,
+ getAuthSessionEpoch: () => 1,
+ },
+ },
+ );
+
+ const save = (done: number) =>
+ saveRecipeExecution({ id: "e1", recipeId: "r1", done });
+ const saves = [save(1)];
+ await new Promise((r) => setTimeout(r, 0));
+ saves.push(save(2), save(3), save(4));
+ await new Promise((r) => setTimeout(r, 0));
+ assert.equal(server.calls.length, 1);
+ await server.flush();
+ await Promise.all(saves);
+
+ assert.deepEqual(
+ server.calls.map((c) => [
+ c.method,
+ c.url,
+ (c.body as { done: number }).done,
+ ]),
+ [
+ ["PUT", "/api/data-recipe/recipes/r1/executions/e1", 1],
+ ["PUT", "/api/data-recipe/recipes/r1/executions/e1", 4],
+ ],
+ );
+});
+
+test("every coalesced caller hears about the failed write that carried its record", async () => {
+ let status = 204;
+ const server = fakeServer(() => status);
+ const { saveRecipeExecution } = loadWithStubs<{
+ saveRecipeExecution: (record: Record<string, unknown>) => Promise<void>;
+ }>(
+ new URL(
+ "../src/features/recipe-studio/data/executions-db.ts",
+ import.meta.url,
+ ),
+ {
+ "@/features/auth": {
+ authFetch: server.authFetch,
+ getAuthSessionEpoch: () => 1,
+ },
+ },
+ );
+ const first = saveRecipeExecution({ id: "e1", recipeId: "r1", done: 1 });
+ const later = [2, 3].map((done) =>
+ saveRecipeExecution({ id: "e1", recipeId: "r1", done }),
+ );
+ const settled = Promise.allSettled([first, ...later]);
+ status = 422;
+ await server.flush();
+ const outcomes = await settled;
+ assert.deepEqual(
+ outcomes.map((o) => o.status),
+ ["fulfilled", "rejected", "rejected"],
+ );
+});
+
+test("a transient failure retries the newest snapshot instead of dropping it", async () => {
+ const statuses = [503, 204];
+ const server = fakeServer(() => statuses.shift() ?? 204);
+ const { saveRecipeExecution } = loadWithStubs<{
+ saveRecipeExecution: (record: Record<string, unknown>) => Promise<void>;
+ }>(
+ new URL(
+ "../src/features/recipe-studio/data/executions-db.ts",
+ import.meta.url,
+ ),
+ {
+ "@/features/auth": {
+ authFetch: server.authFetch,
+ getAuthSessionEpoch: () => 1,
+ },
+ },
+ );
+ const saved = saveRecipeExecution({ id: "e1", recipeId: "r1", done: 9 });
+ await server.flush();
+ await new Promise((r) => setTimeout(r, 1100));
+ await server.flush();
+ await saved;
+ assert.deepEqual(
+ server.calls.map((c) => (c.body as { done: number }).done),
+ [9, 9],
+ );
+});
+
+test("legacy import isolates a rejected record, keeps the rest, and runs once", async () => {
+ const storage = new Map<string, string>();
+ globalThis.localStorage = {
+ getItem: (k: string) => storage.get(k) ?? null,
+ setItem: (k: string, v: string) => void storage.set(k, v),
+ } as Storage;
+ const rejected = "bad";
+ const imported: string[] = [];
+ const recipeRequest = (_path: string, init: RequestInit) => {
+ const body = JSON.parse(String(init.body)) as Record<
+ string,
+ { id: string }[]
+ >;
+ const rows = body.recipes ?? body.executions;
+ if (rows.some((row) => row.id === rejected)) {
+ return Promise.reject(new RecipeApiError("too large", 422));
+ }
+ imported.push(...rows.map((row) => row.id));
+ return Promise.resolve({});
+ };
+ class RecipeApiError extends Error {
+ status: number;
+ constructor(message: string, status: number) {
+ super(message);
+ this.status = status;
+ }
+ }
+ const stores: Record<string, Record<string, unknown>[]> = {
+ "unsloth-data-recipes": [
+ { id: "a", name: "A", payload: {}, createdAt: 1, updatedAt: 2 },
+ { id: rejected, name: "Bad", payload: {}, createdAt: 1, updatedAt: 2 },
+ { id: "no-payload", name: "Skipped client-side" },
+ ],
+ "unsloth-data-recipe-executions": [
+ { id: "e1", recipeId: "a", createdAt: 1 },
+ ],
+ };
+ class FakeDexie {
+ static exists = (name: string) => Promise.resolve(name in stores);
+ tables = [{ name: "recipes" }, { name: "executions" }];
+ dbName: string;
+ constructor(dbName: string) {
+ this.dbName = dbName;
+ }
+ open = () => Promise.resolve();
+ close = () => undefined;
+ table = () => ({ toArray: () => Promise.resolve(stores[this.dbName]) });
+ }
+ const { importLegacyRecipes } = loadWithStubs<{
+ importLegacyRecipes: () => Promise<void>;
+ }>(
+ new URL(
+ "../src/features/data-recipes/data/legacy-import.ts",
+ import.meta.url,
+ ),
+ {
+ "@/lib/account-transition": {
+ accountDatabaseName: (name: string) => name,
+ },
+ "@/utils": {
+ normalizeNonEmptyName: (name: string) => name.trim() || "Unnamed",
+ },
+ dexie: { default: FakeDexie, __esModule: true },
+ "./recipes-api": { recipeRequest, RecipeApiError },
+ },
+ );
+
+ const warn = console.warn;
+ console.warn = () => undefined;
+ try {
+ await importLegacyRecipes();
+ await importLegacyRecipes();
+ } finally {
+ console.warn = warn;
+ }
+ assert.deepEqual(imported, ["a", "e1"]);
+ assert.ok(storage.get("unsloth-data-recipes:server-import.v1"));
+});
+
+test("an auth or throttling failure leaves the legacy import to retry", async () => {
+ const storage = new Map<string, string>();
+ globalThis.localStorage = {
+ getItem: (k: string) => storage.get(k) ?? null,
+ setItem: (k: string, v: string) => void storage.set(k, v),
+ } as Storage;
+ class RecipeApiError extends Error {
+ status: number;
+ constructor(message: string, status: number) {
+ super(message);
+ this.status = status;
+ }
+ }
+ let calls = 0;
+ const recipeRequest = () => {
+ calls += 1;
+ return Promise.reject(new RecipeApiError("Unauthorized", 401));
+ };
+ class FakeDexie {
+ static exists = () => Promise.resolve(true);
+ tables = [{ name: "recipes" }];
+ open = () => Promise.resolve();
+ close = () => undefined;
+ table = () => ({
+ toArray: () =>
+ Promise.resolve([
+ { id: "a", name: "A", payload: {}, createdAt: 1, updatedAt: 2 },
+ { id: "b", name: "B", payload: {}, createdAt: 1, updatedAt: 2 },
+ ]),
+ });
+ }
+ const { importLegacyRecipes } = loadWithStubs<{
+ importLegacyRecipes: () => Promise<void>;
+ }>(
+ new URL(
+ "../src/features/data-recipes/data/legacy-import.ts",
+ import.meta.url,
+ ),
+ {
+ "@/lib/account-transition": {
+ accountDatabaseName: (name: string) => name,
+ },
+ "@/utils": { normalizeNonEmptyName: (name: string) => name },
+ dexie: { default: FakeDexie, __esModule: true },
+ "./recipes-api": { recipeRequest, RecipeApiError },
+ },
+ );
+ const error = console.error;
+ console.error = () => undefined;
+ try {
+ await importLegacyRecipes();
+ await importLegacyRecipes();
+ } finally {
+ console.error = error;
+ }
+ assert.equal(calls, 2);
+ assert.equal(storage.get("unsloth-data-recipes:server-import.v1"), undefined);
+});