Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: edit_file and Rewind write through an open chat-folder descriptor on POSIX (#17389)
Daniel Han43625c944b33
diff --git a/studio/backend/core/inference/file_history.py b/studio/backend/core/inference/file_history.pyindex 46b2a6be194..23564bc5014 100644--- a/studio/backend/core/inference/file_history.py+++ b/studio/backend/core/inference/file_history.py@@ -728,40 +728,100 @@ def _require_plain_dir(raise OSError(f"{name} is no longer a plain folder")-def _safe_write(workdir: str, rel: str, data: bytes, mode: Optional[int]) -> None:- path = _resolve_inside(workdir, rel, create_dirs = True)- tmp = os.path.join(os.path.dirname(path), f".unsloth-rewind-{uuid.uuid4().hex}.tmp")- flags = (- os.O_WRONLY- | os.O_CREAT- | os.O_EXCL- | getattr(os, "O_NOFOLLOW", 0)- | getattr(os, "O_BINARY", 0)- )- fd = os.open(tmp, flags, 0o600)+# POSIX walks the parents as open folders, so a parent swapped for a link between steps fails+# instead of carrying the write outside. Windows has no dir_fd and keeps the lstat walk. os.rename+# stands in for os.replace, which takes the same dir_fd arguments but is not listed.+DIR_FD_WALK = (+ {os.open, os.mkdir, os.stat, os.chmod, os.rename, os.unlink} <= os.supports_dir_fd+ and hasattr(os, "O_DIRECTORY")+ and hasattr(os, "O_NOFOLLOW")+)+++def open_dir_below(root: str, parts: "Iterable[str]", create_dirs: bool) -> int:+ """Descriptor of ``root/parts...``, never following a link at any step; the caller closes it."""+ flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW+ fd = os.open(root, flags)try:- with os.fdopen(fd, "wb") as fh:- fh.write(data)- if mode is not None:- os.chmod(tmp, mode)- if os.path.isfile(path):- from core.library import replace_file- replace_file(tmp, path) # carries the Library's name and folder over to the new inode- else:- os.replace(tmp, path) # replaces a link at the name, never writes through it+ for part in parts:+ if create_dirs:+ try:+ os.mkdir(part, dir_fd = fd)+ except FileExistsError:+ pass+ child = os.open(part, flags, dir_fd = fd)+ os.close(fd)+ fd = childexcept BaseException:- try:- os.unlink(tmp)- except OSError:- pass+ os.close(fd)raise+ return fd+++def _open_parent(workdir: str, rel: str, create_dirs: bool) -> "tuple[Optional[int], str, str]":+ """(folder fd or None, name to use with it, full path) for *rel*."""+ if not DIR_FD_WALK:+ path = _resolve_inside(workdir, rel, create_dirs)+ return None, path, path+ parts = rel.split("/")+ if os.path.isabs(rel) or any(part in ("", ".", "..") for part in parts):+ raise OSError("not a path inside the chat's folder")+ return (+ open_dir_below(workdir, parts[:-1], create_dirs),+ parts[-1],+ os.path.join(workdir, *parts),+ )+++def _safe_write(workdir: str, rel: str, data: bytes, mode: Optional[int]) -> None:+ dir_fd, leaf, path = _open_parent(workdir, rel, create_dirs = True)+ try:+ tmp = os.path.join(os.path.dirname(leaf), f".unsloth-rewind-{uuid.uuid4().hex}.tmp")+ flags = (+ os.O_WRONLY+ | os.O_CREAT+ | os.O_EXCL+ | getattr(os, "O_NOFOLLOW", 0)+ | getattr(os, "O_BINARY", 0)+ )+ fd = os.open(tmp, flags, 0o600, dir_fd = dir_fd)+ try:+ with os.fdopen(fd, "wb") as fh:+ fh.write(data)+ if mode is not None:+ os.chmod(tmp, mode, dir_fd = dir_fd)+ try:+ is_file = stat_mod.S_ISREG(os.stat(leaf, dir_fd = dir_fd).st_mode)+ except OSError:+ is_file = False+ if is_file:+ from core.library import replace_file++ # carries the Library's name and folder over to the new inode+ replace_file(tmp, path, dir_fd = dir_fd)+ else:+ # replaces a link at the name, never writes through it+ os.replace(tmp, leaf, src_dir_fd = dir_fd, dst_dir_fd = dir_fd)+ except BaseException:+ try:+ os.unlink(tmp, dir_fd = dir_fd)+ except OSError:+ pass+ raise+ finally:+ if dir_fd is not None:+ os.close(dir_fd)def _safe_unlink(workdir: str, rel: str) -> None:- path = _resolve_inside(workdir, rel, create_dirs = False)- if not stat_mod.S_ISREG(os.lstat(path).st_mode):- raise OSError("no longer a regular file")- os.unlink(path)+ dir_fd, leaf, _ = _open_parent(workdir, rel, create_dirs = False)+ try:+ if not stat_mod.S_ISREG(os.stat(leaf, dir_fd = dir_fd, follow_symlinks = False).st_mode):+ raise OSError("no longer a regular file")+ os.unlink(leaf, dir_fd = dir_fd)+ finally:+ if dir_fd is not None:+ os.close(dir_fd)_stores: dict = {}diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex ef48f97e849..c56a19d4222 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -11373,18 +11373,23 @@ def _edit_file_write() -> str:"""Atomic rename from a temp file; will not revert a file another chat rewrote since expect; containment rechecked before the rename catches a symlink swap."""payload = (bom + text.replace("\n", newline)).encode("utf-8")- directory = os.path.dirname(path) or "."try:- os.makedirs(directory, exist_ok = True)+ dir_fd, leaf = _edit_file_parent(path, workdir, create_dirs = True)except OSError as exc:return f"Error: cannot create directory for '{os.path.basename(path)}': {exc}"tmp = ""try:- fd, tmp = tempfile.mkstemp(dir = directory, prefix = ".unsloth_edit_")+ if dir_fd is None:+ fd, tmp = tempfile.mkstemp(dir = os.path.dirname(path) or ".", prefix = ".unsloth_edit_")+ else:+ tmp = f".unsloth_edit_{uuid.uuid4().hex}"+ fd = os.open(+ tmp, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600, dir_fd = dir_fd+ )with os.fdopen(fd, "wb") as fh:fh.write(payload)try:- shutil.copymode(path, tmp)+ os.chmod(tmp, stat.S_IMODE(os.stat(leaf, dir_fd = dir_fd).st_mode), dir_fd = dir_fd)except OSError:pass # new file, or a mode we cannot read; the default is fineif workdir is not None and _is_outside_workdir(path, workdir):@@ -11394,7 +11399,9 @@ def _edit_file_write()if expect is not None:try:- with open(path, "rb") as fh:+ with os.fdopen(+ os.open(leaf, os.O_RDONLY | getattr(os, "O_BINARY", 0), dir_fd = dir_fd), "rb"+ ) as fh:current = fh.read(len(expect) + 1)except OSError:current = None@@ -11406,14 +11413,16 @@ def _edit_file_write()from core import library- library.replace_file(tmp, path)+ library.replace_file(tmp, path, dir_fd = dir_fd)tmp = ""except OSError as exc:return f"Error: cannot write '{os.path.basename(path)}': {exc}"finally:if tmp:with contextlib.suppress(OSError):- os.remove(tmp)+ os.remove(tmp, dir_fd = dir_fd)+ if dir_fd is not None:+ os.close(dir_fd)return ""@@ -11552,6 +11561,23 @@ def _edit_file_created_sentinel(target: str, workdir: str) -> str:return "\n__FILES__:" + json.dumps([{"name": "/".join(parts), "size": size}])+def _edit_file_parent(+ target: str, workdir: "str | None", create_dirs: bool+) -> "tuple[int | None, str]":+ """(folder fd or None, name to use with it). Confined POSIX writes open every parent below the+ workdir without following links, so a folder swapped for a link mid-call fails instead of+ carrying the write outside; unconfined calls and Windows keep the path."""+ if workdir is None or not file_history.DIR_FD_WALK:+ if create_dirs:+ os.makedirs(os.path.dirname(target) or ".", exist_ok = True)+ return None, target+ root = os.path.realpath(workdir)+ parts = os.path.relpath(target, root).split(os.sep)+ if parts[0] == os.pardir:+ raise OSError("not inside the working directory")+ return file_history.open_dir_below(root, parts[:-1], create_dirs), parts[-1]++def _edit_file_create(target: str,new: str,@@ -11562,37 +11588,40 @@ def _edit_file_create("""Creates with O_EXCL, not a lexists check, so two chats cannot drop each other's file; never clobbers, and a zero-byte target stays writable on purpose."""payload = (new.replace("\n", newline)).encode("utf-8")if not os.path.lexists(target):- directory = os.path.dirname(target) or "."try:- os.makedirs(directory, exist_ok = True)+ dir_fd, leaf = _edit_file_parent(target, workdir, create_dirs = True)except OSError as exc:return f"Error: cannot create directory for '{name}': {exc}"- if workdir is not None and _is_outside_workdir(target, workdir):- return (- f"Error: '{name}' moved outside the working directory while the "- "edit was being prepared; nothing was written."- )- flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY- # Never follow a symlink planted at the final component in the meantime.- flags |= getattr(os, "O_NOFOLLOW", 0)- try:- fd = os.open(target, flags, 0o666)- except FileExistsError:- return (- f"Error: '{name}' was created by something else while this call "- "was preparing it; nothing was written."- )- except OSError as exc:- return f"Error: cannot write '{name}': {exc}"try:- with os.fdopen(fd, "wb") as fh:- fh.write(payload)- except OSError as exc:- # A partial write after ENOSPC cannot be retried (empty old_string refuses non-empty), so- # remove the inode.- with contextlib.suppress(OSError):- os.remove(target)- return f"Error: cannot write '{name}': {exc}"+ if workdir is not None and _is_outside_workdir(target, workdir):+ return (+ f"Error: '{name}' moved outside the working directory while the "+ "edit was being prepared; nothing was written."+ )+ flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY+ # Never follow a symlink planted at the final component in the meantime.+ flags |= getattr(os, "O_NOFOLLOW", 0)+ try:+ fd = os.open(leaf, flags, 0o666, dir_fd = dir_fd)+ except FileExistsError:+ return (+ f"Error: '{name}' was created by something else while this call "+ "was preparing it; nothing was written."+ )+ except OSError as exc:+ return f"Error: cannot write '{name}': {exc}"+ try:+ with os.fdopen(fd, "wb") as fh:+ fh.write(payload)+ except OSError as exc:+ # A partial write after ENOSPC cannot be retried (empty old_string refuses non-empty), so+ # remove the inode.+ with contextlib.suppress(OSError):+ os.remove(leaf, dir_fd = dir_fd)+ return f"Error: cannot write '{name}': {exc}"+ finally:+ if dir_fd is not None:+ os.close(dir_fd)return f"Created {name} ({new.count(chr(10)) + 1 if new else 0} lines)"try:st = os.stat(target)diff --git a/studio/backend/core/library.py b/studio/backend/core/library.pyindex 073127b1944..8e76b049749 100644--- a/studio/backend/core/library.py+++ b/studio/backend/core/library.py@@ -1271,13 +1271,19 @@ def overlay_write():yield-def replace_file(tmp: str, path: str) -> None:+def replace_file(+ tmp: str,+ path: str,+ dir_fd: "int | None" = None,+) -> None:"""``os.replace(tmp, path)``, carrying the overlay row of the file it replaces over to the new- inode, which the listing would otherwise drop as a different file."""+ inode, which the listing would otherwise drop as a different file. With ``dir_fd``, ``tmp`` and+ the basename of ``path`` are names in that open folder."""+ leaf = path if dir_fd is None else os.path.basename(path)with _replace_lock:- before = os.stat(path)- staged = os.stat(tmp)- os.replace(tmp, path)+ before = os.stat(leaf, dir_fd = dir_fd)+ staged = os.stat(tmp, dir_fd = dir_fd)+ os.replace(tmp, leaf, src_dir_fd = dir_fd, dst_dir_fd = dir_fd)_carry_overlay(path, before, staged)diff --git a/studio/backend/tests/test_edit_file_tool.py b/studio/backend/tests/test_edit_file_tool.pyindex a0da919cea1..199e15676b2 100644--- a/studio/backend/tests/test_edit_file_tool.py+++ b/studio/backend/tests/test_edit_file_tool.py@@ -181,6 +181,37 @@ class TestPathContainment:assert result.startswith("Error:")assert outside.read_text() == "secret\n"+ @pytest.mark.skipif(os.name != "posix", reason = "uses a symlink")+ @pytest.mark.parametrize("existing", [False, True])+ def test_a_parent_swapped_for_a_link_after_the_check_is_not_written_through(+ self, workdir, tmp_path_factory, monkeypatch, existing+ ):+ # A sandboxed process can flip a folder to a link between the containment recheck and the open.+ outside = tmp_path_factory.mktemp("outside")+ (workdir / "a").mkdir()+ if existing:+ (workdir / "a" / "f.txt").write_text("old\n")+ (outside / "f.txt").write_text("old\n")+ check = tools._is_outside_workdir++ def check_then_swap(path, root = None):+ result = check(path, root)+ if sys._getframe(1).f_code.co_name in ("_edit_file_create", "_edit_file_write"):+ monkeypatch.setattr(tools, "_is_outside_workdir", check)+ (workdir / "a").rename(workdir / "real")+ os.symlink(outside, workdir / "a")+ return result++ monkeypatch.setattr(tools, "_is_outside_workdir", check_then_swap)+ if existing:+ _edit(path = "a/f.txt", old_string = "old", new_string = "new")+ assert (outside / "f.txt").read_text() == "old\n"+ else:+ _edit(path = "a/f.txt", old_string = "", new_string = "new\n")+ assert not (outside / "f.txt").exists()+ assert os.listdir(outside) == (["f.txt"] if existing else [])+ assert (workdir / "real" / "f.txt").read_text() == "new\n"+def test_a_code_interpreter_habit_path_keeps_its_suffix(self, workdir):result = _edit(path = "/mnt/data/out.txt", old_string = "", new_string = "hi\n")assert not result.startswith("Error:")diff --git a/studio/backend/tests/test_file_history.py b/studio/backend/tests/test_file_history.pyindex e1458c83936..3d06afbe989 100644--- a/studio/backend/tests/test_file_history.py+++ b/studio/backend/tests/test_file_history.py@@ -292,6 +292,39 @@ def test_a_folder_swapped_for_a_link_is_never_written_through(chat, tmp_path):assert report.errors and (elsewhere / "a.txt").read_text(encoding = "utf-8") == "2\n"[email protected](os.name != "posix", reason = "uses a symlink")+def test_a_parent_swapped_for_a_link_mid_write_is_not_written_through(tmp_path, monkeypatch):+ # Swapped after the parents were checked and before the temp file opens.+ workdir = tmp_path / "sandbox"+ (workdir / "a").mkdir(parents = True)+ outside = tmp_path / "outside"+ outside.mkdir()+ uuid4 = file_history.uuid.uuid4++ def swap_then_uuid():+ monkeypatch.setattr(file_history.uuid, "uuid4", uuid4)+ (workdir / "a").rename(workdir / "real")+ os.symlink(outside, workdir / "a")+ return uuid4()++ monkeypatch.setattr(file_history.uuid, "uuid4", swap_then_uuid)+ try:+ file_history._safe_write(str(workdir), "a/f.txt", b"restored\n", 0o644)+ except OSError:+ pass+ assert os.listdir(outside) == []++[email protected](os.name != "posix", reason = "no dir_fd on Windows")+def test_the_folder_walk_refuses_a_link_at_any_step(tmp_path):+ (tmp_path / "real").mkdir()+ os.symlink(tmp_path / "real", tmp_path / "link")+ with pytest.raises(OSError):+ file_history.open_dir_below(str(tmp_path), ["link"], create_dirs = False)+ with pytest.raises(OSError):+ file_history.open_dir_below(str(tmp_path / "link"), [], create_dirs = False)++def test_deleting_a_chat_that_only_read_files_releases_its_baseline(chat):workdir, history = chat(workdir / "data.csv").write_text("a,b\n", encoding = "utf-8")diff --git a/studio/backend/tests/test_library_routes.py b/studio/backend/tests/test_library_routes.pyindex c72687330e3..fcada793ac5 100644--- a/studio/backend/tests/test_library_routes.py+++ b/studio/backend/tests/test_library_routes.py@@ -533,12 +533,12 @@ def test_a_path_made_again_right_after_an_edit_starts_fresh(client, signed_in, mos.link(path, os.path.join(directory, ".held"))replace = os.replace- def replace_then_recreate(src, dst):- replace(src, dst)+ def replace_then_recreate(src, dst, **dir_fds):+ replace(src, dst, **dir_fds)if os.path.basename(dst) == "report.txt":- other = dst + ".other"+ other = path + ".other"Path(other).write_bytes(b"someone else\n")- replace(other, dst)+ replace(other, path)monkeypatch.setattr(os, "replace", replace_then_recreate)execute_tool(