From a9391da4e4a5d1c9308aadaa8bd0e93f50dfcc30 Mon Sep 17 00:00:00 2001 From: Irozuku Date: Thu, 3 Dec 2026 19:03:09 -0300 Subject: [PATCH 1/8] fix: refuse to copy stored files from an empty or relative path --- DashAI/back/core/stored_paths.py | 157 +++++++++++++++++++++++++++ tests/back/core/test_stored_paths.py | 41 +++++++ 2 files changed, 198 insertions(+) create mode 100644 DashAI/back/core/stored_paths.py create mode 100644 tests/back/core/test_stored_paths.py diff --git a/DashAI/back/core/stored_paths.py b/DashAI/back/core/stored_paths.py new file mode 100644 index 000000000..23e8b77ef --- /dev/null +++ b/DashAI/back/core/stored_paths.py @@ -0,0 +1,157 @@ +"""Copies of the files an entity keeps under its stored path. + +A failed upload or parse leaves an entity with an empty ``file_path``, and +``Path("")`` is the current working directory. Every copy made from a stored +path goes through these helpers, so such a path is refused before anything +is written instead of copying the backend's working directory. +""" + +import shutil +from pathlib import Path +from typing import Optional, Union + +StoredPath = Union[str, Path, None] + + +class StoredPathError(FileNotFoundError): + """A stored path that names no files to copy.""" + + +def _stored_path_problem(path: StoredPath, directory: bool) -> Optional[str]: + """Explain why a stored path cannot be copied from. + + Parameters + ---------- + path : str, Path or None + The path read from the entity row. + directory : bool + Whether the path must be a directory. + + Returns + ------- + str or None + The reason, or None when the path can be copied from. + """ + if path is None or not str(path).strip(): + return "The stored path is empty." + source = Path(path) + if not source.is_absolute(): + return f"The stored path '{path}' is relative to the working directory." + if not source.exists(): + return f"The stored path '{path}' does not exist." + if directory and not source.is_dir(): + return f"The stored path '{path}' is not a directory." + return None + + +def is_stored_path(path: StoredPath) -> bool: + """Tell whether a stored file or directory can be copied from. + + Parameters + ---------- + path : str, Path or None + The path read from the entity row. + + Returns + ------- + bool + True when the path is absolute and exists. + """ + return _stored_path_problem(path, directory=False) is None + + +def is_stored_directory(path: StoredPath) -> bool: + """Tell whether a stored directory can be copied from. + + Parameters + ---------- + path : str, Path or None + The path read from the entity row. + + Returns + ------- + bool + True when the path is absolute and an existing directory. + """ + return _stored_path_problem(path, directory=True) is None + + +def require_stored_path(path: StoredPath, directory: bool = False) -> Path: + """Return a stored path that can be copied from. + + Parameters + ---------- + path : str, Path or None + The path read from the entity row. + directory : bool + Whether the path must be a directory. + + Returns + ------- + Path + The path. + + Raises + ------ + StoredPathError + If the path is empty, relative, missing, or not a directory when one + is required. + """ + problem = _stored_path_problem(path, directory) + if problem is not None: + raise StoredPathError(problem) + return Path(str(path)) + + +def copy_stored_tree( + source: StoredPath, destination: Union[str, Path], dirs_exist_ok: bool = False +) -> Path: + """Copy a stored directory. + + Parameters + ---------- + source : str, Path or None + The stored directory. + destination : str or Path + Where the copy goes. + dirs_exist_ok : bool + Whether the copy may write into an existing ``destination``. + + Returns + ------- + Path + The destination. + + Raises + ------ + StoredPathError + If ``source`` is not a stored directory; nothing is written then. + """ + stored = require_stored_path(source, directory=True) + return Path(shutil.copytree(stored, destination, dirs_exist_ok=dirs_exist_ok)) + + +def copy_stored_entry(source: StoredPath, destination: Union[str, Path]) -> Path: + """Copy a stored file or directory. + + Parameters + ---------- + source : str, Path or None + The stored file or directory. + destination : str or Path + Where the copy goes. + + Returns + ------- + Path + The destination. + + Raises + ------ + StoredPathError + If ``source`` is not a stored path; nothing is written then. + """ + stored = require_stored_path(source) + if stored.is_dir(): + return Path(shutil.copytree(stored, destination)) + return Path(shutil.copy2(stored, destination)) diff --git a/tests/back/core/test_stored_paths.py b/tests/back/core/test_stored_paths.py new file mode 100644 index 000000000..5a405ab8f --- /dev/null +++ b/tests/back/core/test_stored_paths.py @@ -0,0 +1,41 @@ +from pathlib import Path + +import pytest + +from DashAI.back.core.stored_paths import ( + StoredPathError, + copy_stored_entry, + copy_stored_tree, +) + +UNCOPYABLE_SOURCES = { + "empty_string": lambda root: "", + "none": lambda root: None, + "empty_path": lambda root: Path(""), + "dot": lambda root: ".", + "relative_under_empty_base": lambda root: Path("") / "dataset", + "missing_absolute": lambda root: root / "gone", +} + + +@pytest.fixture(name="working_directory") +def a_working_directory_with_a_dataset_folder(tmp_path, monkeypatch): + cwd = tmp_path / "cwd" + (cwd / "dataset").mkdir(parents=True) + (cwd / "dataset" / "data.arrow").write_bytes(b"arrow") + (cwd / "pyproject.toml").write_text("[project]", encoding="utf-8") + monkeypatch.chdir(cwd) + return cwd + + +@pytest.mark.parametrize("copy", [copy_stored_tree, copy_stored_entry]) +@pytest.mark.parametrize("source", UNCOPYABLE_SOURCES.values(), ids=UNCOPYABLE_SOURCES) +def test_failed_dataset_path_never_copies_the_working_directory( + working_directory, tmp_path, copy, source +): + destination = tmp_path / "datasets" / "b196c4c6" + + with pytest.raises(StoredPathError): + copy(source(tmp_path), destination) + + assert not destination.exists() From 323bd0bdc3d527318eed1b8a78003981e55c459b Mon Sep 17 00:00:00 2001 From: Irozuku Date: Thu, 3 Dec 2026 19:05:28 -0300 Subject: [PATCH 2/8] fix: refuse notebooks from datasets that did not finish loading --- DashAI/back/api/api_v1/endpoints/notebook.py | 66 +++++++++++++++----- tests/back/api/test_document_notebook_api.py | 30 +++++++++ tests/back/api/test_notebook_api.py | 52 +++++++++++++++ 3 files changed, 134 insertions(+), 14 deletions(-) diff --git a/DashAI/back/api/api_v1/endpoints/notebook.py b/DashAI/back/api/api_v1/endpoints/notebook.py index 2f9c44ce5..00ee8c8e2 100644 --- a/DashAI/back/api/api_v1/endpoints/notebook.py +++ b/DashAI/back/api/api_v1/endpoints/notebook.py @@ -21,7 +21,8 @@ read_outline, require_content_type, ) -from DashAI.back.core.enums.status import DocumentStatus +from DashAI.back.core.enums.status import DatasetStatus, DocumentStatus +from DashAI.back.core.stored_paths import copy_stored_tree, is_stored_directory from DashAI.back.dependencies.database.models import ( Converter, DataDocument, @@ -60,6 +61,37 @@ class _NotebookCopy(NamedTuple): file_path: Path +def _ready_source(ready: bool, source: Path, detail: str) -> Path: + """Return the directory a notebook copies, once its entity is ready. + + Parameters + ---------- + ready : bool + Whether the dataset or document finished loading. + source : Path + The stored directory the notebook would copy. + detail : str + Error detail sent when the source cannot be copied. + + Returns + ------- + Path + ``source``. + + Raises + ------ + HTTPException + 422 with ``detail`` when the entity is not finished or its stored + directory is empty, relative or missing. + """ + if not ready or not is_stored_directory(source): + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail=detail, + ) + return source + + def _plan_notebook_copy( db: "Session", params: NotebookCreate, config: Dict[str, Any] ) -> _NotebookCopy: @@ -87,8 +119,9 @@ def _plan_notebook_copy( Raises ------ HTTPException - 404 when the source does not exist, 422 when the document has not - finished parsing. + 404 when the source does not exist, 422 ``Dataset is not ready`` or + ``Document is not ready`` when it has not finished loading or has no + stored files. """ if params.document_id is not None: document = db.get(DataDocument, params.document_id) @@ -97,16 +130,16 @@ def _plan_notebook_copy( status_code=status.HTTP_404_NOT_FOUND, detail="Document not found", ) - if document.status != DocumentStatus.FINISHED or not document.file_path: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="Document is not ready", - ) + source = _ready_source( + document.status == DocumentStatus.FINISHED, + Path(document.file_path or "") / "document", + "Document is not ready", + ) working_dir = ( Path(config["NOTEBOOK_PATH"]) / DOCUMENT_NOTEBOOKS_DIR / uuid.uuid4().hex ) return _NotebookCopy( - source=Path(document.file_path) / "document", + source=source, destination=working_dir / "document", file_path=working_dir, ) @@ -117,9 +150,14 @@ def _plan_notebook_copy( status_code=status.HTTP_404_NOT_FOUND, detail="Dataset not found", ) + source = _ready_source( + dataset.status == DatasetStatus.FINISHED, + Path(dataset.file_path or ""), + "Dataset is not ready", + ) working_dir = Path(config["DATASETS_PATH"]) / uuid.uuid4().hex[:8] return _NotebookCopy( - source=Path(dataset.file_path), + source=source, destination=working_dir, file_path=working_dir, ) @@ -153,9 +191,9 @@ def create_notebook( Raises ------ HTTPException - 404 when the dataset or document does not exist, 422 when the - document has not finished parsing, 500 when the copy or the database - write fails. + 404 when the dataset or document does not exist, 422 when it has + not finished loading or has no stored files, 500 when the copy or the + database write fails. """ import shutil @@ -164,7 +202,7 @@ def create_notebook( with session_factory() as db: copy = _plan_notebook_copy(db, params, config) try: - shutil.copytree(copy.source, copy.destination, dirs_exist_ok=True) + copy_stored_tree(copy.source, copy.destination, dirs_exist_ok=True) notebook_model = Notebook( name=params.name or "Untitled Notebook", description=params.description, diff --git a/tests/back/api/test_document_notebook_api.py b/tests/back/api/test_document_notebook_api.py index ad828585f..3923d9105 100644 --- a/tests/back/api/test_document_notebook_api.py +++ b/tests/back/api/test_document_notebook_api.py @@ -2,6 +2,7 @@ import inspect import io +import shutil import uuid from pathlib import Path from typing import Tuple @@ -188,6 +189,35 @@ def test_create_notebook_rejects_unfinished_document(client: TestClient) -> None assert response.json()["detail"] == "Document is not ready" +@pytest.mark.parametrize("stored", ["empty", "missing"]) +def test_create_notebook_rejects_a_finished_document_without_stored_files( + client: TestClient, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + stored: str, +) -> None: + (tmp_path / "document").mkdir() + (tmp_path / "document" / "document.json").write_text("{}", encoding="utf-8") + monkeypatch.chdir(tmp_path) + document_id, document_dir = _create_data_document(client, f"stored_files_{stored}") + if stored == "empty": + with client.app.container["session_factory"]() as db: + db.get(DataDocument, document_id).file_path = "" + db.commit() + else: + shutil.rmtree(document_dir) + notebooks_path = Path(client.app.container["config"]["NOTEBOOK_PATH"]) + before = set(notebooks_path.rglob("*")) + + response = client.post( + "/api/v1/notebook/", json={"name": "orphan", "document_id": document_id} + ) + + assert response.status_code == 422, response.text + assert response.json()["detail"] == "Document is not ready" + assert set(notebooks_path.rglob("*")) == before + + def test_create_notebook_unknown_sources(client: TestClient) -> None: missing_document = client.post( "/api/v1/notebook/", json={"name": "ghost", "document_id": 999999} diff --git a/tests/back/api/test_notebook_api.py b/tests/back/api/test_notebook_api.py index 19c130717..081d17b8e 100644 --- a/tests/back/api/test_notebook_api.py +++ b/tests/back/api/test_notebook_api.py @@ -1,8 +1,23 @@ +import uuid +from pathlib import Path + +import pytest from fastapi.testclient import TestClient +from DashAI.back.core.enums.status import DatasetStatus from DashAI.back.dependencies.database.models import Dataset +def _stored_dataset(client: TestClient, status: DatasetStatus, file_path: str) -> int: + with client.app.container["session_factory"]() as db: + dataset = Dataset( + name=f"stored_{uuid.uuid4().hex[:8]}", file_path=file_path, status=status + ) + db.add(dataset) + db.commit() + return dataset.id + + def test_delete_notebook(client: TestClient, dataset_1: Dataset) -> None: response = client.post( "/api/v1/notebook/", @@ -42,3 +57,40 @@ def test_bulk_delete_notebooks(client: TestClient, dataset_1: Dataset) -> None: for notebook_id in created_ids: response = client.get(f"/api/v1/notebook/{notebook_id}") assert response.status_code == 404, response.text + + +@pytest.mark.parametrize( + ("status", "stored"), + [ + (DatasetStatus.ERROR, "empty"), + (DatasetStatus.FINISHED, "empty"), + (DatasetStatus.FINISHED, "missing"), + (DatasetStatus.STARTED, "ready"), + ], +) +def test_notebook_from_failed_iris_upload_is_refused_without_copying_files( + client: TestClient, + dataset_1: Dataset, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + status: DatasetStatus, + stored: str, +) -> None: + (tmp_path / "pyproject.toml").write_text("[project]", encoding="utf-8") + monkeypatch.chdir(tmp_path) + file_path = { + "empty": "", + "missing": str(tmp_path / "gone"), + "ready": dataset_1.file_path, + }[stored] + dataset_id = _stored_dataset(client, status, file_path) + datasets_path = Path(client.app.container["config"]["DATASETS_PATH"]) + before = set(datasets_path.iterdir()) + + response = client.post( + "/api/v1/notebook/", json={"name": "early", "dataset_id": dataset_id} + ) + + assert response.status_code == 422, response.text + assert response.json()["detail"] == "Dataset is not ready" + assert set(datasets_path.iterdir()) == before From 04ef56b939514abf780b19b1945a488d659c1aa1 Mon Sep 17 00:00:00 2001 From: Irozuku Date: Thu, 3 Dec 2026 19:06:24 -0300 Subject: [PATCH 3/8] fix: keep the notebook working copy when its source has no stored files --- .../back/api/api_v1/endpoints/converters.py | 9 ++++++++ .../back/dataloaders/classes/notebook_data.py | 16 +++++++++----- tests/back/api/test_document_converter_job.py | 22 +++++++++++++++++++ 3 files changed, 42 insertions(+), 5 deletions(-) diff --git a/DashAI/back/api/api_v1/endpoints/converters.py b/DashAI/back/api/api_v1/endpoints/converters.py index 6b8857d39..75c8a28bd 100644 --- a/DashAI/back/api/api_v1/endpoints/converters.py +++ b/DashAI/back/api/api_v1/endpoints/converters.py @@ -304,7 +304,10 @@ async def delete_converter( The notebook's working copy, dataset or document, is restored from its source and the earlier converters are enqueued again in creation order. + A source without stored files answers 409 ``Notebook source data is + missing`` and changes nothing. """ + from DashAI.back.core.stored_paths import StoredPathError from DashAI.back.dataloaders.classes.notebook_data import restore_notebook_data from DashAI.back.dependencies.database.models import Converter, Explorer from DashAI.back.job.converter_job import ConverterJob @@ -369,6 +372,12 @@ async def delete_converter( last_job_id = job_ids[-1] if job_ids else None return {"jobId": last_job_id} + except StoredPathError as e: + logger.warning("Notebook %s has no source to restore: %s", notebook.id, e) + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="Notebook source data is missing", + ) from e except exc.SQLAlchemyError as e: logger.exception(e) raise HTTPException( diff --git a/DashAI/back/dataloaders/classes/notebook_data.py b/DashAI/back/dataloaders/classes/notebook_data.py index 895281e4d..a1b1e41f3 100644 --- a/DashAI/back/dataloaders/classes/notebook_data.py +++ b/DashAI/back/dataloaders/classes/notebook_data.py @@ -11,6 +11,7 @@ from typing import TYPE_CHECKING, Any, Dict, List from DashAI.back.core.data_kinds import DOCUMENT +from DashAI.back.core.stored_paths import copy_stored_tree, require_stored_path if TYPE_CHECKING: from DashAI.back.dataloaders.classes.dashai_dataset import DashAIDataset @@ -49,7 +50,7 @@ def original_data_path(notebook: Any) -> str: dataset folder that is copied over the notebook folder. """ if notebook.data_kind == DOCUMENT: - return os.path.join(notebook.document.file_path, "document") + return os.path.join(notebook.document.file_path or "", "document") return notebook.dataset.file_path @@ -89,15 +90,20 @@ def restore_notebook_data(notebook: Any) -> None: ---------- notebook : Notebook The notebook record. + + Raises + ------ + StoredPathError + If the original data has no stored directory; the working copy is + left as it was. """ + source = require_stored_path(original_data_path(notebook), directory=True) if notebook.data_kind == DOCUMENT: working = notebook_data_path(notebook) shutil.rmtree(working, ignore_errors=True) - shutil.copytree(original_data_path(notebook), working) + copy_stored_tree(source, working) return - shutil.copytree( - original_data_path(notebook), notebook.file_path, dirs_exist_ok=True - ) + copy_stored_tree(source, notebook.file_path, dirs_exist_ok=True) arrow_path = os.path.join(notebook.file_path, "dataset", "data.arrow") if os.path.exists(arrow_path): now = time.time() diff --git a/tests/back/api/test_document_converter_job.py b/tests/back/api/test_document_converter_job.py index 8bb1a2e42..8cc6b9722 100644 --- a/tests/back/api/test_document_converter_job.py +++ b/tests/back/api/test_document_converter_job.py @@ -144,6 +144,28 @@ def test_deleting_the_only_converter_restores_the_original_document( assert working_document(client, notebook_id)[Text] == ["a_b"] +def test_deleting_a_converter_keeps_the_working_copy_when_the_source_is_gone( + client: TestClient, tmp_path, monkeypatch +): + (tmp_path / "document").mkdir() + monkeypatch.chdir(tmp_path) + notebook_id = create_document_notebook(client, "delete_orphan", ["a_b"]) + converter_id = add_converter( + client, notebook_id, "CharacterReplacer", UNDERSCORES, [{"columnName": "Text"}] + ) + ConverterJob(converter_id=converter_id).run() + with client.app.container["session_factory"]() as db: + db.get(Notebook, notebook_id).document.file_path = "" + db.commit() + + response = client.delete(f"/api/v1/converter/{converter_id}") + + assert response.status_code == 409, response.text + assert response.json()["detail"] == "Notebook source data is missing" + assert working_document(client, notebook_id)[Text] == ["a b"] + assert converter_status(client, converter_id) == ConverterStatus.FINISHED + + def test_deleting_a_later_converter_replays_the_earlier_one(client: TestClient): notebook_id = create_document_notebook(client, "delete_replay", ["a_b_c"]) first = add_converter( From ac49d9fe3742fc78d1ea4ba69673e15c580e8409 Mon Sep 17 00:00:00 2001 From: Irozuku Date: Thu, 3 Dec 2026 19:07:08 -0300 Subject: [PATCH 4/8] fix: refuse to save a document notebook without its working copy --- .../api/api_v1/endpoints/data_documents.py | 14 ++++++++-- .../api/test_document_from_notebook_api.py | 28 +++++++++++++++++-- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/DashAI/back/api/api_v1/endpoints/data_documents.py b/DashAI/back/api/api_v1/endpoints/data_documents.py index 4f6f40dbc..91344ad77 100644 --- a/DashAI/back/api/api_v1/endpoints/data_documents.py +++ b/DashAI/back/api/api_v1/endpoints/data_documents.py @@ -34,6 +34,7 @@ require_content_type, ) from DashAI.back.core.enums.status import ConverterStatus, DocumentStatus +from DashAI.back.core.stored_paths import copy_stored_tree, is_stored_directory from DashAI.back.dependencies.database.models import ( Converter, DataDocument, @@ -266,7 +267,7 @@ def _copy_notebook_document( dict The item counts of the copied document, keyed by type name. """ - shutil.copytree(working_copy, target / "document") + copy_stored_tree(working_copy, target / "document") sidecar_path = target / "document" / "document.json" with open(sidecar_path, "r", encoding="utf-8") as f: sidecar = json.load(f) @@ -312,8 +313,10 @@ def create_data_document_from_notebook( ------ HTTPException 404 for an unknown notebook; 409 for a taken name or while a - converter of the notebook is still running; 422 for an empty name or - a dataset notebook; 500 when the copy or the database fails. + converter of the notebook is still running; 422 for an empty name, a + dataset notebook, or ``Notebook document is missing`` when the + working copy has no stored files; 500 when the copy or the database + fails. """ from DashAI.back.dataloaders.classes.notebook_data import notebook_data_path @@ -334,6 +337,11 @@ def create_data_document_from_notebook( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Only document notebooks can be saved as documents", ) + if not is_stored_directory(notebook_data_path(notebook)): + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Notebook document is missing", + ) running = db.execute( select(Converter.id).where( Converter.notebook_id == notebook.id, diff --git a/tests/back/api/test_document_from_notebook_api.py b/tests/back/api/test_document_from_notebook_api.py index 5ee7306ce..2cff7b0ec 100644 --- a/tests/back/api/test_document_from_notebook_api.py +++ b/tests/back/api/test_document_from_notebook_api.py @@ -8,10 +8,15 @@ from DashAI.back.core.enums.status import ConverterStatus, DocumentStatus from DashAI.back.dataloaders.classes.dashai_document import load_document -from DashAI.back.dependencies.database.models import Converter, Dataset +from DashAI.back.dependencies.database.models import Converter, Dataset, Notebook from DashAI.back.job.converter_job import ConverterJob from DashAI.back.types.value_types import Text -from tests.back.document_fixtures import create_document_notebook, image, text +from tests.back.document_fixtures import ( + create_document_notebook, + image, + text, + write_document, +) URL = "/api/v1/documents/from-notebook" @@ -118,3 +123,22 @@ def test_saving_waits_for_running_converters(client: TestClient): _add_converter(client, notebook_id, status=ConverterStatus.STARTED) response = client.post(URL, json={"name": _name(), "notebook_id": notebook_id}) assert response.status_code == 409, response.text + + +def test_a_notebook_without_its_working_copy_is_refused( + client: TestClient, tmp_path, monkeypatch +): + write_document(tmp_path / "document", ["not the notebook"]) + monkeypatch.chdir(tmp_path) + notebook_id = create_document_notebook(client, _name(), ["a"]) + with client.app.container["session_factory"]() as db: + db.get(Notebook, notebook_id).file_path = "" + db.commit() + documents_path = Path(client.app.container["config"]["DOCUMENTS_PATH"]) + before = set(documents_path.iterdir()) + + response = client.post(URL, json={"name": _name(), "notebook_id": notebook_id}) + + assert response.status_code == 422, response.text + assert response.json()["detail"] == "Notebook document is missing" + assert set(documents_path.iterdir()) == before From fdfe8f35fced3f69a3ae05202bb47eae6455d6c9 Mon Sep 17 00:00:00 2001 From: Irozuku Date: Thu, 3 Dec 2026 19:08:08 -0300 Subject: [PATCH 5/8] fix: refuse to copy a dataset without stored files --- DashAI/back/api/api_v1/endpoints/datasets.py | 15 +++++- tests/back/api/test_dataset_copy_api.py | 55 ++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 tests/back/api/test_dataset_copy_api.py diff --git a/DashAI/back/api/api_v1/endpoints/datasets.py b/DashAI/back/api/api_v1/endpoints/datasets.py index f293e3701..117e9982d 100644 --- a/DashAI/back/api/api_v1/endpoints/datasets.py +++ b/DashAI/back/api/api_v1/endpoints/datasets.py @@ -950,10 +950,18 @@ async def copy_dataset( ------- Dataset The newly created dataset. + + Raises + ------ + HTTPException + 404 for an unknown dataset; 422 when it is not finished or has no + stored files; 409 when the copy name is taken; 500 when the copy or + the database write fails. """ import shutil from DashAI.back.core.enums.status import DatasetStatus + from DashAI.back.core.stored_paths import copy_stored_tree, is_stored_directory dataset_id = dataset["dataset_id"] logger.debug(f"Copying dataset with ID {dataset_id}.") @@ -971,12 +979,17 @@ async def copy_dataset( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Original dataset is not in finished state", ) + if not is_stored_directory(original_dataset.file_path): + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Original dataset has no stored files", + ) # Create a new folder for the copied dataset new_name = f"{original_dataset.name}_copy" new_folder_path = config["DATASETS_PATH"] / new_name try: - shutil.copytree(original_dataset.file_path, new_folder_path) + copy_stored_tree(original_dataset.file_path, new_folder_path) except FileExistsError: raise HTTPException( status_code=status.HTTP_409_CONFLICT, diff --git a/tests/back/api/test_dataset_copy_api.py b/tests/back/api/test_dataset_copy_api.py new file mode 100644 index 000000000..bcfaa5d46 --- /dev/null +++ b/tests/back/api/test_dataset_copy_api.py @@ -0,0 +1,55 @@ +import uuid +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +from DashAI.back.core.enums.status import DatasetStatus +from DashAI.back.dependencies.database.models import Dataset + +URL = "/api/v1/dataset/copy" + + +def test_a_finished_dataset_is_copied_with_its_files( + client: TestClient, dataset_1: Dataset +) -> None: + response = client.post(URL, json={"dataset_id": dataset_1.id}) + + assert response.status_code == 201, response.text + copied = Path(response.json()["file_path"]) + assert copied.name == f"{dataset_1.name}_copy" + assert (copied / "dataset" / "data.arrow").is_file() + + +@pytest.mark.parametrize( + ("status", "stored", "detail"), + [ + (DatasetStatus.ERROR, "empty", "Original dataset is not in finished state"), + (DatasetStatus.FINISHED, "empty", "Original dataset has no stored files"), + (DatasetStatus.FINISHED, "missing", "Original dataset has no stored files"), + ], +) +def test_a_dataset_without_stored_files_is_not_copied( + client: TestClient, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + status: DatasetStatus, + stored: str, + detail: str, +) -> None: + (tmp_path / "pyproject.toml").write_text("[project]", encoding="utf-8") + monkeypatch.chdir(tmp_path) + file_path = {"empty": "", "missing": str(tmp_path / "gone")}[stored] + name = f"failed_{uuid.uuid4().hex[:8]}" + with client.app.container["session_factory"]() as db: + dataset = Dataset(name=name, file_path=file_path, status=status) + db.add(dataset) + db.commit() + dataset_id = dataset.id + + response = client.post(URL, json={"dataset_id": dataset_id}) + + assert response.status_code == 422, response.text + assert response.json()["detail"] == detail + datasets_path = Path(client.app.container["config"]["DATASETS_PATH"]) + assert not (datasets_path / f"{name}_copy").exists() From 67a6c267920345a42eb21b116f6e8ae4d39414fa Mon Sep 17 00:00:00 2001 From: Irozuku Date: Thu, 3 Dec 2026 19:09:10 -0300 Subject: [PATCH 6/8] fix: refuse to export a session whose dataset has no stored files --- DashAI/back/session_package/export.py | 30 +++++++++++++++----------- tests/back/api/test_session_package.py | 30 +++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 13 deletions(-) diff --git a/DashAI/back/session_package/export.py b/DashAI/back/session_package/export.py index da5625a81..ba4a300cc 100644 --- a/DashAI/back/session_package/export.py +++ b/DashAI/back/session_package/export.py @@ -10,12 +10,17 @@ import hashlib import json import re -import shutil import tempfile from datetime import datetime from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, Optional +from DashAI.back.core.stored_paths import ( + copy_stored_entry, + copy_stored_tree, + is_stored_directory, + is_stored_path, +) from DashAI.back.model_package.export import _zip_directory from DashAI.back.model_package.manifest import ( MANIFEST_ENTRY, @@ -164,7 +169,7 @@ def _finished(run) -> bool: def _has_model_file(run) -> bool: - return bool(run.run_path) and Path(run.run_path).exists() + return is_stored_path(run.run_path) def _forecasts_path(run) -> Optional[Path]: @@ -206,10 +211,7 @@ def _sha256(path: Path) -> str: def _copy(source: Path, target: Path) -> None: """Copy a file or a folder (HuggingFace models save folders).""" target.parent.mkdir(parents=True, exist_ok=True) - if source.is_dir(): - shutil.copytree(source, target) - else: - shutil.copy2(source, target) + copy_stored_entry(source, target) def _metric_row(metric) -> Dict[str, Any]: @@ -372,8 +374,8 @@ def build_session_package( SessionNotFoundError If the session does not exist. SessionNotExportableError - If no run is chosen, or a chosen run belongs to another session or is - still training. + If no run is chosen, a chosen run belongs to another session or is + still training, or the session's dataset has no stored files. """ from DashAI.back.dependencies.database.models import ( Dataset, @@ -402,7 +404,11 @@ def build_session_package( runs.append(run) dataset = db.get(Dataset, session.dataset_id) - dataset_dir = Path(dataset.file_path) / DATASET_ENTRY + dataset_dir = Path(dataset.file_path or "") / DATASET_ENTRY + if not is_stored_directory(dataset_dir): + raise SessionNotExportableError( + f"The dataset '{dataset.name}' of this session has no stored files." + ) artifacts_path = session.preprocessing_artifacts_path recipe_session = {field: getattr(session, field) for field in SESSION_FIELDS} # A step left without a session default runs with it, and the file @@ -465,9 +471,9 @@ def build_session_package( with tempfile.TemporaryDirectory(prefix="dashai-session-") as staging_dir: staging = Path(staging_dir) - shutil.copytree(dataset_dir, staging / DATASET_ENTRY) - if include_trained_models and artifacts_path and Path(artifacts_path).exists(): - shutil.copytree(artifacts_path, staging / PREPROCESSING_ENTRY) + copy_stored_tree(dataset_dir, staging / DATASET_ENTRY) + if include_trained_models and is_stored_directory(artifacts_path): + copy_stored_tree(artifacts_path, staging / PREPROCESSING_ENTRY) recipe_runs = [] for index, run in enumerate(exported_runs): diff --git a/tests/back/api/test_session_package.py b/tests/back/api/test_session_package.py index 9ff6a8456..1e717d536 100644 --- a/tests/back/api/test_session_package.py +++ b/tests/back/api/test_session_package.py @@ -10,7 +10,7 @@ import pytest from fastapi.testclient import TestClient -from DashAI.back.core.enums.status import RunStatus +from DashAI.back.core.enums.status import DatasetStatus, RunStatus from DashAI.back.dependencies.database.models import ( Dataset, Folder, @@ -45,6 +45,7 @@ add_metrics, fit_classifier_behind_preprocessing, fit_regressor, + new_regression_session, new_run, predicted_in_app, ) @@ -223,6 +224,33 @@ def test_a_missing_session_cannot_be_exported(client, tmp_path): _build(client, 999999, [1], tmp_path / "x.dashai") +def test_a_session_on_a_failed_dataset_cannot_be_exported( + client, tmp_path, monkeypatch +): + (tmp_path / "dataset").mkdir() + (tmp_path / "dataset" / "data.arrow").write_bytes(b"not the session dataset") + monkeypatch.chdir(tmp_path) + session_factory = client.app.container["session_factory"] + with session_factory() as db: + dataset = Dataset( + name="session-package-failed-dataset", + file_path="", + status=DatasetStatus.ERROR, + ) + db.add(dataset) + db.commit() + db.refresh(dataset) + session_id = new_regression_session( + client, dataset, "session-package-failed-dataset-session" + ) + run_id = new_run(session_factory, session_id, "LinearRegression", {}) + + with pytest.raises(SessionNotExportableError): + _build(client, session_id, [run_id], tmp_path / "failed.dashai") + + assert not (tmp_path / "failed.dashai").exists() + + def test_the_preview_lists_runs_and_sizes(client, classifier): preview = export_preview( classifier["session_id"], client.app.container["session_factory"] From f31added6bc124d86830167c93ffa4dffe903f9d Mon Sep 17 00:00:00 2001 From: Irozuku Date: Thu, 3 Dec 2026 19:10:26 -0300 Subject: [PATCH 7/8] fix: refuse to export a run whose model file is gone --- DashAI/back/model_package/export.py | 9 +++------ tests/back/api/test_model_package.py | 10 ++++++++-- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/DashAI/back/model_package/export.py b/DashAI/back/model_package/export.py index 30fc30689..c47a5d065 100644 --- a/DashAI/back/model_package/export.py +++ b/DashAI/back/model_package/export.py @@ -9,6 +9,7 @@ from pathlib import Path from typing import TYPE_CHECKING, Any, Dict +from DashAI.back.core.stored_paths import copy_stored_entry, is_stored_path from DashAI.back.model_package.manifest import ( FORMAT_VERSION, KIND_MODEL, @@ -105,7 +106,7 @@ def build_package( run = db.get(Run, run_id) if run is None: raise RunNotFoundError(f"Run {run_id} does not exist.") - if run.status != RunStatus.FINISHED or not run.run_path: + if run.status != RunStatus.FINISHED or not is_stored_path(run.run_path): raise RunNotExportableError( "Only a finished run with a saved model can be exported." ) @@ -175,11 +176,7 @@ def build_package( with tempfile.TemporaryDirectory(prefix="dashai-export-") as staging_dir: staging = Path(staging_dir) - # A model saves either one file or a folder (HuggingFace models). - if run_path.is_dir(): - shutil.copytree(run_path, staging / MODEL_ENTRY) - else: - shutil.copy2(run_path, staging / MODEL_ENTRY) + copy_stored_entry(run_path, staging / MODEL_ENTRY) if preprocessor_file is not None: (staging / PREPROCESSOR_ENTRY).parent.mkdir(parents=True) shutil.copy2(preprocessor_file, staging / PREPROCESSOR_ENTRY) diff --git a/tests/back/api/test_model_package.py b/tests/back/api/test_model_package.py index f384738c1..97b521ad3 100644 --- a/tests/back/api/test_model_package.py +++ b/tests/back/api/test_model_package.py @@ -100,12 +100,15 @@ def test_a_package_carries_the_model_preprocessor_and_an_empty_schema( assert "Iris-setosa" in types[CLASS_COLUMN]["categories"] -def test_an_unfinished_run_cannot_be_exported(client, dataset_1, tmp_path): +@pytest.mark.parametrize("model_file", ["never_saved", "gone"]) +def test_a_run_without_its_saved_model_cannot_be_exported( + client, dataset_1, tmp_path, model_file +): session_factory = client.app.container["session_factory"] with session_factory() as db: session = ModelSession( dataset_id=dataset_1.id, - name="model-package-unfinished-session", + name=f"model-package-{model_file}-session", task_name="TabularClassificationTask", column_roles=xy_roles(RAW_INPUT_COLUMNS, [CLASS_COLUMN]), train_metrics=[], @@ -125,6 +128,9 @@ def test_an_unfinished_run_cannot_be_exported(client, dataset_1, tmp_path): name="Unfinished", goal_metric="Accuracy", ) + if model_file == "gone": + run.run_path = str(tmp_path / "gone" / "model") + run.set_status_as_finished() db.add(run) db.commit() run_id = run.id From fff2af80d55832fb92579aede9aefbc51975440d Mon Sep 17 00:00:00 2001 From: Irozuku Date: Thu, 3 Dec 2026 19:10:54 -0300 Subject: [PATCH 8/8] fix: copy generative session documents only from stored folders --- DashAI/back/generative_package/export.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/DashAI/back/generative_package/export.py b/DashAI/back/generative_package/export.py index f002594c0..45bcdbeac 100644 --- a/DashAI/back/generative_package/export.py +++ b/DashAI/back/generative_package/export.py @@ -28,6 +28,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional from DashAI.back.core.component_validation import find_component_refs +from DashAI.back.core.stored_paths import copy_stored_tree, is_stored_directory from DashAI.back.model_package.export import _zip_directory from DashAI.back.model_package.manifest import ( MANIFEST_ENTRY, @@ -125,8 +126,7 @@ def _exportable_documents(session) -> List[Any]: document for document in session.documents if document.status == DocumentStatus.FINISHED - and document.file_path - and Path(document.file_path).is_dir() + and is_stored_directory(document.file_path) ] @@ -221,7 +221,7 @@ def _documents(session, staging: Path) -> List[Dict[str, Any]]: entries = [] for index, document in enumerate(_exportable_documents(session)): entry = f"{DOCUMENTS_ENTRY}/{index}" - shutil.copytree(document.file_path, staging / entry) + copy_stored_tree(document.file_path, staging / entry) entries.append( { "ref": document.id,