From 7643ca04521f7e8d305aeeae2057a0f8458e0c73 Mon Sep 17 00:00:00 2001 From: Hyeonsang Cho Date: Wed, 25 Nov 2026 21:39:36 +0900 Subject: [PATCH] fix(skills): make skill_manage share the routes' custom-skill mutation lock (#8568) * fix(skills): make skill_manage share the routes' custom-skill mutation lock The skill routes hold a per-owner lock (a process lock plus a sidecar flock) around read -> write -> history. skill_manage held only its own process-local per-skill lock, so a tool edit and a route edit of the same skill could interleave, in one Gateway process or across several. One overwrote the other while recording a stale prev_content, and the overwritten revision dropped out of the history chain rollback walks. Move the lock into deerflow.skills.mutation_lock and use it from both. The tool takes it after its scans, so a slow model scan does not queue the owner's other mutations, and re-reads under it what the scans assumed: - patch is refused when SKILL.md changed since the patch was derived; - edit and write_file record the content they actually overwrite; - write_file does not recreate a skill deleted meanwhile; - create does not overwrite a skill created meanwhile. * chore(skills): keep the type: ignore on the Windows fcntl fallback The routes carried it before the lock moved, and the other fcntl fallbacks, including deerflow/skills/projection.py, still do. --- backend/app/gateway/routers/skills.py | 89 +-------- backend/docs/API.md | 6 + .../harness/deerflow/skills/AGENTS.md | 3 + .../harness/deerflow/skills/mutation_lock.py | 101 +++++++++++ .../deerflow/tools/skill_manage_tool.py | 85 +++++++-- backend/tests/test_skill_manage_tool.py | 171 +++++++++++++++++- .../tests/test_skills_cache_shared_reset.py | 18 +- .../tests/test_skills_custom_multiprocess.py | 69 +++++-- backend/tests/test_skills_custom_router.py | 6 +- 9 files changed, 419 insertions(+), 129 deletions(-) create mode 100644 backend/packages/harness/deerflow/skills/mutation_lock.py diff --git a/backend/app/gateway/routers/skills.py b/backend/app/gateway/routers/skills.py index fee6e510b5..1ab2a5943b 100644 --- a/backend/app/gateway/routers/skills.py +++ b/backend/app/gateway/routers/skills.py @@ -2,9 +2,8 @@ import asyncio import json import logging import tempfile -import threading -from collections.abc import AsyncGenerator, Callable, Coroutine, Iterator -from contextlib import contextmanager, suppress +from collections.abc import AsyncGenerator, Callable, Coroutine +from contextlib import suppress from pathlib import Path from typing import Any, BinaryIO, Literal @@ -45,6 +44,7 @@ from deerflow.skills import Skill from deerflow.skills.diagnostics import SkillLoadDiagnostic from deerflow.skills.export import SkillExportError, build_skill_export, export_manifest from deerflow.skills.installer import SkillAlreadyExistsError, SkillSecurityScanError +from deerflow.skills.mutation_lock import custom_skill_mutation from deerflow.skills.security_scanner import scan_skill_content from deerflow.skills.security_static_scanner import ( StaticFinding, @@ -60,12 +60,6 @@ from deerflow.utils.thread_id import ThreadId logger = logging.getLogger(__name__) -try: - import fcntl -except ImportError: # pragma: no cover - Windows - fcntl = None # type: ignore[assignment] - import msvcrt - router = APIRouter(prefix="/api", tags=["skills"]) _ADMIN_REQUIRED_DETAIL = "Admin privileges required to manage skills." @@ -183,75 +177,8 @@ class SkillRollbackRequest(BaseModel): # mutation's steps inside one worker-thread function does not make them a # critical section — two requests can both be inside their own workers — so # the cooperating mutation paths share a lock around the whole sequence. -# -# The lock is scoped to the owning user's storage: the -# critical section includes write_custom_skill's projection rebuild, which -# copies that user's whole skill tree (including a large linked package) and -# waits on the user's projection lock. A process-wide lock would therefore -# queue every other user's edit, rollback, and delete behind one user's slow -# filesystem work, even though their skill trees, histories, and projection -# roots are disjoint. Keying on the resolved root — not the user_id string, -# and not one lock per storage instance — keeps a single lock per user when a -# hot-reloaded config or a later request builds a fresh storage object. -_custom_skill_mutation_locks: dict[str, threading.Lock] = {} -_custom_skill_mutation_locks_guard = threading.Lock() - - -def _custom_skill_mutation_lock(storage: SkillStorage) -> threading.Lock: - """Return the process-local part of the owning user's mutation lock.""" - scope = _custom_skill_mutation_scope(storage) - with _custom_skill_mutation_locks_guard: - return _custom_skill_mutation_locks.setdefault(scope, threading.Lock()) - - -def _custom_skill_mutation_scope(storage: SkillStorage) -> str: - """The storage scope whose custom-skill mutations must serialize together. - - User-scoped storage reports the canonical root its mutations touch, so two - users never share a lock while two storage objects for one user always do. - Legacy local storage uses its global custom root. Non-filesystem test - doubles have one process-local scope. - """ - get_user_custom_root = getattr(storage, "get_user_custom_root", None) - if callable(get_user_custom_root): - return str(Path(get_user_custom_root()).resolve()) - get_skills_root_path = getattr(storage, "get_skills_root_path", None) - if callable(get_skills_root_path): - return str((Path(get_skills_root_path()) / SkillCategory.CUSTOM.value).resolve()) - return "global" - - -@contextmanager -def _custom_skill_mutation(storage: SkillStorage) -> Iterator[None]: - """Hold read → write → history across threads and peer Gateway processes. - - Use a stable sidecar outside the skill tree, distinct from projection's - lock: write/delete acquire the projection lock while this one is held. - Acquiring that same file lock twice would deadlock on POSIX. Both locks - are acquired and released in the drained mutation worker, off the loop. - """ - with _custom_skill_mutation_lock(storage): - scope = _custom_skill_mutation_scope(storage) - if scope == "global": - yield - return - root = Path(scope) - lock_path = root.parent / f".{root.name}.mutation.lock" - lock_path.parent.mkdir(parents=True, exist_ok=True) - with lock_path.open("a", encoding="utf-8") as lock_file: - if fcntl is not None: - fcntl.flock(lock_file, fcntl.LOCK_EX) - else: # pragma: no cover - Windows - lock_file.seek(0) - msvcrt.locking(lock_file.fileno(), msvcrt.LK_LOCK, 1) - try: - yield - finally: - if fcntl is not None: - fcntl.flock(lock_file, fcntl.LOCK_UN) - else: # pragma: no cover - Windows - lock_file.seek(0) - msvcrt.locking(lock_file.fileno(), msvcrt.LK_UNLCK, 1) +# That lock is deerflow.skills.mutation_lock.custom_skill_mutation, which the +# agent's skill_manage tool holds as well. def _skill_to_response(skill: Skill) -> SkillResponse: @@ -812,7 +739,7 @@ async def update_custom_skill(skill_name: str, body: CustomSkillUpdateRequest, r # what this mutation actually overwrites, or the overwritten # revision silently drops out of the history chain and becomes # unreachable by rollback. - with _custom_skill_mutation(storage): + with custom_skill_mutation(storage): prev_content = storage.read_custom_skill(skill_name) storage.write_custom_skill(skill_name, SKILL_MD_FILE, body.content) storage.append_history( @@ -865,7 +792,7 @@ async def delete_custom_skill(skill_name: str, request: Request, config: AppConf # joins the owning user's mutation lock so it cannot interleave with # a concurrent edit or rollback's read → write → append sequence. def _delete_and_record() -> None: - with _custom_skill_mutation(storage): + with custom_skill_mutation(storage): storage.delete_custom_skill( skill_name, history_meta={ @@ -988,7 +915,7 @@ async def rollback_custom_skill(skill_name: str, body: SkillRollbackRequest, req # path): the recorded prev_content must be what this rollback # actually overwrites, which requires that no concurrent mutation # can land between the predecessor read and the write. - with _custom_skill_mutation(storage): + with custom_skill_mutation(storage): current_content = _read_current_content() storage.write_custom_skill(skill_name, SKILL_MD_FILE, target_content) storage.append_history( diff --git a/backend/docs/API.md b/backend/docs/API.md index ae9aa59fc3..eb0445122f 100644 --- a/backend/docs/API.md +++ b/backend/docs/API.md @@ -1331,6 +1331,12 @@ GET /api/skills/custom/{skill_name}/history An invalid skill name returns `400`; a skill with neither a `SKILL.md` nor recorded history returns `404`. +Each entry's `prev_content` is the content that change replaced. Edits, +rollbacks and deletions through these routes and the agent's `skill_manage` tool +take one lock per user, also across Gateway processes that share the home +volume, so they cannot interleave. An agent patch is refused, and nothing is +written, when `SKILL.md` changed while the patch was being scanned. + #### Rollback Custom Skill Restore a custom skill's `SKILL.md` from a history entry. The restored content is diff --git a/backend/packages/harness/deerflow/skills/AGENTS.md b/backend/packages/harness/deerflow/skills/AGENTS.md index ac63fc8d12..ae38d9f99a 100644 --- a/backend/packages/harness/deerflow/skills/AGENTS.md +++ b/backend/packages/harness/deerflow/skills/AGENTS.md @@ -50,6 +50,9 @@ their credentials and enabled state stay per user. - **Projection readers and mutation writers share the owner lock.** Export also captures its bytes under that lock and re-checks them. A read-only export does not rebuild projections. +- **Custom-skill read → write → history runs under `custom_skill_mutation`.** The + skill routes and `skill_manage` share it across processes. It is per owner, so + take it after the scans and re-read under it what a scan assumed. - **A skill name is a directory name on every host.** Creation and archive install reject Windows reserved device names on all platforms. Reads and deletes stay permissive, so that skills stored by an older release can still be removed. diff --git a/backend/packages/harness/deerflow/skills/mutation_lock.py b/backend/packages/harness/deerflow/skills/mutation_lock.py new file mode 100644 index 0000000000..ec8ffb1004 --- /dev/null +++ b/backend/packages/harness/deerflow/skills/mutation_lock.py @@ -0,0 +1,101 @@ +"""The lock every custom-skill mutation holds around read → write → history. + +A mutation reads the content it replaces, writes the new content and appends a +history record that names both. Two mutations of one owner must not interleave +those steps, or one overwrites the other while recording a stale predecessor, +and the overwritten revision drops out of the history chain that rollback +walks. The Gateway skill routes and the agent's ``skill_manage`` tool both +mutate custom skills, so they hold this one lock, in-process and across +Gateway processes that share the home volume. + +The lock is scoped to the owning user's storage: the critical section includes +``write_custom_skill``'s projection rebuild, which copies that user's whole +skill tree (including a large linked package) and waits on the user's +projection lock. A process-wide lock would queue every other user's mutation +behind one user's slow filesystem work, even though their skill trees, +histories and projection roots are disjoint. Keying on the resolved root, not +the user_id string and not one lock per storage instance, keeps a single lock +per user when a hot-reloaded config or a later request builds a fresh storage +object. +""" + +from __future__ import annotations + +import threading +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path + +from deerflow.skills.storage.skill_storage import SkillStorage +from deerflow.skills.types import SkillCategory + +try: + import fcntl +except ImportError: # pragma: no cover - Windows + fcntl = None # type: ignore[assignment] + import msvcrt + +_locks: dict[str, threading.Lock] = {} +_locks_guard = threading.Lock() + + +def custom_skill_mutation_lock(storage: SkillStorage) -> threading.Lock: + """Return the process-local part of the owning user's mutation lock.""" + scope = _mutation_scope(storage) + with _locks_guard: + return _locks.setdefault(scope, threading.Lock()) + + +def _mutation_scope(storage: SkillStorage) -> str: + """The storage scope whose custom-skill mutations must serialize together. + + User-scoped storage reports the canonical root its mutations touch, so two + users never share a lock while two storage objects for one user always do. + Legacy local storage uses its global custom root. Non-filesystem test + doubles have one process-local scope. + """ + get_user_custom_root = getattr(storage, "get_user_custom_root", None) + if callable(get_user_custom_root): + return str(Path(get_user_custom_root()).resolve()) + get_skills_root_path = getattr(storage, "get_skills_root_path", None) + if callable(get_skills_root_path): + return str((Path(get_skills_root_path()) / SkillCategory.CUSTOM.value).resolve()) + return "global" + + +@contextmanager +def custom_skill_mutation(storage: SkillStorage) -> Iterator[None]: + """Hold the owner's mutation lock across threads and peer Gateway processes. + + Blocking: take it in a worker thread, and run the whole read → write → + history sequence in that same worker. Hold it only for that sequence, not + across a security scan: it queues every other mutation of the owner's + skills. Whatever a scan assumed about the stored skill has to be re-read + under the lock. + + Use a stable sidecar outside the skill tree, distinct from projection's + lock: write/delete acquire the projection lock while this one is held. + Acquiring that same file lock twice would deadlock on POSIX. + """ + with custom_skill_mutation_lock(storage): + scope = _mutation_scope(storage) + if scope == "global": + yield + return + root = Path(scope) + lock_path = root.parent / f".{root.name}.mutation.lock" + lock_path.parent.mkdir(parents=True, exist_ok=True) + with lock_path.open("a", encoding="utf-8") as lock_file: + if fcntl is not None: + fcntl.flock(lock_file, fcntl.LOCK_EX) + else: # pragma: no cover - Windows + lock_file.seek(0) + msvcrt.locking(lock_file.fileno(), msvcrt.LK_LOCK, 1) + try: + yield + finally: + if fcntl is not None: + fcntl.flock(lock_file, fcntl.LOCK_UN) + else: # pragma: no cover - Windows + lock_file.seek(0) + msvcrt.locking(lock_file.fileno(), msvcrt.LK_UNLCK, 1) diff --git a/backend/packages/harness/deerflow/tools/skill_manage_tool.py b/backend/packages/harness/deerflow/tools/skill_manage_tool.py index c43ab681cd..aa0eca5bb2 100644 --- a/backend/packages/harness/deerflow/tools/skill_manage_tool.py +++ b/backend/packages/harness/deerflow/tools/skill_manage_tool.py @@ -19,6 +19,7 @@ from langchain.tools import tool from deerflow.agents.lead_agent.prompt import SkillCacheResetPublishError, publish_skills_cache_reset, refresh_user_skills_system_prompt_cache_async from deerflow.runtime.user_context import resolve_runtime_user_id +from deerflow.skills.mutation_lock import custom_skill_mutation from deerflow.skills.package_files import is_code_file from deerflow.skills.security_scanner import scan_skill_content from deerflow.skills.security_static_scanner import ( @@ -182,9 +183,26 @@ async def _to_thread(func, /, *args, **kwargs): return await asyncio.to_thread(func, *args, **kwargs) -async def _write_and_record(skill_storage: SkillStorage, name: str, relative_path: str, content: str, record: dict[str, Any]) -> None: - await _to_thread(skill_storage.write_custom_skill, name, relative_path, content) - await _to_thread(skill_storage.append_history, name, record) +async def _locked_mutation(skill_storage: SkillStorage, mutate: Callable[[], None]) -> None: + """Run ``mutate`` in one worker thread under the owner's custom-skill mutation lock. + + The Gateway skill routes hold the same lock around their read → write → + history sequence, in this process and in peer Gateway processes. It is + taken after the scans, so a slow scan does not queue the owner's other + skill mutations. ``mutate`` re-reads whatever the scans assumed about the + stored skill. + """ + + def _run() -> None: + with custom_skill_mutation(skill_storage): + mutate() + + await _to_thread(_run) + + +def _write_and_record(skill_storage: SkillStorage, name: str, relative_path: str, content: str, record: dict[str, Any]) -> None: + skill_storage.write_custom_skill(name, relative_path, content) + skill_storage.append_history(name, record) async def _settle_skill_mutation(user_id: str, name: str, persist: Callable[[], Awaitable[object]]) -> None: @@ -256,7 +274,14 @@ async def _skill_manage_impl( scan = await _scan_or_raise(content, executable=False, location=f"{name}/{SKILL_MD_FILE}", static_findings=static_findings) scan["static_findings"] = static_findings record = _history_record(action="create", file_path=SKILL_MD_FILE, prev_content=None, new_content=content, thread_id=thread_id, scanner=scan) - await _settle_skill_mutation(user_id, name, lambda: _write_and_record(skill_storage, name, SKILL_MD_FILE, content, record)) + + def _create() -> None: + # A route or a peer process may have created it during the scans. + if skill_storage.custom_skill_exists(name): + raise ValueError(f"Custom skill '{name}' already exists.") + _write_and_record(skill_storage, name, SKILL_MD_FILE, content, record) + + await _settle_skill_mutation(user_id, name, lambda: _locked_mutation(skill_storage, _create)) return f"Created custom skill '{name}'." if action == "edit": await _to_thread(skill_storage.ensure_custom_skill_is_editable, name) @@ -266,9 +291,15 @@ async def _skill_manage_impl( static_findings = await _scan_static_candidate_or_raise(name, {SKILL_MD_FILE: content}) scan = await _scan_or_raise(content, executable=False, location=f"{name}/{SKILL_MD_FILE}", static_findings=static_findings) scan["static_findings"] = static_findings - prev_content = await _to_thread(skill_storage.read_custom_skill, name) - record = _history_record(action="edit", file_path=SKILL_MD_FILE, prev_content=prev_content, new_content=content, thread_id=thread_id, scanner=scan) - await _settle_skill_mutation(user_id, name, lambda: _write_and_record(skill_storage, name, SKILL_MD_FILE, content, record)) + + def _edit() -> None: + # The edit replaces the whole file, so it records what it + # actually overwrites, read under the lock. + prev_content = skill_storage.read_custom_skill(name) + record = _history_record(action="edit", file_path=SKILL_MD_FILE, prev_content=prev_content, new_content=content, thread_id=thread_id, scanner=scan) + _write_and_record(skill_storage, name, SKILL_MD_FILE, content, record) + + await _settle_skill_mutation(user_id, name, lambda: _locked_mutation(skill_storage, _edit)) return f"Updated custom skill '{name}'." if action == "patch": @@ -288,7 +319,16 @@ async def _skill_manage_impl( scan = await _scan_or_raise(new_content, executable=False, location=f"{name}/{SKILL_MD_FILE}", static_findings=static_findings) scan["static_findings"] = static_findings record = _history_record(action="patch", file_path=SKILL_MD_FILE, prev_content=prev_content, new_content=new_content, thread_id=thread_id, scanner=scan) - await _settle_skill_mutation(user_id, name, lambda: _write_and_record(skill_storage, name, SKILL_MD_FILE, new_content, record)) + + def _patch() -> None: + # The patched content was derived from, and scanned as, a + # change to prev_content. Writing it over a newer revision + # would silently revert that revision. + if skill_storage.read_custom_skill(name) != prev_content: + raise ValueError(f"SKILL.md of custom skill '{name}' changed while this patch was being checked. Nothing was written; read the skill again and retry the patch.") + _write_and_record(skill_storage, name, SKILL_MD_FILE, new_content, record) + + await _settle_skill_mutation(user_id, name, lambda: _locked_mutation(skill_storage, _patch)) return f"Patched custom skill '{name}' ({replacement_count} replacement(s) applied, {occurrences} match(es) found)." if action == "delete": @@ -300,7 +340,7 @@ async def _skill_manage_impl( thread_id=thread_id, scanner={"decision": "allow", "reason": "Deletion requested."}, ) - await _settle_skill_mutation(user_id, name, lambda: _to_thread(skill_storage.delete_custom_skill, name, history_meta=record)) + await _settle_skill_mutation(user_id, name, lambda: _locked_mutation(skill_storage, lambda: skill_storage.delete_custom_skill(name, history_meta=record))) return f"Deleted custom skill '{name}'." if action == "write_file": @@ -310,9 +350,6 @@ async def _skill_manage_impl( target = await _to_thread(skill_storage.ensure_safe_support_path, name, path) if await _to_thread(target.is_dir): raise ValueError(f"Supporting file path '{path}' is a directory, not a file.") - from deerflow.skills.mutations.guard import read_optional_text - - prev_content = await _to_thread(read_optional_text, skill_storage, target) # Executable content is whatever the shared package-file rule classifies # as code: a file under the top-level ``scripts/`` directory, a code-suffix # file anywhere in the package, or an extensionless file that starts with @@ -325,8 +362,19 @@ async def _skill_manage_impl( static_findings = await _scan_static_candidate_or_raise(name, {path: content}, skill_storage) scan = await _scan_or_raise(content, executable=executable, location=f"{name}/{path}", static_findings=static_findings) scan["static_findings"] = static_findings - record = _history_record(action="write_file", file_path=path, prev_content=prev_content, new_content=content, thread_id=thread_id, scanner=scan) - await _settle_skill_mutation(user_id, name, lambda: _write_and_record(skill_storage, name, path, content, record)) + + def _write_file() -> None: + from deerflow.skills.mutations.guard import read_optional_text + + # A skill deleted during the scans must not come back as a + # package with this one file and no SKILL.md. + if not skill_storage.custom_skill_exists(name): + raise FileNotFoundError(f"Custom skill '{name}' not found.") + prev_content = read_optional_text(skill_storage, target) + record = _history_record(action="write_file", file_path=path, prev_content=prev_content, new_content=content, thread_id=thread_id, scanner=scan) + _write_and_record(skill_storage, name, path, content, record) + + await _settle_skill_mutation(user_id, name, lambda: _locked_mutation(skill_storage, _write_file)) return f"Wrote '{path}' for custom skill '{name}'." if action == "remove_file": @@ -334,15 +382,14 @@ async def _skill_manage_impl( if path is None: raise ValueError("path is required for remove_file.") - async def _remove_and_record() -> None: - prev_content = await _to_thread(skill_storage.remove_custom_skill_file, name, path) - await _to_thread( - skill_storage.append_history, + def _remove_and_record() -> None: + prev_content = skill_storage.remove_custom_skill_file(name, path) + skill_storage.append_history( name, _history_record(action="remove_file", file_path=path, prev_content=prev_content, new_content=None, thread_id=thread_id, scanner={"decision": "allow", "reason": "Deletion requested."}), ) - await _settle_skill_mutation(user_id, name, _remove_and_record) + await _settle_skill_mutation(user_id, name, lambda: _locked_mutation(skill_storage, _remove_and_record)) return f"Removed '{path}' from custom skill '{name}'." if await _to_thread(skill_storage.public_skill_exists, name): diff --git a/backend/tests/test_skill_manage_tool.py b/backend/tests/test_skill_manage_tool.py index 69e89dea8b..3d58d8124b 100644 --- a/backend/tests/test_skill_manage_tool.py +++ b/backend/tests/test_skill_manage_tool.py @@ -10,6 +10,7 @@ import anyio import pytest from deerflow.skills.security_static_scanner import StaticScannerError +from deerflow.skills.types import SKILL_MD_FILE skill_manage_module = importlib.import_module("deerflow.tools.skill_manage_tool") @@ -623,10 +624,23 @@ def test_skill_manage_lock_waiters_leave_workers_for_other_skills(monkeypatch): waiters_parked.set() storage = _park_skill_mutations(monkeypatch, on_arrival) + # Park the holder after its delete: it keeps the skill lock but no + # longer holds the owner's mutation lock, as during a slow scan. A + # holder parked inside the delete would hold up the owner's other + # skills by design, like a route mutation does. + storage.entered.set() + holder_parked = threading.Event() + + async def _parked_refresh(_user_id: str) -> None: + if not holder_parked.is_set(): + holder_parked.set() + assert await asyncio.to_thread(storage.release.wait, 5), "test never released the parked holder" + + monkeypatch.setattr(skill_manage_module, "refresh_user_skills_system_prompt_cache_async", _parked_refresh) holder = asyncio.create_task(_delete("alice", "busy-skill")) tasks = [holder] try: - assert await asyncio.to_thread(storage.entered.wait, 5) + assert await asyncio.to_thread(holder_parked.wait, 5) tasks += [asyncio.create_task(_delete("alice", "busy-skill")) for _ in range(2)] await asyncio.wait_for(waiters_parked.wait(), 5) # The holder parks one worker; the waiters must leave the other free @@ -808,3 +822,158 @@ def test_skill_manage_edits_stay_permissive_for_device_named_skills(monkeypatch, anyio.run(skill_manage_module.skill_manage_tool.coroutine, runtime, "edit", "nul", _skill_content("nul")) with pytest.raises(FileNotFoundError, match="not found"): anyio.run(skill_manage_module.skill_manage_tool.coroutine, runtime, "delete", "nul") + + +# --- the owner's custom-skill mutation lock, shared with the Gateway routes --- + + +def _run_tool(runtime, *args): + return anyio.run(skill_manage_module.skill_manage_tool.coroutine, runtime, *args) + + +def _owner_storage(): + from deerflow.skills.storage import get_or_new_user_skill_storage + + return get_or_new_user_skill_storage("default") + + +def _change_during_model_scan(monkeypatch, change): + """Run ``change`` once from the model scan: after the tool read the skill, before it writes. + + ``change`` stands for a mutation that a route or a peer Gateway process + completed while the tool was scanning. + """ + changed = [] + + async def _scan(*args, **kwargs): + if not changed: + changed.append(True) + await asyncio.to_thread(change) + return await _async_result("allow", "ok") + + monkeypatch.setattr(skill_manage_module, "scan_skill_content", _scan) + + +def test_skill_manage_waits_for_the_owner_mutation_lock(monkeypatch, tmp_path): + """A route holding the owner's lock finishes its read → write → history first.""" + from deerflow.skills import mutation_lock + + user_custom = _patch_skill_manage_env(monkeypatch, tmp_path) + runtime = _make_runtime(user_id="default") + initial, human, agent = (_skill_content("demo-skill", label) for label in ("Initial", "Human", "Agent")) + _run_tool(runtime, "create", "demo-skill", initial) + storage = _owner_storage() + reached, done = threading.Event(), threading.Event() + original_lock = mutation_lock.custom_skill_mutation_lock + + def _observed_lock(lock_storage): + reached.set() + return original_lock(lock_storage) + + def _edit(): + try: + _run_tool(runtime, "edit", "demo-skill", agent) + finally: + done.set() + + tool_call = threading.Thread(target=_edit, daemon=True) + with mutation_lock.custom_skill_mutation(storage): + monkeypatch.setattr(mutation_lock, "custom_skill_mutation_lock", _observed_lock) + tool_call.start() + assert reached.wait(5), "the tool never reached the owner's mutation lock" + assert not done.wait(1), "the tool edited the skill inside a route's critical section" + prev_content = storage.read_custom_skill("demo-skill") + storage.write_custom_skill("demo-skill", SKILL_MD_FILE, human) + storage.append_history("demo-skill", {"action": "human_edit", "author": "human", "prev_content": prev_content, "new_content": human}) + tool_call.join(5) + + assert done.is_set() + assert (user_custom / "demo-skill" / SKILL_MD_FILE).read_text(encoding="utf-8") == agent + records = _history_records(user_custom / "demo-skill") + assert [(r["action"], r["prev_content"], r["new_content"]) for r in records] == [ + ("create", None, initial), + ("human_edit", initial, human), + ("edit", human, agent), + ] + + +def test_skill_manage_patch_refuses_a_skill_that_changed_during_its_scans(monkeypatch, tmp_path): + """The patch was derived from, and scanned as, a change to the content it read.""" + user_custom = _patch_skill_manage_env(monkeypatch, tmp_path) + runtime = _make_runtime(user_id="default") + initial, human = _skill_content("demo-skill"), _skill_content("demo-skill", "Human revision") + _run_tool(runtime, "create", "demo-skill", initial) + + def _human_edit(): + storage = _owner_storage() + storage.write_custom_skill("demo-skill", SKILL_MD_FILE, human) + storage.append_history("demo-skill", {"action": "human_edit", "author": "human", "prev_content": initial, "new_content": human}) + + _change_during_model_scan(monkeypatch, _human_edit) + + with pytest.raises(ValueError, match="changed while this patch was being checked"): + _run_tool(runtime, "patch", "demo-skill", None, None, "Demo skill", "Patched skill", 1) + + assert (user_custom / "demo-skill" / SKILL_MD_FILE).read_text(encoding="utf-8") == human + assert [r["action"] for r in _history_records(user_custom / "demo-skill")] == ["create", "human_edit"] + + +def test_skill_manage_write_file_records_the_content_it_overwrites(monkeypatch, tmp_path): + user_custom = _patch_skill_manage_env(monkeypatch, tmp_path) + runtime = _make_runtime(user_id="default") + _run_tool(runtime, "create", "demo-skill", _skill_content("demo-skill")) + _run_tool(runtime, "write_file", "demo-skill", "v1", "references/guide.md") + _change_during_model_scan(monkeypatch, lambda: _owner_storage().write_custom_skill("demo-skill", "references/guide.md", "v2")) + + _run_tool(runtime, "write_file", "demo-skill", "v3", "references/guide.md") + + assert (user_custom / "demo-skill" / "references" / "guide.md").read_text(encoding="utf-8") == "v3" + record = _history_records(user_custom / "demo-skill")[-1] + assert (record["action"], record["prev_content"], record["new_content"]) == ("write_file", "v2", "v3") + + +def test_skill_manage_write_file_does_not_recreate_a_skill_deleted_during_its_scans(monkeypatch, tmp_path): + user_custom = _patch_skill_manage_env(monkeypatch, tmp_path) + runtime = _make_runtime(user_id="default") + _run_tool(runtime, "create", "demo-skill", _skill_content("demo-skill")) + _change_during_model_scan(monkeypatch, lambda: _owner_storage().delete_custom_skill("demo-skill")) + + with pytest.raises(FileNotFoundError, match="not found"): + _run_tool(runtime, "write_file", "demo-skill", "print('hi')\n", "references/guide.md") + + assert not (user_custom / "demo-skill").exists() + + +def test_skill_manage_create_does_not_overwrite_a_skill_created_during_its_scans(monkeypatch, tmp_path): + user_custom = _patch_skill_manage_env(monkeypatch, tmp_path) + runtime = _make_runtime(user_id="default") + theirs = _skill_content("demo-skill", "Created elsewhere") + _change_during_model_scan(monkeypatch, lambda: _owner_storage().write_custom_skill("demo-skill", SKILL_MD_FILE, theirs)) + + with pytest.raises(ValueError, match="already exists"): + _run_tool(runtime, "create", "demo-skill", _skill_content("demo-skill")) + + assert (user_custom / "demo-skill" / SKILL_MD_FILE).read_text(encoding="utf-8") == theirs + assert not list(user_custom.rglob("*.jsonl")) + + +def test_skill_manage_scans_without_holding_the_owner_mutation_lock(monkeypatch, tmp_path): + """A slow scan must not queue the owner's route edits of other skills.""" + from deerflow.skills.mutation_lock import custom_skill_mutation_lock + + _patch_skill_manage_env(monkeypatch, tmp_path) + runtime = _make_runtime(user_id="default") + _run_tool(runtime, "create", "demo-skill", _skill_content("demo-skill")) + acquired = [] + + def _route_lock_is_free(): + lock = custom_skill_mutation_lock(_owner_storage()) + acquired.append(lock.acquire(timeout=2)) + if acquired[-1]: + lock.release() + + _change_during_model_scan(monkeypatch, _route_lock_is_free) + + _run_tool(runtime, "edit", "demo-skill", _skill_content("demo-skill", "Edited")) + + assert acquired == [True] diff --git a/backend/tests/test_skills_cache_shared_reset.py b/backend/tests/test_skills_cache_shared_reset.py index e9d3215c4a..51b5ee611b 100644 --- a/backend/tests/test_skills_cache_shared_reset.py +++ b/backend/tests/test_skills_cache_shared_reset.py @@ -843,20 +843,14 @@ async def test_skill_manage_tool_drains_write_refresh_and_publish_across_cancell await asyncio.to_thread(agent_skill_tool.install) entered = threading.Event() release = threading.Event() - to_thread = skill_manage_module._to_thread + write_custom_skill = UserScopedSkillStorage.write_custom_skill - async def _parking_to_thread(func, /, *args, **kwargs): - if getattr(func, "__name__", None) != "write_custom_skill": - return await to_thread(func, *args, **kwargs) + def _parked_write(self, *args, **kwargs): + entered.set() + assert release.wait(5), "test never released the parked write" + return write_custom_skill(self, *args, **kwargs) - def _parked(): - entered.set() - assert release.wait(5), "test never released the parked write" - return func(*args, **kwargs) - - return await to_thread(_parked) - - monkeypatch.setattr(skill_manage_module, "_to_thread", _parking_to_thread) + monkeypatch.setattr(UserScopedSkillStorage, "write_custom_skill", _parked_write) edited = _skill_content(_AGENT_SKILL, "Edited skill") task = asyncio.create_task(agent_skill_tool.call(action="edit", content=edited)) try: diff --git a/backend/tests/test_skills_custom_multiprocess.py b/backend/tests/test_skills_custom_multiprocess.py index 6b34558091..dcefa8be23 100644 --- a/backend/tests/test_skills_custom_multiprocess.py +++ b/backend/tests/test_skills_custom_multiprocess.py @@ -1,4 +1,8 @@ -"""History ordering for independent Gateway processes sharing a skills root.""" +"""History ordering for independent Gateway processes sharing a skills root. + +The skill routes and the agent's ``skill_manage`` tool both mutate custom +skills, so each pair must serialize, not only two routes. +""" import asyncio import json @@ -44,13 +48,22 @@ def _mutate_in_process(base_dir, action, content, gate_phase, ready, start, atte patch.setattr(router, "_scan_static_skill_markdown_or_raise", static_scan) patch.setattr(router, "refresh_user_skills_system_prompt_cache_async", refresh) patch.setattr(router, "_publish_skills_cache_reset", refresh) - original_lock = router._custom_skill_mutation_lock + + from deerflow.tools import skill_manage_tool + + patch.setattr(skill_manage_tool, "scan_skill_content", scan) + patch.setattr(skill_manage_tool, "refresh_user_skills_system_prompt_cache_async", refresh) + patch.setattr(skill_manage_tool, "publish_skills_cache_reset", lambda *, user_id=None: None) + + from deerflow.skills import mutation_lock + + original_lock = mutation_lock.custom_skill_mutation_lock def observed_lock(storage): attempted.set() return original_lock(storage) - patch.setattr(router, "_custom_skill_mutation_lock", observed_lock) + patch.setattr(mutation_lock, "custom_skill_mutation_lock", observed_lock) if gate_phase: method = "write_custom_skill" if gate_phase == "write" else "append_history" original = getattr(UserScopedSkillStorage, method) @@ -65,32 +78,34 @@ def _mutate_in_process(base_dir, action, content, gate_phase, ready, start, atte request = SimpleNamespace(state=SimpleNamespace(user=SimpleNamespace(system_role="admin"))) ready.set() assert start.wait(30), "parent did not start the mutation" - if action == "edit": + if action == "tool_edit": + runtime = SimpleNamespace(context={"thread_id": "thread-1", "user_id": "default"}, config={"configurable": {"thread_id": "thread-1", "user_id": "default"}}) + asyncio.run(skill_manage_tool.skill_manage_tool.coroutine(runtime, "edit", "demo-skill", content)) + elif action == "edit": asyncio.run(router.update_custom_skill("demo-skill", router.CustomSkillUpdateRequest(content=content), request, config)) else: asyncio.run(router.rollback_custom_skill("demo-skill", router.SkillRollbackRequest(history_index=0), request, config)) done.set() -@pytest.mark.parametrize("action", ["edit", "rollback"]) -@pytest.mark.parametrize("gate_phase", ["write", "history"]) -def test_custom_skill_history_serializes_independent_processes(tmp_path, action, gate_phase): - """A peer must wait through both the predecessor read and history append.""" +def _mutate_in_two_processes(tmp_path, first_action, peer_action, gate_phase, prior=()): + """Park ``first_action`` at ``gate_phase`` and require ``peer_action`` to wait for it. + + Returns the history entries and the final ``SKILL.md``. + """ custom_root = tmp_path / "users" / "default" / "skills" / "custom" skill_file = custom_root / "demo-skill" / "SKILL.md" skill_file.parent.mkdir(parents=True) - initial, restored, edited, concurrent = (_content(label) for label in ("Initial", "Restored", "Edited", "Concurrent")) - skill_file.write_text(initial, encoding="utf-8") + skill_file.write_text(_content("Initial"), encoding="utf-8") history_file = custom_root / ".history" / "demo-skill.jsonl" history_file.parent.mkdir() - prior = [{"action": "human_edit", "prev_content": restored, "new_content": initial}] if action == "rollback" else [] history_file.write_text("".join(json.dumps(entry) + "\n" for entry in prior), encoding="utf-8") context = multiprocessing.get_context("spawn") parked, release = context.Event(), context.Event() workers = [] starts, ready_events, attempted_events, done_events = [], [], [], [] - for worker_action, worker_content, phase in [(action, edited, gate_phase), ("edit", concurrent, None)]: + for worker_action, worker_content, phase in [(first_action, _content("Edited"), gate_phase), (peer_action, _content("Concurrent"), None)]: ready, start, attempted, done = (context.Event() for _ in range(4)) workers.append(context.Process(target=_mutate_in_process, args=(tmp_path, worker_action, worker_content, phase, ready, start, attempted, parked, release, done))) ready_events.append(ready) @@ -126,6 +141,18 @@ def test_custom_skill_history_serializes_independent_processes(tmp_path, action, worker.close() entries = [json.loads(line) for line in history_file.read_text(encoding="utf-8").splitlines()] + return entries, skill_file.read_text(encoding="utf-8") + + +@pytest.mark.parametrize("action", ["edit", "rollback"]) +@pytest.mark.parametrize("gate_phase", ["write", "history"]) +def test_custom_skill_history_serializes_independent_processes(tmp_path, action, gate_phase): + """A peer must wait through both the predecessor read and history append.""" + initial, restored, edited, concurrent = (_content(label) for label in ("Initial", "Restored", "Edited", "Concurrent")) + prior = [{"action": "human_edit", "prev_content": restored, "new_content": initial}] if action == "rollback" else [] + + entries, final_content = _mutate_in_two_processes(tmp_path, action, "edit", gate_phase, prior) + first_content = edited if action == "edit" else restored assert len(entries) == len(prior) + 2 assert entries[len(prior)]["action"] == ("human_edit" if action == "edit" else "rollback") @@ -133,4 +160,20 @@ def test_custom_skill_history_serializes_independent_processes(tmp_path, action, assert entries[len(prior)]["new_content"] == first_content assert entries[-1]["prev_content"] == first_content assert entries[-1]["new_content"] == concurrent - assert skill_file.read_text(encoding="utf-8") == concurrent + assert final_content == concurrent + + +@pytest.mark.parametrize("first, peer", [("tool_edit", "edit"), ("edit", "tool_edit")], ids=["tool-then-route", "route-then-tool"]) +@pytest.mark.parametrize("gate_phase", ["write", "history"]) +def test_skill_manage_and_routes_serialize_across_processes(tmp_path, first, peer, gate_phase): + """The tool and a route in another Gateway process share the owner's mutation lock.""" + initial, edited, concurrent = (_content(label) for label in ("Initial", "Edited", "Concurrent")) + + entries, final_content = _mutate_in_two_processes(tmp_path, first, peer, gate_phase) + + actions = {"edit": "human_edit", "tool_edit": "edit"} + assert [(entry["action"], entry["prev_content"], entry["new_content"]) for entry in entries] == [ + (actions[first], initial, edited), + (actions[peer], edited, concurrent), + ] + assert final_content == concurrent diff --git a/backend/tests/test_skills_custom_router.py b/backend/tests/test_skills_custom_router.py index 9681a29b0c..3729a58d6b 100644 --- a/backend/tests/test_skills_custom_router.py +++ b/backend/tests/test_skills_custom_router.py @@ -2212,8 +2212,8 @@ def test_custom_skill_mutation_lock_is_scoped_to_the_owning_user(tmp_path, monke two users that own disjoint custom-skill trees must not share the lock that also spans write_custom_skill's whole projection rebuild. """ - from app.gateway.routers.skills import _custom_skill_mutation_lock from deerflow.config.paths import Paths + from deerflow.skills.mutation_lock import custom_skill_mutation_lock monkeypatch.setattr("deerflow.config.paths.get_paths", lambda: Paths(base_dir=tmp_path)) monkeypatch.setattr("deerflow.config.paths._paths", None) @@ -2222,8 +2222,8 @@ def test_custom_skill_mutation_lock_is_scoped_to_the_owning_user(tmp_path, monke alice_second_instance = UserScopedSkillStorage("alice", host_path=str(tmp_path / "skills")) bob = UserScopedSkillStorage("bob", host_path=str(tmp_path / "skills")) - assert _custom_skill_mutation_lock(alice) is _custom_skill_mutation_lock(alice_second_instance) - assert _custom_skill_mutation_lock(alice) is not _custom_skill_mutation_lock(bob) + assert custom_skill_mutation_lock(alice) is custom_skill_mutation_lock(alice_second_instance) + assert custom_skill_mutation_lock(alice) is not custom_skill_mutation_lock(bob) def test_custom_skill_update_does_not_serialize_an_unrelated_user(monkeypatch, tmp_path):