diff --git a/backend/packages/harness/deerflow/skills/AGENTS.md b/backend/packages/harness/deerflow/skills/AGENTS.md index ae38d9f99a..3339aeb3ff 100644 --- a/backend/packages/harness/deerflow/skills/AGENTS.md +++ b/backend/packages/harness/deerflow/skills/AGENTS.md @@ -57,7 +57,10 @@ their credentials and enabled state stay per user. 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. - **History is JSONL split on LF only.** Unicode line separators inside a saved - field are data. + field are data. Every history writer appends a whole record and its LF under + `locked_history_file`: callers do not share a mutation lock, and a split or + retried write would let another record join the line. Readers take its shared + mode, or a retried write reads as a torn record. - **Export is not a secret audit.** It returns raw saved files. Responses carry relative paths and generic errors, and limits are reported, not silently applied by truncation. diff --git a/backend/packages/harness/deerflow/skills/history_lock.py b/backend/packages/harness/deerflow/skills/history_lock.py new file mode 100644 index 0000000000..42ef977b01 --- /dev/null +++ b/backend/packages/harness/deerflow/skills/history_lock.py @@ -0,0 +1,42 @@ +"""The lock every writer and reader of a custom-skill history file holds.""" + +from __future__ import annotations + +import os +from collections.abc import Iterator +from contextlib import contextmanager + +try: + import fcntl +except ImportError: # pragma: no cover - Windows + fcntl = None # type: ignore[assignment] + import msvcrt + + +@contextmanager +def locked_history_file(fd: int, *, shared: bool = False) -> Iterator[None]: + """Hold a lock on the open history file ``fd``: exclusive, or ``shared``. + + ``O_APPEND`` makes one write atomic, but finishing a short write takes a + second one, and no other record may land between the two. Writers hold the + lock exclusively across all of a record's writes. Readers hold it shared, so + they never see a record that is still being written. The lock belongs to the + open file, so it also serializes two threads of one process, which open the + file separately. Take it last: a holder acquires no other lock meanwhile. + + ``msvcrt.locking`` has no shared mode, so on Windows readers lock + exclusively as well. + """ + if fcntl is not None: + fcntl.flock(fd, fcntl.LOCK_SH if shared else fcntl.LOCK_EX) + else: # pragma: no cover - Windows + os.lseek(fd, 0, os.SEEK_SET) + msvcrt.locking(fd, msvcrt.LK_LOCK, 1) + try: + yield + finally: + if fcntl is not None: + fcntl.flock(fd, fcntl.LOCK_UN) + else: # pragma: no cover - Windows + os.lseek(fd, 0, os.SEEK_SET) + msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) diff --git a/backend/packages/harness/deerflow/skills/mutations/history.py b/backend/packages/harness/deerflow/skills/mutations/history.py index 8a7968bf44..685ef8c36b 100644 --- a/backend/packages/harness/deerflow/skills/mutations/history.py +++ b/backend/packages/harness/deerflow/skills/mutations/history.py @@ -6,6 +6,7 @@ import stat from collections import defaultdict from dataclasses import asdict +from deerflow.skills.history_lock import locked_history_file from deerflow.skills.mutations.assets import open_directory_chain MAX_HISTORY_BYTES = 8 * 1024 * 1024 @@ -37,66 +38,69 @@ def mirror_operations(storage, operations): storage.validate_skill_name(name) fd = os.open(name + ".jsonl", os.O_RDWR | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600, dir_fd=directory) try: - before = os.fstat(fd) - if not stat.S_ISREG(before.st_mode) or before.st_size > MAX_HISTORY_BYTES: - continue - seen, pending, total = set(), b"", 0 - valid = True - while chunk := os.read(fd, min(65536, MAX_HISTORY_BYTES + 1 - total)): - total += len(chunk) - if total > MAX_HISTORY_BYTES: - valid = False - break - lines = (pending + chunk).split(b"\n") - pending = lines.pop() - for line in lines: - if len(line) > MAX_HISTORY_LINE_BYTES: - valid = False - break - if not line.strip(): - continue - try: - record = json.loads(line) - if not isinstance(record, dict): - raise ValueError - identifier = record.get("operation_id") - if isinstance(identifier, str): - seen.add(identifier) - except (ValueError, UnicodeError): - valid = False - break - if not valid or len(pending) > MAX_HISTORY_LINE_BYTES: - valid = False - break - if not valid or pending.strip() or os.fstat(fd).st_size != before.st_size: - continue - records = [] - for operation in reversed(items): - if operation.operation_id in seen: + # Storage appends take the same lock, so a record never lands inside + # another one and the size check below sees a settled file. + with locked_history_file(fd): + before = os.fstat(fd) + if not stat.S_ISREG(before.st_mode) or before.st_size > MAX_HISTORY_BYTES: continue - records.append( - json.dumps( - { - "operation_id": operation.operation_id, - "action": "host_revert" if operation.reverts_operation_id else "host_commit", - "publication": operation.publication, - "prev_revision": asdict(operation.before_revision), - "new_revision": asdict(operation.after_revision), - "scope": "main-file-only", - "file_path": "SKILL.md", - }, - separators=(",", ":"), - ).encode() - + b"\n" - ) - if total + sum(map(len, records)) > MAX_HISTORY_BYTES: - continue - for record in records: - if os.write(fd, record) != len(record): - raise OSError("incomplete history mirror") - if records: - os.fsync(fd) - os.fsync(directory) + seen, pending, total = set(), b"", 0 + valid = True + while chunk := os.read(fd, min(65536, MAX_HISTORY_BYTES + 1 - total)): + total += len(chunk) + if total > MAX_HISTORY_BYTES: + valid = False + break + lines = (pending + chunk).split(b"\n") + pending = lines.pop() + for line in lines: + if len(line) > MAX_HISTORY_LINE_BYTES: + valid = False + break + if not line.strip(): + continue + try: + record = json.loads(line) + if not isinstance(record, dict): + raise ValueError + identifier = record.get("operation_id") + if isinstance(identifier, str): + seen.add(identifier) + except (ValueError, UnicodeError): + valid = False + break + if not valid or len(pending) > MAX_HISTORY_LINE_BYTES: + valid = False + break + if not valid or pending.strip() or os.fstat(fd).st_size != before.st_size: + continue + records = [] + for operation in reversed(items): + if operation.operation_id in seen: + continue + records.append( + json.dumps( + { + "operation_id": operation.operation_id, + "action": "host_revert" if operation.reverts_operation_id else "host_commit", + "publication": operation.publication, + "prev_revision": asdict(operation.before_revision), + "new_revision": asdict(operation.after_revision), + "scope": "main-file-only", + "file_path": "SKILL.md", + }, + separators=(",", ":"), + ).encode() + + b"\n" + ) + if total + sum(map(len, records)) > MAX_HISTORY_BYTES: + continue + for record in records: + if os.write(fd, record) != len(record): + raise OSError("incomplete history mirror") + if records: + os.fsync(fd) + os.fsync(directory) finally: os.close(fd) finally: diff --git a/backend/packages/harness/deerflow/skills/storage/local_skill_storage.py b/backend/packages/harness/deerflow/skills/storage/local_skill_storage.py index e578492509..7dc0666217 100644 --- a/backend/packages/harness/deerflow/skills/storage/local_skill_storage.py +++ b/backend/packages/harness/deerflow/skills/storage/local_skill_storage.py @@ -6,6 +6,7 @@ import asyncio import errno import json import logging +import os import shutil import tempfile from collections.abc import Iterable @@ -14,6 +15,7 @@ from pathlib import Path from deerflow.config.runtime_paths import resolve_path from deerflow.constants import DEFAULT_SKILLS_CONTAINER_PATH +from deerflow.skills.history_lock import locked_history_file from deerflow.skills.permissions import make_skill_written_path_sandbox_readable from deerflow.skills.storage.skill_storage import SKILL_MD_FILE, SkillStorage, walk_skill_directories from deerflow.skills.types import SkillCategory @@ -297,23 +299,45 @@ class LocalSkillStorage(SkillStorage): def append_history(self, name: str, record: dict) -> None: self.validate_skill_name(name) payload = {"ts": datetime.now(UTC).isoformat(), **record} + # A record and its LF terminator are appended whole, under the history + # file's own lock. Appenders in other threads and processes do not always + # share a mutation lock, and a record holding two SKILL.md revisions + # outgrows the text-file buffer: a separate terminator write let another + # record land between a record and its "\n", and read_history then + # rejected the joined line for good. Encoding first leaves no file + # behind on failure. + data = (json.dumps(payload, ensure_ascii=False) + "\n").encode("utf-8") history_path = self.get_skill_history_file(name) history_path.parent.mkdir(parents=True, exist_ok=True) - # JSONL records are LF-delimited on every host: a translated record - # boundary made read_history and any raw-byte reader describe different - # revisions of the same entry. - with history_path.open("a", encoding="utf-8", newline="") as f: - f.write(json.dumps(payload, ensure_ascii=False)) - f.write("\n") + # JSONL records are LF-delimited on every host (O_BINARY: no Windows + # translation): a translated record boundary made read_history and any + # raw-byte reader describe different revisions of the same entry. + fd = os.open(history_path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | getattr(os, "O_BINARY", 0), 0o666) + try: + # The lock spans the retries: a short write (a full disk, a signal) + # continues with the rest rather than dropping the tail, and no other + # writer's record can land inside this one meanwhile. + with locked_history_file(fd): + remaining = memoryview(data) + while remaining: + remaining = remaining[os.write(fd, remaining) :] + finally: + os.close(fd) def read_history(self, name: str) -> list[dict]: self.validate_skill_name(name) history_path = self.get_skill_history_file(name) - if not history_path.exists(): + try: + history_file = history_path.open(encoding="utf-8") + except FileNotFoundError: return [] + # Shared with other readers, but not with an append: a record whose + # write is still being retried would otherwise read as a torn tail. + with history_file, locked_history_file(history_file.fileno(), shared=True): + text = history_file.read() records: list[dict] = [] # JSONL boundaries are newlines, not Unicode separators inside JSON strings. - for line in history_path.read_text(encoding="utf-8").split("\n"): + for line in text.split("\n"): if not line.strip(): continue records.append(json.loads(line)) diff --git a/backend/tests/test_skill_history_jsonl.py b/backend/tests/test_skill_history_jsonl.py index e1fecfc387..f848f4fe6b 100644 --- a/backend/tests/test_skill_history_jsonl.py +++ b/backend/tests/test_skill_history_jsonl.py @@ -1,6 +1,7 @@ """Skill history records use physical JSONL boundaries, not Unicode text lines.""" import json +import os import pytest @@ -54,3 +55,265 @@ def test_malformed_json_is_still_rejected(storage): path.write_bytes(b'{"reason":"valid"}\n{"reason":') with pytest.raises(json.JSONDecodeError): storage.read_history("demo-skill") + + +def test_concurrent_appends_keep_one_record_per_line(storage): + # Records this large hold two SKILL.md revisions; they outgrow the text-file + # buffer, which once sent the "\n" terminator in a separate write. + import threading + + bodies = {tag: tag * 65536 for tag in "abcd"} + + def append(tag): + for index in range(40): + storage.append_history("demo-skill", {"action": "edit", "author": tag, "index": index, "new_content": bodies[tag]}) + + threads = [threading.Thread(target=append, args=(tag,)) for tag in bodies] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + records = storage.read_history("demo-skill") + assert sorted((record["author"], record["index"]) for record in records) == sorted((tag, index) for tag in bodies for index in range(40)) + assert all(record["new_content"] == bodies[record["author"]] for record in records) + + +def _script_history_writes(monkeypatch, storage, script=None): + """Route every ``os.write`` to the history file through ``script``. + + ``script(data, write)`` performs the write with ``write`` and returns its + count; it may shorten ``data`` or let another writer run around it. Returns + the list of bytes that reached the file, one entry per write. + """ + history_path = storage.get_skill_history_file("demo-skill") + real_write = os.write + writes = [] + + def is_history(fd): + try: + target = os.stat(history_path) + except FileNotFoundError: + return False + opened = os.fstat(fd) + return (opened.st_dev, opened.st_ino) == (target.st_dev, target.st_ino) + + def write(fd, data): + if not is_history(fd): + return real_write(fd, data) + + def record(chunk): + writes.append(bytes(chunk)) + return real_write(fd, chunk) + + return script(bytes(data), record) if script is not None else record(data) + + monkeypatch.setattr(os, "write", write) + return writes + + +def _shorten_first_write(limit, before_rest=None): + """Cut the first write to ``limit`` bytes; run ``before_rest`` before the retry.""" + calls = [] + + def script(data, write): + calls.append(data) + if len(calls) == 1: + return write(data[:limit]) + if len(calls) == 2 and before_rest is not None: + before_rest() + return write(data) + + return script + + +def _signal_blocked_history_lock(monkeypatch): + """Set the returned event when a storage read or append has to wait for the history file lock. + + The holder of a short write uses it as a barrier: it retries only once the + other thread is blocked on the lock, or has finished without waiting for + it, which is past the point where a path that is not excluded would have + touched the file. Neither depends on how the threads are scheduled. + """ + import threading + + from deerflow.skills.storage import local_skill_storage + + blocked = threading.Event() + real = local_skill_storage.locked_history_file + + def held_elsewhere(fd): + try: + import fcntl + except ImportError: # Windows + import msvcrt + + os.lseek(fd, 0, os.SEEK_SET) + try: + msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) + except OSError: + return True + msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) + return False + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return True + fcntl.flock(fd, fcntl.LOCK_UN) + return False + + def locked(fd, **kwargs): + if held_elsewhere(fd): + blocked.set() + return real(fd, **kwargs) + + monkeypatch.setattr(local_skill_storage, "locked_history_file", locked) + return blocked + + +def _thread_signalling(event, target, *args): + """A thread running ``target`` that also sets ``event`` when it ends.""" + import threading + + def run(): + try: + target(*args) + finally: + event.set() + + return threading.Thread(target=run) + + +def _operation(operation_id): + from deerflow_extension_api.skill_mutations import AssetRevision, Operation + + revision = AssetRevision("incarnation", 1, "digest") + return Operation(operation_id, "history-owner", "demo-skill", "published", "main", revision, revision, 1) + + +def test_each_record_reaches_the_file_in_one_write(storage, monkeypatch): + writes = _script_history_writes(monkeypatch, storage) + + storage.append_history("demo-skill", {"action": "edit", "new_content": "x" * 65536}) + storage.append_history("demo-skill", {"action": "edit", "reason": "small"}) + + assert len(writes) == 2 + assert all(data.endswith(b"\n") and data.count(b"\n") == 1 for data in writes) + assert [record["action"] for record in storage.read_history("demo-skill")] == ["edit", "edit"] + + +def test_a_short_write_still_stores_the_whole_record(storage, monkeypatch): + writes = _script_history_writes(monkeypatch, storage, _shorten_first_write(10)) + + storage.append_history("demo-skill", {"action": "edit", "new_content": "x" * 1000}) + + assert len(writes) == 2 and len(writes[0]) == 10 + (record,) = storage.read_history("demo-skill") + assert record["new_content"] == "x" * 1000 + + +def test_another_append_waits_for_a_short_write_to_finish(storage, monkeypatch): + blocked = _signal_blocked_history_lock(monkeypatch) + other = _thread_signalling(blocked, storage.append_history, "demo-skill", {"action": "edit", "author": "b"}) + + def let_the_other_append_run(): + # Between the short write and its retry: the record is half written. + # The retry waits until the other append is blocked on the lock, or + # has finished without waiting. + other.start() + assert blocked.wait(timeout=5) + + _script_history_writes(monkeypatch, storage, _shorten_first_write(10, before_rest=let_the_other_append_run)) + + storage.append_history("demo-skill", {"action": "edit", "author": "a", "new_content": "x" * 1000}) + other.join(timeout=5) + + assert not other.is_alive() + assert [record["author"] for record in storage.read_history("demo-skill")] == ["a", "b"] + + +def test_a_read_waits_for_a_short_write_to_finish(storage, monkeypatch): + storage.append_history("demo-skill", {"action": "create", "author": "first"}) + blocked = _signal_blocked_history_lock(monkeypatch) + seen = [] + + def read(): + try: + seen.append([record["author"] for record in storage.read_history("demo-skill")]) + except json.JSONDecodeError as error: + seen.append(error) + + reader = _thread_signalling(blocked, read) + + def let_the_read_run(): + # Between the short write and its retry: the tail is half a record. + # The retry waits until the reader is blocked on the lock, or has read + # without waiting. + reader.start() + assert blocked.wait(timeout=5) + + _script_history_writes(monkeypatch, storage, _shorten_first_write(10, before_rest=let_the_read_run)) + + storage.append_history("demo-skill", {"action": "edit", "author": "a", "new_content": "x" * 1000}) + reader.join(timeout=5) + + assert not reader.is_alive() + assert seen == [["first", "a"]] + + +@pytest.mark.skipif(os.name != "posix", reason="msvcrt.locking has no shared mode, so Windows readers lock exclusively") +def test_reads_share_the_history_lock(storage): + import fcntl + import threading + + storage.append_history("demo-skill", {"action": "create", "author": "first"}) + seen = [] + with storage.get_skill_history_file("demo-skill").open("rb") as other_reader: + fcntl.flock(other_reader, fcntl.LOCK_SH) + reader = threading.Thread(target=lambda: seen.append(storage.read_history("demo-skill"))) + reader.start() + reader.join(timeout=5) + fcntl.flock(other_reader, fcntl.LOCK_UN) + + assert not reader.is_alive() + assert [record["author"] for record in seen[0]] == ["first"] + + +@pytest.mark.skipif(os.name != "posix", reason="the operation mirror requires POSIX directory descriptors") +def test_the_operation_mirror_and_appends_share_the_history_lock(storage, monkeypatch): + import threading + + from deerflow.skills.mutations.history import mirror_operations + + storage.get_skill_history_file("demo-skill").parent.mkdir(parents=True) + # Set when the append has to wait for the mirror's lock, or, without that + # lock, once the append's first, short write is in. + append_held = _signal_blocked_history_lock(monkeypatch) + resume_append = threading.Event() + append = threading.Thread(target=storage.append_history, args=("demo-skill", {"action": "edit", "author": "a"})) + append_calls = [] + + def script(data, write): + if b'"operation_id":"op-b"' in data: + # The mirror is about to write. An append that starts now must not + # get its first, short write in before the mirror's record. + append.start() + assert append_held.wait(timeout=5) + written = write(data) + resume_append.set() + return written + append_calls.append(data) + if len(append_calls) > 1: + return write(data) + written = write(data[:10]) + append_held.set() + resume_append.wait(timeout=5) + return written + + _script_history_writes(monkeypatch, storage, script) + + mirror_operations(storage, [_operation("op-b")]) + append.join(timeout=5) + + assert not append.is_alive() + assert [record.get("operation_id", record.get("author")) for record in storage.read_history("demo-skill")] == ["op-b", "a"] diff --git a/docs/guide/skills-and-tools.md b/docs/guide/skills-and-tools.md index 8af2b0259e..d1fb49a09b 100644 --- a/docs/guide/skills-and-tools.md +++ b/docs/guide/skills-and-tools.md @@ -235,7 +235,7 @@ and other runs. `SKILL.md` YAML frontmatter must open and close with `---` on its own line (trailing spaces or tabs are allowed). A line such as `---suffix` is not a closing delimiter. -Custom skill history preserves Unicode line separators inside saved content and metadata, keeping those revisions readable for history inspection and rollback. Malformed JSON history records are still rejected. +Custom skill history preserves Unicode line separators inside saved content and metadata, keeping those revisions readable for history inspection and rollback. Malformed JSON history records are still rejected. Each record is appended whole under the history file's lock, so concurrent edits from the agent, the skill API or several Gateway workers cannot join two records on one line. History reads take the same lock, so they never see a record that is still being written. The bundled `github-deep-research` API client also works without `requests`, using Python's standard-library HTTP client. Its fallback preserves spaces, Unicode, and