From ca134bbfb3711447945f2c9653da940557e07b9b Mon Sep 17 00:00:00 2001 From: kongxin Date: Fri, 27 Nov 2026 06:07:26 -0800 Subject: [PATCH] fix(sandbox): keep line endings when str_replace edits a file on AIO (#8662) * fix(sandbox): keep line endings when str_replace edits a file on AIO AioSandbox.read_file read through the AIO /v1/file/read route, which returns text with every CRLF and bare CR turned into LF. str_replace then saw no CRLF, so changing one word in a CRLF file wrote every line back as LF; CR-only and mixed-ending files were rewritten the same way. The write route stores "\r" as given, so only the read was lossy. read_file now reads the stored bytes through the download route and decodes them as UTF-8, so a full read returns line endings as stored, as on the local sandbox since #6343. Ranged reads are sliced with split_file_lines, as on E2B, BoxLite, Tenki and OpenSandbox: the server's ranges also ended lines at a bare CR, form feeds and Unicode separators, and would no longer agree with the start_line a truncated full read suggests. A missing file, a directory, a file the server cannot open and a non-UTF-8 file still return "Error: file not found or unreadable". A file over the 100 MB download limit raises instead: an error string would let str_replace replace text inside it and write it over the file. * fix(sandbox): match str_replace snippets that span mixed line endings A ranged read joins lines with "\n", so an old_str copied from a file that mixes CRLF and LF lines matched neither its literal nor its all-CRLF spelling once read_file returned the stored endings. Match it against the file with CRLF read as LF and replace only the original span, so line endings outside the edited text stay as stored; new_str takes the ending of the span's first line break. HarnessGuard splices through the same helper. * fix(sandbox): block writes over an AIO file too large to read back AioSandbox.read_file raises OSError(EFBIG) for a file over the 100 MB download limit, so that str_replace never writes an error string over it. The read-before-write gate caught that exception in its generic handler and failed open: write_file could replace an existing AIO file over 100 MB without any read, which the gate blocked before, when the read route returned the content. On a live AIO 1.11.0 container, write_file replaced a 110 MB file that had never been read. No read can ever mark such a file, so the gate now returns a blocked result for EFBIG, with the usual write-block metadata, telling the model to use bash instead. This covers write_file, appends and str_replace, on the sync and async paths. Other inspection errors still fail open, and a new file is still created. * fix(sandbox): copy only the selected lines in an AIO ranged read A ranged AIO read_file split the whole downloaded file into a list of every line before slicing. On a 100 MB file of short lines one read peaked at about 2 GB of extra memory in the Gateway; on main the server sliced ranges itself. slice_file_lines returns the same text as joining the split_file_lines slice, with the same clamping, but counts newlines block by block and copies only the selected lines. The same read now needs a few kilobytes and runs in under 0.1 s instead of 1-5 s. A property test checks it against the split-and-join result on random content. * fix(sandbox): match str_replace snippets in file order whatever their line endings str_replace tried the literal and the all-CRLF spelling of old_str over the whole file before it looked for a snippet that spans CRLF and LF lines. When a ranged read spanned mixed endings and the same text recurred later with LF only or CRLF only, a default edit changed the later copy and returned OK, and replace_all left the mixed copy alone. The offset table behind the mixed search also kept one integer per CRLF in the file: 1.6 GB of extra memory for one edit in a 100 MB file of short lines. The matcher now has one rule instead of fallbacks. In a file with CRLF, a CRLF is one line break; a "\r\n" in old_str matches only a CRLF, a "\n" matches either ending, and every other character matches itself. Matches are taken in file order without overlapping, as str.replace takes them. The n-th line break of new_str is written in the ending of the n-th line break inside the match, so an edit that keeps the line count keeps every line's ending, and no match splits a CRLF. A file without CRLF is still matched literally, and a file whose breaks are all CRLF, or an edit without line breaks, still runs as one str.replace, which the tests show gives the same result. Match boundaries are mapped by counting CRLFs forward from the previous match, so the extra memory stays near three times the file (the CRLF-as-LF copy and the output) whatever its newline density: 292 MB for that edit instead of 1.6 GB. An empty old_str is a no-op here too, so the HarnessGuard syntax check no longer blocks an edit that str_replace would not make. Tests: a hypothesis reference model of the rule on files that mix "\r\n", "\n" and "\r", with snippets from ranged reads, full reads and typed text; parity with main on files with one ending; ranged-read snippets are never reported missing; the real str_replace and the HarnessGuard splice against the model. The AIO tests now run the real agent_sandbox client over an httpx transport that serves the download, read and write routes as AIO 1.11.0 does, including the ordering cases and the oversized-file gate. * fix(sandbox): keep ranged reads and str_replace matching linear A ranged read dropped the carriage returns that end each line with the regex \r+(?=\n). On a run of bare \r followed by ordinary text the lookahead failed and the search retried from every \r of the run, so the read was quadratic in its length: 15 s for an 80,000-character run through the AIO SDK. The same sub also built a list with two entries per CRLF line, 220 MiB for a ranged read of a 10 MB CRLF file. The read now turns each \r\n into \n with str.replace, and only when a line ended in several \r does it cut each run with one find and rstrip per such line, writing to a StringIO. Every character is read a fixed number of times, and the result equals joining the split_file_lines slice as before. The str_replace matcher had the same class of problem. A snippet with \r\n was searched with CRLF read as LF and each overlapping candidate was then checked position by position, so a CRLF snippet over many LF lines cost the file length times the snippet length. Accepting a snippet whose \r\n and \n may land on any mix of endings is a subset match, which no forward scan does, so a snippet with \r\n now matches as written or with every line break spelled CRLF, the two spellings main tried, in file order; a leading \n may also be the LF of a CRLF, since such a snippet cannot show the ending of the line before it. A snippet without \r\n, as a ranged read or the model writes it, still matches with each \n as LF or CRLF. Each spelling is found with str.find; only a spelling that ends in a bare \r and occurs right before an LF uses a regex, whose literal prefix re scans with a KMP overlap table, so candidates that would split a CRLF are skipped without rescanning them. Tests: a growth check (tests/support/scaling.py) compares the thread CPU time of a 16x larger adversarial input with a small one and requires under 64x, where linear is about 16x and quadratic 256x. It covers CR runs, CRLF and multi-CR lines for ranged reads, through the real AIO SDK too, and rejected candidates, CR runs and replace_all with many matches for the matcher. The old code fails it at 180x to 277x, a find-and-retry finder at 300x to 400x, and it passed 72 of 72 runs with the CPU four times oversubscribed. The reference model follows the new rule, a full-read snippet that does not split a CRLF is never reported missing, and the ranged-read property test draws runs of \r. --- .../middlewares/harness_guard_middleware.py | 8 +- .../read_before_write_middleware.py | 24 +- .../deerflow/community/aio_sandbox/AGENTS.md | 10 +- .../community/aio_sandbox/aio_sandbox.py | 68 +++- .../deerflow/sandbox/read_file_contract.py | 64 +++ .../harness/deerflow/sandbox/tools.py | 190 +++++++-- backend/tests/support/scaling.py | 46 +++ backend/tests/test_aio_sandbox.py | 382 +++++++++++++++--- .../tests/test_harness_guard_middleware.py | 86 ++++ .../test_read_before_write_middleware.py | 46 +++ .../test_remote_read_file_line_numbers.py | 30 ++ backend/tests/test_sandbox_line_endings.py | 305 +++++++++++++- docs/guide/sandbox.md | 6 +- 13 files changed, 1159 insertions(+), 106 deletions(-) create mode 100644 backend/tests/support/scaling.py diff --git a/backend/packages/harness/deerflow/agents/middlewares/harness_guard_middleware.py b/backend/packages/harness/deerflow/agents/middlewares/harness_guard_middleware.py index f8003d2889..2ac4b7c62d 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/harness_guard_middleware.py +++ b/backend/packages/harness/deerflow/agents/middlewares/harness_guard_middleware.py @@ -35,7 +35,7 @@ from deerflow.agents.middlewares.tool_result_meta import ( ) from deerflow.agents.middlewares.tool_transform_meta import append_tool_transform from deerflow.config.harness_guard_config import HarnessGuardConfig -from deerflow.sandbox.tools import _match_line_endings, read_current_file_content +from deerflow.sandbox.tools import _replace_keeping_line_endings, read_current_file_content logger = logging.getLogger(__name__) @@ -287,10 +287,8 @@ class HarnessGuardMiddleware(AgentMiddleware): if isinstance(old_str, str) and isinstance(new_str, str) and (file_path.endswith(".py") or file_path.endswith(".json")): try: current = read_current_file_content(request.runtime, file_path) - old_str, new_str = _match_line_endings(current, old_str, new_str) - if old_str in current and verify_content_syntax(file_path, current) is None: - replace_all = bool(args.get("replace_all", False)) - spliced = current.replace(old_str, new_str) if replace_all else current.replace(old_str, new_str, 1) + spliced = _replace_keeping_line_endings(current, old_str, new_str, bool(args.get("replace_all", False))) + if spliced is not None and verify_content_syntax(file_path, current) is None: err = verify_content_syntax(file_path, spliced) except Exception: # Fail open on sandbox read errors and let str_replace handle execution diff --git a/backend/packages/harness/deerflow/agents/middlewares/read_before_write_middleware.py b/backend/packages/harness/deerflow/agents/middlewares/read_before_write_middleware.py index 20e1c6adfe..2f917db4f7 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/read_before_write_middleware.py +++ b/backend/packages/harness/deerflow/agents/middlewares/read_before_write_middleware.py @@ -35,6 +35,7 @@ Design invariants: """ import asyncio +import errno import hashlib import logging import posixpath @@ -85,6 +86,7 @@ _ELIDED_PAYLOAD_TEMPLATE = "[payload elided: {chars} chars; this {tool_name} cal _UNINSPECTABLE_CONTENT_PREFIX = "Error:" _BLOCK_MESSAGE = "Error: {tool_name} blocked — {path} already exists ({line_desc}) and you have not read its current version. Any write invalidates earlier reads, so re-read before every modification. {read_hint}" +_TOO_LARGE_MESSAGE = "Error: {tool_name} blocked — {path} already exists and is too large to read, so its current version cannot be checked ({detail}). Inspect or change it with bash instead." # Per-(scope, path) locks serializing gate check + tool execution. Same @@ -347,6 +349,7 @@ class ReadBeforeWriteMiddleware(AgentMiddleware): path = self._requested_path(request) if path is None: return None + tool_name = str(tool_call.get("name", "write")) try: current = self._content_reader(request.runtime, path) except FileNotFoundError: @@ -354,7 +357,13 @@ class ReadBeforeWriteMiddleware(AgentMiddleware): return None except SandboxAuthorizationError: raise - except Exception: + except Exception as exc: + if isinstance(exc, OSError) and exc.errno == errno.EFBIG: + # The file exists but is over the read limit, so read_file can + # never stamp a mark for it: failing open here would let + # write_file replace it unread. + detail = exc.strerror or str(exc) + return self._blocked_result(tool_call, path, _TOO_LARGE_MESSAGE.format(tool_name=tool_name, path=path, detail=detail)) logger.warning("read-before-write gate could not inspect %r; allowing the write (fail-open)", path, exc_info=True) return None if current.startswith(_UNINSPECTABLE_CONTENT_PREFIX): @@ -366,7 +375,6 @@ class ReadBeforeWriteMiddleware(AgentMiddleware): norm_path = _normalize_mark_path(path) if self._latest_mark_hash(request.state, norm_path) == _content_hash(current): return None - tool_name = str(tool_call.get("name", "write")) # count_file_lines matches LocalSandbox.read_file line numbering and the # truncation-marker formula in _truncate_read_file_output, so the number # reported here agrees with start_line/end_line the model can pass back. @@ -378,13 +386,18 @@ class ReadBeforeWriteMiddleware(AgentMiddleware): else: start = max(1, line_count - 29) read_hint = f"Call read_file on it first (e.g. start_line={start}, end_line={line_count}), check what is already there, then retry." - blocked = ToolMessage( - content=_BLOCK_MESSAGE.format(tool_name=tool_name, path=path, line_desc=line_desc, read_hint=read_hint), + return self._blocked_result(tool_call, path, _BLOCK_MESSAGE.format(tool_name=tool_name, path=path, line_desc=line_desc, read_hint=read_hint)) + + @staticmethod + def _blocked_result(tool_call: dict[str, Any], path: str, content: str) -> ToolMessage: + tool_name = str(tool_call.get("name", "write")) + return ToolMessage( + content=content, tool_call_id=str(tool_call.get("id", "")), name=tool_name, status="error", additional_kwargs={ - WRITE_BLOCK_KEY: {"path": norm_path, "tool": tool_name}, + WRITE_BLOCK_KEY: {"path": _normalize_mark_path(path), "tool": tool_name}, # Pre-stamp gate metadata so normalize_tool_result's text heuristics # cannot misclassify a numeric line count (e.g. 401, 403, 500) as an # HTTP error code. normalize_tool_message returns early when an @@ -398,7 +411,6 @@ class ReadBeforeWriteMiddleware(AgentMiddleware): }, }, ) - return blocked @staticmethod def _requested_path(request: ToolCallRequest) -> str | None: diff --git a/backend/packages/harness/deerflow/community/aio_sandbox/AGENTS.md b/backend/packages/harness/deerflow/community/aio_sandbox/AGENTS.md index c341b10bb0..aaa480027f 100644 --- a/backend/packages/harness/deerflow/community/aio_sandbox/AGENTS.md +++ b/backend/packages/harness/deerflow/community/aio_sandbox/AGENTS.md @@ -68,8 +68,14 @@ make test-blocking-io only the children first lets it run the rest of the command. - **Broker logs carry argument count, exit code and duration**, never argument values. -- **`read_file` returns content or an `Error: ...` string and never raises.** A - missing file is expected when a write probes first, and is logged at debug. +- **`read_file` returns content or an `Error: ...` string.** A missing file is + expected when a write probes first, and is logged at debug. Only a file over + the download limit raises `EFBIG`: `str_replace` would replace text inside an + error string and write it over the file. The read-before-write gate blocks on + `EFBIG` instead of failing open, because no read can ever mark that file. +- **`read_file` reads the download route, not `/v1/file/read`.** That route + turns every line ending into `\n` and splits ranges at a bare `\r` too, so + `str_replace` would write a CRLF file back as LF. ## Restricted network mode diff --git a/backend/packages/harness/deerflow/community/aio_sandbox/aio_sandbox.py b/backend/packages/harness/deerflow/community/aio_sandbox/aio_sandbox.py index a5f3722da2..de208f2fbe 100644 --- a/backend/packages/harness/deerflow/community/aio_sandbox/aio_sandbox.py +++ b/backend/packages/harness/deerflow/community/aio_sandbox/aio_sandbox.py @@ -1,4 +1,5 @@ import base64 +import errno import json import logging import math @@ -11,12 +12,12 @@ from dataclasses import dataclass, field import httpx from agent_sandbox import Sandbox as AioSandboxClient from agent_sandbox.core.api_error import ApiError -from pydantic import ValidationError from deerflow.config.paths import VIRTUAL_PATH_PREFIX from deerflow.sandbox.command_scope import COMMAND_OWNER_ENV, CommandScopeCancelled, command_lock, current_command_scope from deerflow.sandbox.download import DEFAULT_DOWNLOAD_LIMIT as _MAX_DOWNLOAD_SIZE from deerflow.sandbox.download import download_limit, read_download_stream +from deerflow.sandbox.read_file_contract import slice_file_lines from deerflow.sandbox.remote_list_dir import parse_remote_list_dir_output, remote_list_dir_command from deerflow.sandbox.sandbox import Sandbox, _validate_extra_env from deerflow.sandbox.search import GrepMatch, path_matches, should_ignore_path_under_root, truncate_line @@ -1208,33 +1209,62 @@ class AioSandbox(Sandbox): ) -> str: """Read the content of a file in the sandbox. + A full read returns line endings as stored. A ranged read ends lines + only at ``"\\n"``, drops the ``"\\r"`` characters that end a line and + joins the selected lines with ``"\\n"``, as ``LocalSandbox.read_file`` + does. + Args: path: The absolute path of the file to read. + start_line: Optional starting line number (1-indexed, inclusive). + end_line: Optional ending line number (1-indexed, inclusive). Returns: - The content of the file. + The content of the file, or an ``Error: ...`` string. + + Raises: + OSError: If the file is larger than the download limit. """ + unreadable = f"Error: file not found or unreadable: {path}" try: - kwargs = {} - if start_line is not None: - kwargs["start_line"] = max(start_line - 1, 0) - if end_line is not None: - kwargs["end_line"] = max(end_line, 0) - result = self._client.file.read_file(file=path, **kwargs) - return result.data.content if result.data else "" - except ValidationError as e: - # The server reports read failures (e.g. ENOENT) as an error - # envelope with ``data: {}``, which cannot satisfy the required - # ``content``/``file`` fields of the SDK's FileReadResult model, - # so the SDK raises a ValidationError. A missing file is an - # expected outcome (ReadBeforeWrite probes every new-file write), - # so log quietly and return an explicit, model-actionable result - # instead of leaking the pydantic error text. - logger.debug("Sandbox read_file validation failure for %r: %s", path, e) - return f"Error: file not found or unreadable: {path}" + # /v1/file/read turns every line ending into "\n", so str_replace + # wrote a CRLF file back as LF, and its line ranges also end at a + # bare "\r", \f and Unicode separators. The download route returns + # the stored bytes. No self._lock: it would make a read wait for a + # running shell command, and a read cut off by close() still ends + # in an error result below. + content = read_download_stream(self._client.file.download_file(path=path), _MAX_DOWNLOAD_SIZE, path).decode("utf-8") + except ApiError as e: + if e.status_code in (400, 404): + # 404 is a missing file, an expected outcome because + # ReadBeforeWrite probes every new-file write; 400 is a + # directory. Log quietly and return a model-actionable result. + logger.debug("Sandbox read_file of %r returned HTTP %s", path, e.status_code) + return unreadable + logger.error("Failed to read file %r in sandbox: HTTP %s", path, e.status_code) + return f"Error: failed to read {path} (HTTP {e.status_code})" + except httpx.RemoteProtocolError as e: + # The server sends the response headers before it opens the file, + # so a file it may not read (e.g. root-owned) ends the body early. + logger.warning("Sandbox read_file of %r ended early: %s", path, e) + return unreadable + except UnicodeDecodeError: + logger.debug("Sandbox read_file of %r is not UTF-8 text", path) + return unreadable + except OSError as e: + if e.errno == errno.EFBIG: + # Raise instead of returning an error string: str_replace + # would replace text inside the string and write it over the + # file whenever old_str happens to occur in it. + raise OSError(errno.EFBIG, f"File is larger than {_MAX_DOWNLOAD_SIZE // (1024 * 1024)} MB; read part of it with bash (head, tail or sed -n)", path) from None + logger.error(f"Failed to read file in sandbox: {e}") + return f"Error: {e}" except Exception as e: logger.error(f"Failed to read file in sandbox: {e}") return f"Error: {e}" + if start_line is None and end_line is None: + return content + return slice_file_lines(content, start_line, end_line) def download_file(self, path: str, *, max_bytes: int | None = None) -> bytes: """Download file bytes from the sandbox. diff --git a/backend/packages/harness/deerflow/sandbox/read_file_contract.py b/backend/packages/harness/deerflow/sandbox/read_file_contract.py index 7d4396bcb9..34b29f0886 100644 --- a/backend/packages/harness/deerflow/sandbox/read_file_contract.py +++ b/backend/packages/harness/deerflow/sandbox/read_file_contract.py @@ -1,5 +1,7 @@ """Text markers shared by read_file and its display-only consumers.""" +import io + READ_FILE_EMPTY = "(empty)" READ_FILE_START_LINE_EXCEEDS = "(start_line exceeds file length)" READ_FILE_INVALID_START_LINE = "(start_line must be >= 1)" @@ -54,3 +56,65 @@ def split_file_lines(content: str) -> list[str]: if lines[-1] == "": lines.pop() return [line.rstrip("\r") for line in lines] + + +def _line_start(content: str, line: int, pos: int = 0, at: int = 1) -> int: + """Offset where 1-indexed ``line`` starts, counting from line ``at`` at ``pos``; -1 past the end.""" + remaining = line - at + while remaining > 0: + block_end = min(pos + 65536, len(content)) + newlines = content.count("\n", pos, block_end) + if newlines < remaining: + if block_end == len(content): + return -1 + remaining -= newlines + pos = block_end + continue + for _ in range(remaining): + pos = content.index("\n", pos) + 1 + remaining = 0 + return pos + + +def slice_file_lines(content: str, start_line: int | None = None, end_line: int | None = None) -> str: + """Return lines ``start_line``-``end_line`` of ``content`` as a ranged ``read_file`` does. + + The result equals joining ``split_file_lines(content)[start - 1 : end]`` + with ``"\\n"``, with ``start`` and ``end`` clamped as ``LocalSandbox.read_file`` + clamps them, but only the selected lines are copied: splitting a large, + newline-dense file into a list of every line takes many times its size. + """ + start = max(start_line or 1, 1) + if end_line is not None and end_line < start: + return "" + begin = _line_start(content, start) + if begin < 0 or begin >= len(content): + return "" + stop = len(content) if end_line is None else _line_start(content, end_line + 1, begin, start) + text = content[begin : stop if stop >= 0 else len(content)] + if text.endswith("\n"): + text = text[:-1] + return _drop_line_end_crs(text).rstrip("\r") + + +def _drop_line_end_crs(text: str) -> str: + """Drop every run of ``"\\r"`` that sits directly before a ``"\\n"``. + + Every character is read a fixed number of times, so the time is linear + however long a run of ``"\\r"`` is and whatever follows it, and the + output is built as one string, never as a list of lines. + """ + # One CR before each LF: the usual CRLF line, handled in C. + text = text.replace("\r\n", "\n") + if "\r\n" not in text: + return text + # A line ended in two or more CRs. Each remaining CRLF ends such a run: + # cut the run off the text before it and keep the LF. + out = io.StringIO() + pos = 0 + while (crlf := text.find("\r\n", pos)) >= 0: + out.write(text[pos:crlf].rstrip("\r")) + out.write("\n") + pos = crlf + 2 + out.write(text[pos:]) + return out.getvalue() diff --git a/backend/packages/harness/deerflow/sandbox/tools.py b/backend/packages/harness/deerflow/sandbox/tools.py index 9d346d483a..c831a02f42 100644 --- a/backend/packages/harness/deerflow/sandbox/tools.py +++ b/backend/packages/harness/deerflow/sandbox/tools.py @@ -1,4 +1,5 @@ import asyncio +import io import json import logging import ntpath @@ -3598,25 +3599,172 @@ async def _write_file_tool_async( write_file_tool.coroutine = _write_file_tool_async -def _to_crlf(text: str) -> str: - return text.replace("\r\n", "\n").replace("\n", "\r\n") +def _replace_keeping_line_endings(content: str, old_str: str, new_str: str, replace_all: bool) -> str | None: + """Return ``content`` with ``old_str`` replaced, or None when it is absent. + A file without CRLF is matched and written literally. In a file with CRLF, + a CRLF is one line break, and a match never starts or ends between its + ``\\r`` and ``\\n``. An ``old_str`` without ``\\r\\n``, as a ranged read + (lines joined with ``\\n``) or the model writes it, matches with each + ``\\n`` read as an LF or a CRLF and every other character, ``\\r`` + included, matching itself. An ``old_str`` with ``\\r\\n``, as copied from + a full read, matches as written or with every line break spelled CRLF; a + leading ``\\n`` may also be the LF of a CRLF. + Matches are taken in file order without overlapping, as ``str.replace`` + takes them: the first one, or every one with ``replace_all``. The n-th line + break of ``new_str`` is written in the ending of the n-th line break inside + the match, and later ones in the ending of the last; a match without a line + break lends the ending of the line it is on (on a last line without one, + the line before). Everything outside the matches keeps its bytes. -def _match_line_endings(content: str, old_str: str, new_str: str) -> tuple[str, str]: - """Spell ``old_str`` and ``new_str`` with the CRLF line endings ``content`` uses. - - Full reads return line endings as stored, but the model tends to write - ``\\n`` (and ranged reads join lines with ``\\n``), so a multi-line - ``old_str`` would never match a CRLF file and inserted lines would be LF. - A CRLF-only file takes both strings in CRLF; a mixed file does so only - when the LF spelling is absent and the CRLF one is present. + Every search is a fixed number of forward scans of ``content``, so the + time is linear in the file and the snippet whatever they contain. That is why a snippet that + itself mixes ``\\r\\n`` and ``\\n`` does not also match lines that mix their + endings in another way: that search is a subset match, which no forward + scan does, and checking each overlapping candidate in turn is quadratic. """ - if "\r\n" not in content: - return old_str, new_str - crlf_old = _to_crlf(old_str) - if content.count("\r\n") == content.count("\n") or (old_str not in content and crlf_old in content): - return crlf_old, _to_crlf(new_str) - return old_str, new_str + if not old_str: + # str_replace treats an empty old_str as a no-op edit. + return content + count = -1 if replace_all else 1 + if "\r\n" not in content or not ("\r" in old_str or "\n" in old_str or "\n" in new_str): + # Without CRLF in the file, or without a line break or CR on either + # side, the rule above matches and writes exactly as str.replace. + return content.replace(old_str, new_str, count) if old_str in content else None + flat_old = old_str.replace("\r\n", "\n") + lf_new = new_str.replace("\r\n", "\n") + if content.count("\r\n") == content.count("\n") and not flat_old.endswith("\r"): + # Every line break is a CRLF, so the CRLF spelling of old_str finds the + # same matches in place. Only a trailing bare "\r" could differ, by + # matching the "\r" of a CRLF, and that case takes the general path. + crlf_old = flat_old.replace("\n", "\r\n") + return content.replace(crlf_old, lf_new.replace("\n", "\r\n"), count) if crlf_old in content else None + if "\r\n" not in old_str: + spans = _flat_spans(content, flat_old) + else: + spans = _spelled_spans(content, old_str, flat_old.replace("\n", "\r\n")) + return _splice_keeping_line_endings(content, spans, lf_new, count) + + +def _flat_spans(content: str, flat_old: str) -> Iterator[tuple[int, int]]: + """Yield, in file order and without overlap, the spans of ``content`` that read as ``flat_old`` with CRLF read as LF.""" + flat = content.replace("\r\n", "\n") + # content[:pos] reads as flat[:flat_pos]. Matches arrive in file order, so + # each step counts only the CRLFs since the previous one: linear time and + # no per-line bookkeeping. + pos = flat_pos = 0 + index = flat.find(flat_old) + while index >= 0: + bounds = [] + for target in (index, index + len(flat_old)): + while True: + end = pos + target - flat_pos + crlfs = content.count("\r\n", pos, end) + if end > pos and content[end - 1] == "\r" and content.startswith("\n", end): + # A CRLF is one flat character: never stop between its \r and \n. + crlfs += 1 + end += 1 + flat_pos += end - pos - crlfs + pos = end + if not crlfs: + break + bounds.append(pos) + yield bounds[0], bounds[1] + index = flat.find(flat_old, index + len(flat_old)) + + +def _spelled_spans(content: str, *spellings: str) -> Iterator[tuple[int, int]]: + """Yield, in file order and without overlap, the spans of ``content`` spelled as one of ``spellings``.""" + finders = [_crlf_safe_finder(content, spelling) for spelling in dict.fromkeys(spellings)] + found = [find(0) for find in finders] + while spans := [span for span in found if span is not None]: + start, stop = min(spans) + yield start, stop + # Two spellings that match at the same offset match the same text: + # elsewhere they differ where one has "\n" and the other "\r\n". A + # finder searches again only when its next match overlaps the one + # just taken, from where that ends. + found = [span if span is None or span[0] >= stop else find(stop) for span, find in zip(found, finders)] + + +def _crlf_safe_finder(content: str, spelling: str) -> Callable[[int], tuple[int, int] | None]: + """Return a function that finds ``spelling`` in ``content`` from an offset, never splitting a CRLF. + + Inside a match, the spelling's own characters already tell a CRLF from a + bare ``\\r`` or LF; only its first and last character can meet half a + CRLF of the file. A leading ``\\n`` may be the LF of a CRLF, and the match + then starts at that CRLF's ``\\r``. A trailing ``\\r`` must not be the CR + of a CRLF. + """ + if spelling.endswith("\r") and spelling + "\n" in content: + # Skipping a candidate that ends on the CR of a CRLF and searching + # again from the next offset rescans the overlap of every skipped + # candidate, which is quadratic. re scans a pattern whose literal + # prefix is the whole spelling with a KMP overlap table, and checks the + # lookahead once per candidate. Compiling costs time linear in the + # spelling, so plain str.find serves every file where no candidate + # can be skipped. + regex = re.compile(re.escape(spelling) + r"(?!\n)") + + def locate(pos: int) -> int: + match = regex.search(content, pos) + return match.start() if match else -1 + + else: + + def locate(pos: int) -> int: + return content.find(spelling, pos) + + def find(pos: int) -> tuple[int, int] | None: + index = locate(pos) + if index < 0: + return None + start = index - 1 if spelling.startswith("\n") and index > 0 and content[index - 1] == "\r" else index + return start, index + len(spelling) + + return find + + +def _splice_keeping_line_endings(content: str, spans: Iterator[tuple[int, int]], lf_new: str, count: int) -> str | None: + """Replace the first ``count`` of ``spans`` (all when negative) with ``lf_new`` in their line endings.""" + new_lines = lf_new.split("\n") + out = io.StringIO() + copied = 0 + line_end = -1 + line_crlf = False + found = False + for start, stop in spans: + found = True + endings: list[str] = [] + at = start + while len(endings) < len(new_lines) - 1: + at = content.find("\n", at, stop) + 1 + if not at: + break + endings.append("\r\n" if content[at - 2 : at] == "\r\n" else "\n") + if not endings and len(new_lines) > 1: + if start > line_end: + line_end = content.find("\n", start) + if line_end < 0: + line_end = len(content) + line_break = content.rfind("\n", 0, start) + else: + line_break = line_end + line_crlf = line_break > 0 and content[line_break - 1] == "\r" + endings.append("\r\n" if line_crlf else "\n") + out.write(content[copied:start]) + out.write(new_lines[0]) + for n, line in enumerate(new_lines[1:]): + out.write(endings[min(n, len(endings) - 1)]) + out.write(line) + copied = stop + count -= 1 + if not count: + break + if not found: + return None + out.write(content[copied:]) + return out.getvalue() @tool("str_replace", parse_docstring=True) @@ -3657,14 +3805,10 @@ def str_replace_tool( # A no-op edit. str.replace("", new_str) would insert new_str at # every character boundary, so this cannot fall through. return "OK" - old_str, new_str = _match_line_endings(content, old_str, new_str) - if not content or old_str not in content: + replaced = _replace_keeping_line_endings(content, old_str, new_str, replace_all) + if replaced is None: return f"Error: String to replace not found in file: {requested_path}" - if replace_all: - content = content.replace(old_str, new_str) - else: - content = content.replace(old_str, new_str, 1) - sandbox.write_file(path, content) + sandbox.write_file(path, replaced) return "OK" except SandboxCapacityExceededError as e: return _sandbox_capacity_result(runtime, e, "str_replace") diff --git a/backend/tests/support/scaling.py b/backend/tests/support/scaling.py new file mode 100644 index 0000000000..3bb968c0d5 --- /dev/null +++ b/backend/tests/support/scaling.py @@ -0,0 +1,46 @@ +"""Growth-rate check for scans that must stay linear on adversarial input. + +A fixed time limit passes on a fast machine and fails on a loaded runner, so +``growth`` compares the same call on a small and a large input instead. Time is +the CPU time of the calling thread, which does not count while other processes +hold the core, and each size is the best of several samples that repeat the +call for a few milliseconds. Over a 16x larger input a linear scan grows about +16x (less when fixed costs dominate the small input) and a quadratic one about +256x. +""" + +from __future__ import annotations + +import gc +import time +from collections.abc import Callable + +SCALE = 16 +# Four times the linear growth and a quarter of the quadratic one. +LINEAR_LIMIT = 64 + + +def _best_time(call: Callable[[], object], *, samples: int, sample_seconds: float = 0.005) -> float: + repeats = 1 + while True: + started = time.thread_time() + for _ in range(repeats): + call() + if time.thread_time() - started >= sample_seconds or repeats >= 1 << 12: + break + repeats *= 4 + best = float("inf") + for _ in range(samples): + gc.collect() + started = time.thread_time() + for _ in range(repeats): + call() + best = min(best, (time.thread_time() - started) / repeats) + return best + + +def growth(run: Callable[[int], object], size: int) -> float: + """Return how much more CPU time ``run(size * SCALE)`` takes than ``run(size)``.""" + small = _best_time(lambda: run(size), samples=5) + large = _best_time(lambda: run(size * SCALE), samples=3) + return large / small diff --git a/backend/tests/test_aio_sandbox.py b/backend/tests/test_aio_sandbox.py index 90fda81e48..fb7445c628 100644 --- a/backend/tests/test_aio_sandbox.py +++ b/backend/tests/test_aio_sandbox.py @@ -1,16 +1,20 @@ """Tests for AioSandbox concurrent command serialization (#1433).""" +import errno +import json import logging import os import shlex import subprocess import sys import threading +from collections.abc import Iterator from types import SimpleNamespace from unittest.mock import MagicMock, patch import httpx import pytest +from support.scaling import LINEAR_LIMIT, growth class _TeardownFirstScopeLock: @@ -2740,18 +2744,318 @@ class TestNoChangeTimeout: assert calls[0].get("no_change_timeout") == sandbox._DEFAULT_NO_CHANGE_TIMEOUT +class _AioFileRoutes: + """The AIO file routes as observed on AIO 1.11.0, served under the real SDK. + + ``/v1/file/read`` turns ``\\r\\n`` and ``\\r`` into ``\\n``. ``/v1/file/download`` + streams the stored bytes, answers 404 for a missing path and 400 for a + directory. ``/v1/file/write`` stores the JSON ``content`` as given, ``\\r`` + included. ``streams`` serves a path from an iterator of chunks instead, to + observe how much of a large or broken body the client consumed, and + ``failures`` makes a download of a path fail in the transport. + """ + + def __init__(self) -> None: + self.files: dict[str, bytes] = {} + self.streams: dict[str, Iterator[bytes]] = {} + self.failures: dict[str, type[httpx.TransportError]] = {} + self.routes: list[str] = [] + + @staticmethod + def _envelope(status: int, message: str, data=None) -> httpx.Response: + return httpx.Response(status, json={"success": status == 200, "message": message, "data": data, "hint": None}) + + def __call__(self, request: httpx.Request) -> httpx.Response: + route = request.url.path + self.routes.append(route) + if route == "/v1/file/download": + path = request.url.params["path"] + if path in self.failures: + raise self.failures[path]("connection reset", request=request) + if path in self.streams: + return httpx.Response(200, headers={"content-type": "application/octet-stream"}, content=self.streams.pop(path)) + if path in self.files: + return httpx.Response(200, headers={"content-type": "application/octet-stream"}, content=self.files[path]) + if any(name.startswith(path.rstrip("/") + "/") for name in self.files): + return self._envelope(400, f"Path is not a file: {path}") + return self._envelope(404, f"File does not exist: {path}") + body = json.loads(request.content) + if route == "/v1/file/write": + data = body["content"].encode("utf-8") + self.files[body["file"]] = self.files.get(body["file"], b"") + data if body.get("append") else data + return self._envelope(200, "File written successfully", {"file": body["file"], "bytes_written": len(data)}) + if route == "/v1/file/read": + text = self.files[body["file"]].decode("utf-8").replace("\r\n", "\n").replace("\r", "\n") + return self._envelope(200, "File read successfully", {"content": text, "file": body["file"]}) + return self._envelope(404, "Not Found") + + +@pytest.fixture() +def aio_files(monkeypatch): + """An ``AioSandbox`` whose real SDK client talks to ``_AioFileRoutes``, with the sandbox tools bound to it.""" + from agent_sandbox import Sandbox as RealSdkClient + + import deerflow.community.aio_sandbox.aio_sandbox as aio_module + + routes = _AioFileRoutes() + transport_client = httpx.Client(transport=httpx.MockTransport(routes), follow_redirects=True) + monkeypatch.setattr(aio_module, "AioSandboxClient", lambda **kwargs: RealSdkClient(**{**kwargs, "httpx_client": transport_client})) + sandbox = aio_module.AioSandbox(id="test-sandbox", base_url="http://localhost:8080") + monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized", lambda runtime: sandbox) + monkeypatch.setattr("deerflow.sandbox.tools.ensure_thread_directories_exist", lambda runtime: None) + monkeypatch.setattr("deerflow.sandbox.tools.is_local_sandbox", lambda runtime: False) + try: + yield sandbox, routes + finally: + transport_client.close() + + +def _tool_runtime() -> SimpleNamespace: + return SimpleNamespace(state={"sandbox": {"sandbox_id": "test-sandbox"}}, context={"thread_id": "t1"}) + + class TestReadFile: - def test_read_file_forwards_requested_line_range(self, sandbox): - sandbox._client.file.read_file = MagicMock(return_value=SimpleNamespace(data=SimpleNamespace(content="line 1\nline 2"))) + """``/v1/file/read`` turns every line ending into "\\n" and its ranges also + end lines at a bare "\\r", \\f and Unicode separators. ``read_file`` takes the + stored bytes from the download route instead and slices ranges like + ``LocalSandbox``, so a full read returns the endings as stored and a ranged + read numbers the lines that ``count_file_lines`` counts.""" - result = sandbox.read_file("/mnt/user-data/workspace/huge.log", start_line=1, end_line=10) + def test_read_file_returns_line_endings_as_stored(self, aio_files): + sandbox, routes = aio_files + routes.files["/mnt/user-data/workspace/run.bat"] = b"a\r\nb\rc\n" - assert result == "line 1\nline 2" - sandbox._client.file.read_file.assert_called_once_with( - file="/mnt/user-data/workspace/huge.log", - start_line=0, - end_line=10, - ) + assert sandbox.read_file("/mnt/user-data/workspace/run.bat") == "a\r\nb\rc\n" + assert routes.routes == ["/v1/file/download"] + + @pytest.mark.parametrize( + ("stored", "start_line", "end_line", "expected"), + [ + pytest.param(b"one\r\ntwo\r\nthree\r\n", 2, 3, "two\nthree", id="crlf"), + pytest.param(b"one\rtwo\nthree\n", 2, 2, "three", id="bare-cr-is-not-a-line-end"), + pytest.param("one
two\fx\nthree\n".encode(), 1, 1, "one
two\fx", id="unicode-separators"), + pytest.param(b"one\ntwo\n", 3, None, "", id="past-the-end"), + pytest.param(b"one\ntwo\n", None, 1, "one", id="end-only"), + pytest.param(b"a\n" + b"\r" * 5 + b"x\n", 2, 2, "\r" * 5 + "x", id="cr-run-then-text"), + pytest.param(b"a\r\r\r\nb\r\n", 1, 2, "a\nb", id="several-crs-end-a-line"), + ], + ) + def test_ranged_read_file_ends_lines_only_at_lf(self, aio_files, stored, start_line, end_line, expected): + sandbox, routes = aio_files + routes.files["/mnt/user-data/workspace/f.txt"] = stored + + assert sandbox.read_file("/mnt/user-data/workspace/f.txt", start_line=start_line, end_line=end_line) == expected + assert routes.routes == ["/v1/file/download"] + + def test_a_ranged_read_scans_a_run_of_carriage_returns_once(self, aio_files): + # A run of "\r" followed by text made the ranged read quadratic in the + # length of the run. + sandbox, routes = aio_files + + def ranged_read(n: int) -> str: + routes.files["/mnt/user-data/workspace/progress.log"] = b"a\n" + b"\r" * n + b"x\n" + return sandbox.read_file("/mnt/user-data/workspace/progress.log", start_line=1, end_line=2) + + assert ranged_read(3) == "a\n\r\r\rx" + assert growth(ranged_read, 4000) < LINEAR_LIMIT + + def test_read_file_reads_paths_outside_user_data(self, aio_files): + # download_file() refuses paths outside /mnt/user-data; read_file must + # keep reading skills and custom mounts. + sandbox, routes = aio_files + routes.files["/mnt/skills/custom/x/SKILL.md"] = b"---\r\nname: x\r\n" + + assert sandbox.read_file("/mnt/skills/custom/x/SKILL.md") == "---\r\nname: x\r\n" + + def test_read_file_does_not_wait_for_a_running_command(self, aio_files): + sandbox, routes = aio_files + routes.files["/mnt/user-data/workspace/f.txt"] = b"ok" + results: list[str] = [] + + with sandbox._lock: + # A read that waited for the lock would park here; fail instead of hanging. + reader = threading.Thread(target=lambda: results.append(sandbox.read_file("/mnt/user-data/workspace/f.txt")), daemon=True) + reader.start() + reader.join(timeout=10) + finished = not reader.is_alive() + reader.join() + + assert finished + assert results == ["ok"] + + def test_an_oversized_file_raises_without_reading_the_rest(self, aio_files, monkeypatch): + import deerflow.community.aio_sandbox.aio_sandbox as aio_module + + sandbox, routes = aio_files + monkeypatch.setattr(aio_module, "_MAX_DOWNLOAD_SIZE", 4 * 1024 * 1024) + chunks = iter([b"x" * (3 * 1024 * 1024), b"x" * (3 * 1024 * 1024), b"never read"]) + routes.streams["/mnt/user-data/workspace/huge.log"] = chunks + + with pytest.raises(OSError, match="larger than 4 MB; read part of it with bash") as raised: + sandbox.read_file("/mnt/user-data/workspace/huge.log", start_line=1, end_line=10) + assert raised.value.errno == errno.EFBIG + assert next(chunks) == b"never read" + + def test_read_file_reports_a_binary_file_as_unreadable(self, aio_files): + sandbox, routes = aio_files + routes.files["/mnt/user-data/uploads/a.bin"] = b"\xafI~m\xd3" + + assert sandbox.read_file("/mnt/user-data/uploads/a.bin") == "Error: file not found or unreadable: /mnt/user-data/uploads/a.bin" + + def test_read_file_reports_a_directory_as_unreadable(self, aio_files): + sandbox, routes = aio_files + routes.files["/mnt/user-data/workspace/dir/inner.txt"] = b"x" + + assert sandbox.read_file("/mnt/user-data/workspace/dir") == "Error: file not found or unreadable: /mnt/user-data/workspace/dir" + + def test_read_file_reports_a_file_the_server_cannot_open_as_unreadable(self, aio_files): + # The server sends headers before it opens the file, so a root-owned + # file ends the response body early. + def cut_off(): + raise httpx.RemoteProtocolError("peer closed connection without sending complete message body (received 0 bytes, expected 7)") + yield b"" + + sandbox, routes = aio_files + routes.streams["/mnt/user-data/workspace/root600.txt"] = cut_off() + + assert sandbox.read_file("/mnt/user-data/workspace/root600.txt") == "Error: file not found or unreadable: /mnt/user-data/workspace/root600.txt" + + +_AIO_PATH = "/mnt/user-data/outputs/f.txt" + + +def _aio_str_replace(old_str: str, new_str: str, replace_all: bool = False, path: str = _AIO_PATH): + from deerflow.sandbox.tools import str_replace_tool + + return str_replace_tool.func(runtime=_tool_runtime(), description="d", path=path, old_str=old_str, new_str=new_str, replace_all=replace_all) + + +def _aio_ranged_read(start_line: int, end_line: int) -> str: + from deerflow.sandbox.tools import read_file_tool + + return read_file_tool.func(runtime=_tool_runtime(), path=_AIO_PATH, start_line=start_line, end_line=end_line) + + +@pytest.mark.parametrize( + ("stored", "old_str", "new_str", "expected"), + [ + pytest.param(b"@echo off\r\nset NAME=old\r\necho %NAME%\r\n", "old", "new", b"@echo off\r\nset NAME=new\r\necho %NAME%\r\n", id="crlf"), + pytest.param(b"one\rtwo old\rthree\r", "old", "new", b"one\rtwo new\rthree\r", id="cr-only"), + pytest.param(b"one\r\ntwo old\nthree\rfour", "old", "new", b"one\r\ntwo new\nthree\rfour", id="mixed"), + pytest.param(b"one\ntwo old\nthree\n", "old", "new", b"one\ntwo new\nthree\n", id="lf"), + pytest.param(b"first\r\nsecond\r\n", "first\nsecond", "1\n2", b"1\r\n2\r\n", id="crlf-multiline-lf-old-str"), + ], +) +def test_str_replace_on_aio_keeps_the_file_line_endings(aio_files, stored, old_str, new_str, expected): + _, routes = aio_files + routes.files[_AIO_PATH] = stored + + assert _aio_str_replace(old_str, new_str) == "OK" + assert routes.files[_AIO_PATH] == expected + assert routes.routes == ["/v1/file/download", "/v1/file/write"] + + +@pytest.mark.parametrize( + ("stored", "lines", "first", "every"), + [ + # Lines 1-3 end in CRLF, LF, LF; the same text occurs again with LF + # only and with CRLF only. The ranged read is "a\nb\nc" either way, + # and the first match in file order is the mixed one. + pytest.param(b"a\r\nb\nc\nsep\na\nb\nc\n", (1, 3), b"A\r\nB\nC\nsep\na\nb\nc\n", b"A\r\nB\nC\nsep\nA\nB\nC\n", id="later-lf-only"), + pytest.param(b"a\r\nb\nc\nsep\na\r\nb\r\nc\r\n", (1, 3), b"A\r\nB\nC\nsep\na\r\nb\r\nc\r\n", b"A\r\nB\nC\nsep\nA\r\nB\r\nC\r\n", id="later-crlf-only"), + # An earlier plain occurrence still comes first. + pytest.param(b"a\nb\nsep\na\r\nb\n", (4, 5), b"A\nB\nsep\na\r\nb\n", b"A\nB\nsep\nA\r\nB\n", id="earlier-lf-only"), + # Lines 3-5 read as "c\nd\ne"; the span crosses from CRLF to LF. + pytest.param(b"a\r\nb\r\nc\r\nd\ne\n", (3, 5), b"a\r\nb\r\nC\r\nD\nE\n", b"a\r\nb\r\nC\r\nD\nE\n", id="single-mixed-span"), + ], +) +def test_str_replace_on_aio_edits_a_ranged_read_in_file_order(aio_files, stored, lines, first, every): + # Each line of new_str keeps the ending of the line it replaces. + _, routes = aio_files + routes.files[_AIO_PATH] = stored + old_str = _aio_ranged_read(*lines) + new_str = old_str.upper() + + assert _aio_str_replace(old_str, new_str) == "OK" + assert routes.files[_AIO_PATH] == first + + routes.files[_AIO_PATH] = stored + assert _aio_str_replace(old_str, new_str, replace_all=True) == "OK" + assert routes.files[_AIO_PATH] == every + assert "/v1/file/read" not in routes.routes + + +def test_str_replace_on_aio_leaves_a_file_without_the_snippet_unchanged(aio_files): + _, routes = aio_files + routes.files[_AIO_PATH] = b"a\r\nb\nc\r\n" + + assert _aio_str_replace("a\nc", "x").startswith("Error: String to replace not found in file") + assert routes.files[_AIO_PATH] == b"a\r\nb\nc\r\n" + assert "/v1/file/write" not in routes.routes + + +class TestOversizedFileGate: + """A file over the download limit cannot be read, so read_file never marks + it. The read-before-write gate blocks writes to it instead of failing + open, and str_replace never writes an error string over it.""" + + @pytest.fixture() + def huge_file(self, aio_files, monkeypatch): + import deerflow.community.aio_sandbox.aio_sandbox as aio_module + + sandbox, routes = aio_files + monkeypatch.setattr(aio_module, "_MAX_DOWNLOAD_SIZE", 1024) + routes.files["/mnt/user-data/workspace/huge.log"] = b"read me\n" * 512 + return routes + + @staticmethod + def _gated_call(name: str, args: dict): + from langchain_core.messages import ToolMessage + from langgraph.prebuilt.tool_node import ToolCallRequest + + from deerflow.agents.middlewares.read_before_write_middleware import WRITE_BLOCK_KEY, ReadBeforeWriteMiddleware + from deerflow.sandbox.tools import str_replace_tool, write_file_tool + + tool = {"write_file": write_file_tool, "str_replace": str_replace_tool}[name] + runtime = _tool_runtime() + request = ToolCallRequest(tool_call={"name": name, "args": args, "id": "call-1"}, tool=None, state={"messages": []}, runtime=runtime) + + def handler(req): + return ToolMessage(content=tool.func(runtime=runtime, **req.tool_call["args"]), tool_call_id="call-1", name=name) + + result = ReadBeforeWriteMiddleware().wrap_tool_call(request, handler) + return result, WRITE_BLOCK_KEY + + @pytest.mark.parametrize( + ("name", "args"), + [ + pytest.param("write_file", {"path": "/mnt/user-data/workspace/huge.log", "content": "replaced"}, id="write_file"), + pytest.param("write_file", {"path": "/mnt/user-data/workspace/huge.log", "content": "more", "append": True}, id="append"), + pytest.param("str_replace", {"path": "/mnt/user-data/workspace/huge.log", "old_str": "read", "new_str": "x"}, id="str_replace"), + ], + ) + def test_a_write_over_an_oversized_file_is_blocked(self, huge_file, name, args): + result, write_block_key = self._gated_call(name, args) + + assert result.status == "error" + assert result.additional_kwargs[write_block_key]["tool"] == name + assert "too large to read" in result.content + assert huge_file.files["/mnt/user-data/workspace/huge.log"] == b"read me\n" * 512 + assert "/v1/file/write" not in huge_file.routes + + def test_str_replace_does_not_write_an_error_string_over_it(self, huge_file): + # Without the gate, str_replace itself must still refuse: "read" + # occurs in an error message and would be replaced inside it. + result = _aio_str_replace("read", "x", path="/mnt/user-data/workspace/huge.log") + + assert result.startswith("Error: ") + assert "/v1/file/write" not in huge_file.routes + + def test_a_new_file_is_still_created(self, huge_file): + result, _ = self._gated_call("write_file", {"path": "/mnt/user-data/workspace/new.txt", "content": "fresh\r\n"}) + + assert result.status != "error" + assert huge_file.files["/mnt/user-data/workspace/new.txt"] == b"fresh\r\n" class TestWriteFile: @@ -3085,45 +3389,25 @@ def test_list_dir_preserves_trailing_space_in_filename(sandbox): assert sandbox.list_dir("/test") == ["/test/notes.txt ", "/test/sub"] -def _sdk_file_read_validation_error() -> Exception: - """The exact exception the SDK raises for a server failure envelope. - - The AIO server reports read failures (e.g. ENOENT) as - ``{"success": false, "message": ..., "data": {}}``; the empty ``data`` - cannot satisfy the required fields of the SDK's ``FileReadResult`` model, - so parsing raises a ``ValidationError`` with two "Field required" errors. - Building it from the real SDK models keeps the test faithful to what - production raises. - """ - from agent_sandbox.file.client import ResponseFileReadResult - from pydantic import ValidationError - - try: - ResponseFileReadResult.model_validate({"success": False, "message": "file not found", "data": {}}) - except ValidationError as e: - return e - raise AssertionError("model_validate should fail on data: {}") - - -def test_read_file_missing_file_returns_actionable_error(sandbox, caplog): - """A server failure envelope must not leak the SDK's pydantic - validation-error text to the model. The result must state the file is - missing/unreadable so the agent can act on it (create it, pick another - path) instead of retrying the same read or "fixing" a nonexistent file.""" - sandbox._client.file.read_file.side_effect = _sdk_file_read_validation_error() +def test_read_file_missing_file_returns_actionable_error(aio_files, caplog): + """A missing file must not leak the SDK's error text (headers included) + to the model. The result must state the file is missing/unreadable so the + agent can act on it (create it, pick another path) instead of retrying + the same read or "fixing" a nonexistent file.""" + sandbox, _ = aio_files with caplog.at_level(logging.DEBUG, logger="deerflow.community.aio_sandbox.aio_sandbox"): result = sandbox.read_file("/workspace/new_file.py") assert result == "Error: file not found or unreadable: /workspace/new_file.py" - assert "validation errors" not in result + assert "headers" not in result -def test_read_file_missing_file_does_not_log_error_noise(sandbox, caplog): +def test_read_file_missing_file_does_not_log_error_noise(aio_files, caplog): """Missing files are an expected outcome — ReadBeforeWriteMiddleware - probes every new-file write — so the validation failure must stay out of - the error-level gateway log.""" - sandbox._client.file.read_file.side_effect = _sdk_file_read_validation_error() + probes every new-file write — so the 404 must stay out of the + error-level gateway log.""" + sandbox, _ = aio_files with caplog.at_level(logging.DEBUG, logger="deerflow.community.aio_sandbox.aio_sandbox"): sandbox.read_file("/workspace/new_file.py") @@ -3131,17 +3415,19 @@ def test_read_file_missing_file_does_not_log_error_noise(sandbox, caplog): assert not [record for record in caplog.records if record.levelno >= logging.ERROR] -def test_read_file_success_returns_content(sandbox): - sandbox._client.file.read_file.return_value = SimpleNamespace(data=SimpleNamespace(content="hello\n", file="/workspace/a.txt")) +def test_read_file_success_returns_content(aio_files): + sandbox, routes = aio_files + routes.files["/workspace/a.txt"] = b"hello\n" + assert sandbox.read_file("/workspace/a.txt") == "hello\n" - sandbox._client.file.read_file.assert_called_once_with(file="/workspace/a.txt") + assert routes.routes == ["/v1/file/download"] -def test_read_file_unexpected_error_still_logged(sandbox, caplog): - """Non-validation failures keep the error log and the generic error - string; only the server failure envelope is downgraded to debug.""" - sandbox._client.file.read_file.side_effect = RuntimeError("connection reset") - +def test_read_file_unexpected_error_still_logged(aio_files, caplog): + """Other failures keep the error log and the generic error string; only + a missing file is downgraded to debug.""" + sandbox, routes = aio_files + routes.failures["/workspace/a.txt"] = httpx.ConnectError with caplog.at_level(logging.ERROR, logger="deerflow.community.aio_sandbox.aio_sandbox"): result = sandbox.read_file("/workspace/a.txt") diff --git a/backend/tests/test_harness_guard_middleware.py b/backend/tests/test_harness_guard_middleware.py index c6919c3cdf..551cd63f4f 100644 --- a/backend/tests/test_harness_guard_middleware.py +++ b/backend/tests/test_harness_guard_middleware.py @@ -4,6 +4,8 @@ import json from unittest.mock import MagicMock, patch import pytest +from hypothesis import given, settings +from hypothesis import strategies as st from langchain_core.messages import ToolMessage from langgraph.prebuilt.tool_node import ToolCallRequest @@ -283,6 +285,90 @@ class TestHarnessGuardMiddleware: assert res.status == "error" assert "WRITE BLOCKED" in res.content + def test_str_replace_across_mixed_endings_is_verified(self): + """A ranged-read old_str spanning CRLF and LF lines is spliced and checked too.""" + middleware = HarnessGuardMiddleware(HarnessGuardConfig(write_verify_syntax=True, block_on_syntax_error=True)) + mixed_file = "def foo():\r\n x = 1\n return x\r\n" + req = _make_request( + "str_replace", + {"path": "module.py", "old_str": "def foo():\n x = 1\n return x", "new_str": "def foo(:\n return 1"}, + ) + + def dummy_handler(r): + return ToolMessage(content="Replaced", tool_call_id=r.tool_call["id"], name="str_replace") + + with patch( + "deerflow.agents.middlewares.harness_guard_middleware.read_current_file_content", + return_value=mixed_file, + ): + res = middleware.wrap_tool_call(req, dummy_handler) + + assert isinstance(res, ToolMessage) + assert res.status == "error" + assert "WRITE BLOCKED" in res.content + + def test_an_empty_old_str_is_not_checked_as_an_insertion(self): + """str_replace makes no change for an empty old_str, so nothing is spliced in front of the file.""" + middleware = HarnessGuardMiddleware(HarnessGuardConfig(write_verify_syntax=True, block_on_syntax_error=True)) + req = _make_request("str_replace", {"path": "module.py", "old_str": "", "new_str": "def broken(:"}) + + def dummy_handler(r): + return ToolMessage(content="OK", tool_call_id=r.tool_call["id"], name="str_replace") + + with patch( + "deerflow.agents.middlewares.harness_guard_middleware.read_current_file_content", + return_value="x = 1\r\n", + ): + res = middleware.wrap_tool_call(req, dummy_handler) + + assert res.content == "OK" + + @settings(max_examples=200, deadline=None) + @given( + content=st.lists(st.sampled_from(["x = 1", "y", "\r\n", "\n", "\r"]), max_size=12).map("".join), + data=st.data(), + new_str=st.lists(st.sampled_from(["z", "\n", "\r\n"]), max_size=3).map("".join), + replace_all=st.booleans(), + ) + def test_str_replace_check_sees_the_bytes_str_replace_writes(self, tmp_path_factory, content, data, new_str, replace_all): + """The syntax check runs on the same splice that str_replace writes, for any mix of endings.""" + from deerflow.sandbox.local.local_sandbox import LocalSandbox + from deerflow.sandbox.tools import str_replace_tool + + start = data.draw(st.integers(0, len(content))) + # A snippet as stored, or as a ranged read shows it (CRLF read as LF). + old_str = data.draw(st.sampled_from([content, content.replace("\r\n", "\n")]))[start : data.draw(st.integers(start, len(content)))] + root = tmp_path_factory.mktemp("guard") + (root / "outputs").mkdir() + target = root / "outputs" / "module.py" + target.write_bytes(content.encode()) + runtime = MagicMock() + runtime.context = {"thread_id": "t-1"} + runtime.state = {"sandbox": {"sandbox_id": "local:t-1"}, "thread_data": {"workspace_path": str(root), "uploads_path": str(root), "outputs_path": str(root / "outputs")}} + args = {"path": "/mnt/user-data/outputs/module.py", "old_str": old_str, "new_str": new_str, "replace_all": replace_all} + request = ToolCallRequest(tool_call={"name": "str_replace", "args": args, "id": "call-1"}, tool=None, state={"messages": []}, runtime=runtime) + checked: list[str] = [] + + def record(path, text): + checked.append(text) + return None + + def handler(req): + return ToolMessage(content=str_replace_tool.func(runtime=runtime, description="d", **req.tool_call["args"]), tool_call_id="call-1", name="str_replace") + + with ( + patch("deerflow.sandbox.tools.ensure_sandbox_initialized", lambda _runtime: LocalSandbox("t-1")), + patch("deerflow.sandbox.tools.ensure_thread_directories_exist", lambda _runtime: None), + patch("deerflow.agents.middlewares.harness_guard_middleware.verify_content_syntax", record), + ): + result = HarnessGuardMiddleware(HarnessGuardConfig(write_verify_syntax=True, block_on_syntax_error=True)).wrap_tool_call(request, handler) + + if result.content == "OK" and old_str: + # checked[0] is the file as read, checked[1] the splice. + assert checked == [content, target.read_bytes().decode()] + else: + assert target.read_bytes() == content.encode() + def test_file_backed_progressive_repair_python(self, tmp_path): """Start with two Python syntax errors (missing colons). The first edit must reach disk while the other error remains; diff --git a/backend/tests/test_read_before_write_middleware.py b/backend/tests/test_read_before_write_middleware.py index 0e9f7e2dd9..ae4786d290 100644 --- a/backend/tests/test_read_before_write_middleware.py +++ b/backend/tests/test_read_before_write_middleware.py @@ -204,6 +204,38 @@ class TestWriteGate: handler.assert_called_once() assert result.status != "error" + @pytest.mark.parametrize( + ("name", "args"), + [ + pytest.param("write_file", {"content": "v2"}, id="write_file"), + pytest.param("write_file", {"content": "v2", "append": True}, id="append"), + pytest.param("str_replace", {"old_str": "a", "new_str": "b"}, id="str_replace"), + ], + ) + def test_file_too_large_to_read_blocks_instead_of_failing_open(self, name, args): + # read_file can never mark such a file, so failing open would let any + # write replace it unread. + import errno + + from deerflow.agents.middlewares.read_before_write_middleware import WRITE_BLOCK_KEY + + mw = _middleware({self.PATH: OSError(errno.EFBIG, "File is larger than 100 MB", self.PATH)}) + request = _make_request(name, {"description": "d", "path": self.PATH, **args}) + handler = MagicMock() + result = mw.wrap_tool_call(request, handler) + handler.assert_not_called() + assert result.status == "error" + assert result.additional_kwargs[WRITE_BLOCK_KEY] == {"path": self.PATH, "tool": name} + assert "File is larger than 100 MB" in result.content + + def test_other_os_errors_still_fail_open(self): + mw = _middleware({self.PATH: OSError("connection reset")}) + request = _make_request("write_file", {"description": "d", "path": self.PATH, "content": "v2"}) + handler = MagicMock(return_value=ToolMessage(content="OK", tool_call_id="call-1", name="write_file")) + result = mw.wrap_tool_call(request, handler) + handler.assert_called_once() + assert result.status != "error" + def test_normalized_path_matching(self): mw = _middleware({self.PATH: "v1"}) messages = [_read_marked_message(self.PATH, "v1")] @@ -239,6 +271,20 @@ class TestAsyncPaths: result = asyncio.run(mw.awrap_tool_call(request, handler)) assert result.status == "error" + def test_async_file_too_large_to_read_blocks(self): + import asyncio + import errno + + mw = _middleware({self.PATH: OSError(errno.EFBIG, "File is larger than 100 MB", self.PATH)}) + request = _make_request("write_file", {"description": "d", "path": self.PATH, "content": "v2"}) + + async def handler(_request): + raise AssertionError("handler must not run when blocked") + + result = asyncio.run(mw.awrap_tool_call(request, handler)) + assert result.status == "error" + assert "too large to read" in result.content + def test_async_blocked_write_has_deerflow_tool_meta(self): import asyncio diff --git a/backend/tests/test_remote_read_file_line_numbers.py b/backend/tests/test_remote_read_file_line_numbers.py index 3115a644b6..ad00aac782 100644 --- a/backend/tests/test_remote_read_file_line_numbers.py +++ b/backend/tests/test_remote_read_file_line_numbers.py @@ -15,6 +15,8 @@ from pathlib import Path from types import SimpleNamespace import pytest +from hypothesis import given, settings +from hypothesis import strategies as st from deerflow.sandbox.local.local_sandbox import LocalSandbox from deerflow.sandbox.read_file_contract import READ_FILE_TRUNCATION_PREFIX, count_file_lines @@ -99,3 +101,31 @@ def test_split_file_lines_agrees_with_count_file_lines(content): from deerflow.sandbox.read_file_contract import split_file_lines assert len(split_file_lines(content)) == count_file_lines(content) + + +@settings(max_examples=3000, deadline=None) +@given( + content=st.lists(st.sampled_from(["a", "\n", "\r", "\r\n", "\r\r", "\r\r\n", " "]), max_size=30).map("".join), + start_line=st.none() | st.integers(-2, 12), + end_line=st.none() | st.integers(-2, 12), +) +def test_slice_file_lines_equals_joining_the_split_lines(content, start_line, end_line): + # slice_file_lines copies only the selected lines; it must return what + # slicing the full split_file_lines list returns, with LocalSandbox's clamping. + from deerflow.sandbox.read_file_contract import slice_file_lines, split_file_lines + + lines = split_file_lines(content) + start = max(start_line or 1, 1) + end = max(end_line, 0) if end_line is not None else len(lines) + + assert slice_file_lines(content, start_line, end_line) == "\n".join(lines[start - 1 : end]) + + +def test_slice_file_lines_finds_lines_beyond_one_counting_block(): + from deerflow.sandbox.read_file_contract import slice_file_lines + + content = "".join(f"{n}\r\n" for n in range(1, 200_001)) + + assert slice_file_lines(content, 150_000, 150_002) == "150000\n150001\n150002" + assert slice_file_lines(content, 200_000, None) == "200000" + assert slice_file_lines(content, 200_001, None) == "" diff --git a/backend/tests/test_sandbox_line_endings.py b/backend/tests/test_sandbox_line_endings.py index 79ff49f4fd..ea92b2da54 100644 --- a/backend/tests/test_sandbox_line_endings.py +++ b/backend/tests/test_sandbox_line_endings.py @@ -16,11 +16,14 @@ from types import SimpleNamespace from unittest.mock import MagicMock import pytest +from hypothesis import assume, given, settings +from hypothesis import strategies as st +from support.scaling import LINEAR_LIMIT, growth import deerflow.sandbox.local.local_sandbox as local_sandbox from deerflow.sandbox.local.local_sandbox import LocalSandbox -from deerflow.sandbox.read_file_contract import count_file_lines -from deerflow.sandbox.tools import read_current_file_content, str_replace_tool +from deerflow.sandbox.read_file_contract import count_file_lines, slice_file_lines, split_file_lines +from deerflow.sandbox.tools import _replace_keeping_line_endings, read_current_file_content, str_replace_tool CRLF_SOURCE = b"first\r\nsecond\r\nthird\r\n" @@ -175,6 +178,268 @@ def test_str_replace_on_a_mixed_file_edits_only_the_matched_lines(tmp_path, monk assert after == b"lf1\nlf2\nCRLF1\r\nCRLF2\r\n" +@pytest.mark.parametrize( + ("old_str", "new_str", "expected"), + [ + # The n-th line break of new_str takes the ending of the n-th one in + # the matched text, so an edit that keeps the line count keeps every + # line's ending. + pytest.param("b\nc\nd", "B\nC\nD", b"a\r\nB\r\nC\nD\r\ne\n", id="crlf-first"), + pytest.param("c\nd\ne", "C\nD\nE", b"a\r\nb\r\nC\nD\r\nE\n", id="lf-first"), + pytest.param("b\nc\n", "B\n", b"a\r\nB\r\nd\r\ne\n", id="ends-after-lf"), + pytest.param("c\nd\n", "X\n", b"a\r\nb\r\nX\ne\n", id="ends-after-crlf"), + ], +) +def test_str_replace_matches_a_ranged_read_across_mixed_endings(tmp_path, monkeypatch, old_str, new_str, expected) -> None: + # A ranged read joins lines with "\n", so a span crossing CRLF and LF lines + # matches neither the literal nor the all-CRLF spelling of old_str. + result, after = _str_replace(tmp_path, monkeypatch, b"a\r\nb\r\nc\nd\r\ne\n", old_str=old_str, new_str=new_str) + + assert result == "OK" + assert after == expected + + +def test_str_replace_across_mixed_endings_replaces_the_first_match_or_all(tmp_path, monkeypatch) -> None: + mixed = b"x\r\ny\nx\ny\r\nx\r\ny\n" + + result, after = _str_replace(tmp_path, monkeypatch, mixed, old_str="x\ny\nx", new_str="Z\nZ") + assert result == "OK" + assert after == b"Z\r\nZ\ny\r\nx\r\ny\n" + + result, after = _str_replace(tmp_path, monkeypatch, mixed, old_str="x\ny\n", new_str="X\nY\n", replace_all=True) + assert result == "OK" + assert after == b"X\r\nY\nX\nY\r\nX\r\nY\n" + + +def test_str_replace_on_a_mixed_file_still_reports_a_missing_old_str(tmp_path, monkeypatch) -> None: + mixed = b"a\r\nb\nc\r\n" + + result, after = _str_replace(tmp_path, monkeypatch, mixed, old_str="a\nc", new_str="x") + + assert result.startswith("Error: String to replace not found in file") + assert after == mixed + + +@pytest.mark.parametrize( + ("source", "old_str", "new_str", "replace_all", "expected"), + [ + # A single-line edit inserts lines in the ending of the line it is on. + pytest.param(b"a\r\nb\nc\r\n", "b", "b\nB", False, b"a\r\nb\nB\nc\r\n", id="inserted-lines-follow-an-lf-line"), + pytest.param(b"a\nb\r\nc\n", "b", "b\nB", False, b"a\nb\r\nB\r\nc\n", id="inserted-lines-follow-a-crlf-line"), + # The last line has no ending of its own and takes the one before it. + pytest.param(b"a\nb\r\nc", "c", "c\nd", False, b"a\nb\r\nc\r\nd", id="unterminated-last-line"), + # An old_str that starts at a line break takes the whole CRLF. + pytest.param(b"a\r\nb\nc", "\nb", "\nB", False, b"a\r\nB\nc", id="starts-at-a-crlf"), + # A match never ends between a "\r" and its "\n". + pytest.param(b"a\r\nb\nc\r\n", "a\r", "x", False, None, id="never-splits-a-crlf"), + # A bare "\r" is ordinary text, in old_str and in the file. + pytest.param(b"one\rtwo\r\nthree\n", "one\rtwo\nthree", "1\n3", False, b"1\r\n3\n", id="bare-cr-is-text"), + # Overlapping candidates: matches do not overlap, as with str.replace. + pytest.param(b"a\r\na\na\r\na\n", "a\na", "b", True, b"b\nb\n", id="no-overlap"), + # "\r\n" in old_str comes from a full read and matches only a CRLF. + pytest.param(b"x\ny\nx\r\ny\n", "x\r\ny", "Q", False, b"x\ny\nQ\n", id="crlf-in-old-str-matches-only-crlf"), + pytest.param(b"a\r\nb\nc\r\n", "a\r\nb\r\nc", "x", False, None, id="crlf-in-old-str-never-matches-lf"), + # A snippet with CRLF matches as written or with every line break + # spelled CRLF, not with its endings mixed in another way. + pytest.param(b"a\r\nb\r\nc\r\nd\n", "a\r\nb\nc", "A\nB\nC", False, b"A\r\nB\r\nC\r\nd\n", id="lf-in-old-str-matches-crlf"), + pytest.param(b"a\r\nb\r\nc\nd\n", "a\r\nb\nc\nd", "x", False, None, id="mixed-old-str-matches-no-other-mix"), + pytest.param(b"a\r\nb\nc\r\nd\n", "b\nc\r\nd", "x", False, b"a\r\nx\n", id="mixed-old-str-matches-as-written"), + # A snippet cut from a full read just after a "\r" starts with the LF of a CRLF. + pytest.param(b"a\r\n\r\nb\r\n\n", "\n\r\nb\r\n\n", "\nX\n", False, b"a\r\nX\r\n", id="leading-lf-of-a-crlf"), + # Each line break of new_str keeps the ending of the one it replaces. + pytest.param(b"a\r\nb\nc\nd\n", "\nb\n", "\nB\n", False, b"a\r\nB\nc\nd\n", id="keeps-each-line-ending"), + pytest.param(b"a\r\nb\nc\n", "a\nb\n", "a\nx\ny\nb\n", False, b"a\r\nx\ny\nb\nc\n", id="extra-lines-take-the-last-ending"), + # Without replace_all only the first match in file order changes. + pytest.param(b"x\ny\r\nz\nx\r\ny\r\nz\r\n", "x\ny\nz", "Q", False, b"Q\nx\r\ny\r\nz\r\n", id="first-of-two-spellings"), + ], +) +def test_replace_keeping_line_endings_rules(source, old_str, new_str, replace_all, expected) -> None: + result = _replace_keeping_line_endings(source.decode(), old_str, new_str, replace_all) + + assert result == (None if expected is None else expected.decode()) + + +def test_replace_keeping_line_endings_treats_an_empty_old_str_as_a_no_op() -> None: + # str_replace returns "OK" without writing; the syntax pre-check must see + # the file unchanged, not new_str inserted at the start. + assert _replace_keeping_line_endings("a\r\nb\n", "", "x", False) == "a\r\nb\n" + assert _replace_keeping_line_endings("a\nb\n", "", "x", True) == "a\nb\n" + + +def test_a_line_with_several_crs_before_its_lf_matches_only_as_stored() -> None: + # A ranged read drops every trailing "\r", so "a\r\r\nb" reads as "a\nb" + # there. Read with CRLF as LF it is "a\r\nb": only the stored spelling + # matches, and the ranged-read one is reported missing, not misplaced. + content = "a\r\r\nb\r\n" + + assert _replace_keeping_line_endings(content, "a\r\r\nb", "x", False) == "x\r\n" + assert _replace_keeping_line_endings(content, "a\nb", "x", False) is None + + +# The matcher against a reference model. Files and snippets are drawn from +# "a", "b" and the three line-ending pieces, so endings repeat and mix densely. +_PIECES = ("a", "b", "\r\n", "\n", "\r") + + +def _main_replace(content: str, old_str: str, new_str: str, replace_all: bool) -> str | None: + """str_replace's matching before mixed-ending support, for files with one ending.""" + + def to_crlf(text: str) -> str: + return text.replace("\r\n", "\n").replace("\n", "\r\n") + + if "\r\n" in content: + crlf_old = to_crlf(old_str) + if content.count("\r\n") == content.count("\n") or (old_str not in content and crlf_old in content): + old_str, new_str = crlf_old, to_crlf(new_str) + if not content or old_str not in content: + return None + return content.replace(old_str, new_str) if replace_all else content.replace(old_str, new_str, 1) + + +def _reference_replace(content: str, old_str: str, new_str: str, replace_all: bool) -> str | None: + """The documented rule, spelled out on units: a CRLF in the file or in old_str is one unit.""" + if not old_str: + return content + if "\r\n" not in content: + return _main_replace(content, old_str, new_str, replace_all) + units: list[str] = [] + i = 0 + while i < len(content): + units.append("\r\n" if content.startswith("\r\n", i) else content[i]) + i += len(units[-1]) + needle: list[str] = [] + i = 0 + while i < len(old_str): + needle.append("\r\n" if old_str.startswith("\r\n", i) else old_str[i]) + i += len(needle[-1]) + new_lines = new_str.replace("\r\n", "\n").split("\n") + out: list[str] = [] + i = copied = 0 + found = False + + def matches(window: list[str]) -> bool: + if "\r\n" not in needle: + # A snippet without CRLF: "\n" matches either ending, anything else itself. + return all(want == unit or (want == "\n" and unit == "\r\n") for want, unit in zip(needle, window)) + # A snippet with CRLF matches as written, its first "\n" also as a + # CRLF, or with every line break spelled CRLF. + as_written = window[1:] == needle[1:] and (window[0] == needle[0] or needle[0] == "\n" == window[0][-1]) + return as_written or window == ["\r\n" if want == "\n" else want for want in needle] + + while i + len(needle) <= len(units): + if not matches(units[i : i + len(needle)]): + i += 1 + continue + found = True + endings = [unit for unit in units[i : i + len(needle)] if unit in ("\n", "\r\n")] + if not endings: + endings = [unit for unit in units[i:] if unit in ("\n", "\r\n")][:1] or [unit for unit in units[:i] if unit in ("\n", "\r\n")][-1:] + spelled = new_lines[0] + "".join(endings[min(n, len(endings) - 1)] + line for n, line in enumerate(new_lines[1:])) + out += units[copied:i] + [spelled] + i = copied = i + len(needle) + if not replace_all: + break + return "".join(out + units[copied:]) if found else None + + +@st.composite +def _replace_cases(draw, pieces=_PIECES): + content = "".join(draw(st.lists(st.sampled_from(pieces), max_size=24))) + lines = split_file_lines(content) + source = draw(st.sampled_from(["ranged-read", "full-read", "typed"])) + if source == "ranged-read" and lines: + first = draw(st.integers(0, len(lines) - 1)) + last = draw(st.integers(first, len(lines) - 1)) + text = "\n".join(lines[first : last + 1]) + elif source == "full-read": + text = content + else: + text = "".join(draw(st.lists(st.sampled_from(_PIECES), min_size=1, max_size=6))) + start = draw(st.integers(0, len(text))) + old_str = text[start : draw(st.integers(start, len(text)))] + new_str = "".join(draw(st.lists(st.sampled_from(("X", "\n", "\r\n", "\r")), max_size=4))) + return content, old_str, new_str, draw(st.booleans()) + + +@settings(max_examples=3000, deadline=None) +@given(_replace_cases()) +def test_replace_keeping_line_endings_matches_the_reference_model(case) -> None: + content, old_str, new_str, replace_all = case + + assert _replace_keeping_line_endings(content, old_str, new_str, replace_all) == _reference_replace(content, old_str, new_str, replace_all) + + +@settings(max_examples=1500, deadline=None) +@given(_replace_cases()) +def test_an_edit_that_keeps_the_lines_keeps_every_line_ending(case) -> None: + # Upper-casing the matched text keeps its line count, so the file may + # change only in case: every line ending stays as stored. + content, old_str, _, replace_all = case + result = _replace_keeping_line_endings(content, old_str, old_str.upper(), replace_all) + + assume(result is not None) + assert result.lower() == content + + +@settings(max_examples=1500, deadline=None) +@given(_replace_cases(), st.sampled_from(["\n", "\r\n"]), st.sampled_from(["\n", "\r\n"])) +def test_replace_keeping_line_endings_is_unchanged_on_files_with_one_ending(case, ending, old_ending) -> None: + content, old_str, new_str, replace_all = case + content = content.replace("\r\n", "\n").replace("\r", "").replace("\n", ending) + old_str = old_str.replace("\r\n", "\n").replace("\r", "").replace("\n", old_ending) + # str_replace returns before matching an empty old_str. + assume(old_str) + + assert _replace_keeping_line_endings(content, old_str, new_str, replace_all) == _main_replace(content, old_str, new_str, replace_all) + + +@settings(max_examples=1500, deadline=None) +@given(_replace_cases(), st.data()) +def test_a_ranged_read_snippet_is_never_reported_missing(case, data) -> None: + # Ranged reads drop every trailing "\r"; see the several-CRs case above. + content, _, new_str, replace_all = case + assume("\r\r\n" not in content) + lines = split_file_lines(content) + assume(lines) + first = data.draw(st.integers(0, len(lines) - 1)) + last = data.draw(st.integers(first, len(lines) - 1)) + snippet = "\n".join(lines[first : last + 1]) + assume(snippet) + + assert _replace_keeping_line_endings(content, snippet, new_str, replace_all) is not None + + +@settings(max_examples=1500, deadline=None) +@given(_replace_cases(), st.data()) +def test_a_full_read_snippet_is_found_unless_it_splits_a_crlf(case, data) -> None: + content, _, new_str, replace_all = case + start = data.draw(st.integers(0, len(content))) + stop = data.draw(st.integers(start, len(content))) + snippet = content[start:stop] + assume(snippet and not (snippet.endswith("\r") and content.startswith("\n", stop))) + + assert _replace_keeping_line_endings(content, snippet, new_str, replace_all) is not None + + +@settings(max_examples=150, deadline=None) +@given(_replace_cases()) +def test_str_replace_writes_what_the_reference_model_predicts(tmp_path_factory, case) -> None: + content, old_str, new_str, replace_all = case + assume(old_str) + tmp_path = tmp_path_factory.mktemp("prop") + expected = _reference_replace(content, old_str, new_str, replace_all) + + with pytest.MonkeyPatch.context() as monkeypatch: + result, after = _str_replace(tmp_path, monkeypatch, content.encode(), old_str=old_str, new_str=new_str, replace_all=replace_all) + + if expected is None: + assert result.startswith("Error: String to replace not found in file") + assert after == content.encode() + else: + assert result == "OK" + assert after == expected.encode() + + def test_str_replace_on_an_lf_file_writes_new_str_as_given(tmp_path, monkeypatch) -> None: result, after = _str_replace(tmp_path, monkeypatch, b"one\ntwo\n", old_str="one\n", new_str="uno\r\n") @@ -238,3 +503,39 @@ def test_grep_does_not_match_the_line_terminator(tmp_path, pattern, literal, exp matches, _ = LocalSandbox("t").grep(str(path), pattern, literal=literal) assert [(match.line_number, match.line) for match in matches] == expected + + +# Each scan must stay linear on input built to defeat it. A run of "\r" +# followed by text made the old ranged-read regex retry from every "\r" of +# the run; a CRLF snippet over LF lines made the matcher check every +# overlapping candidate in full. +@pytest.mark.parametrize( + ("make", "size"), + [ + pytest.param(lambda n: ("a\n" + "\r" * n + "x\n", 1, 2), 2000, id="cr-run-then-text"), + pytest.param(lambda n: ("\r" * n + "\nx\n", 1, 2), 2000, id="cr-run-then-lf"), + pytest.param(lambda n: ("x\r\r\r" * n + "\n", 1, 1), 2000, id="cr-runs-inside-a-line"), + pytest.param(lambda n: ("a\r\r\n" * n, 1, None), 2000, id="lines-ending-in-several-crs"), + pytest.param(lambda n: ("a\r\n" * n, 2, None), 2000, id="crlf-lines"), + ], +) +def test_a_ranged_read_is_linear_in_the_file(make, size) -> None: + assert growth(lambda n: slice_file_lines(*make(n)), size) < LINEAR_LIMIT + + +@pytest.mark.parametrize( + ("make", "size"), + [ + # Both the file and the snippet grow, so a check of every overlapping + # candidate in full grows with their product. + pytest.param(lambda n: ("a\n" * 64 * n + "b\r\n", "a\r\n" + "a\n" * n, "x", False), 20, id="crlf-snippet-over-lf-lines"), + pytest.param(lambda n: ("\r" + "\na\nb\r" * 50 * n + "\n", "\na\nb\r" * n, "x", False), 20, id="leading-lf-on-every-crlf"), + pytest.param(lambda n: ("x\r\n" * 50 * n + "y\n", "x\r\n" * n + "x\r", "x", False), 20, id="trailing-cr-before-every-lf"), + pytest.param(lambda n: ("\r" * 100 * n + "\r\nq\n", "\r" * n + "x\n", "x", False), 20, id="ranged-snippet-over-a-cr-run"), + pytest.param(lambda n: ("a\r\nb\n" * 50 * n, "a\nb", "A\nB", True), 20, id="replace-all-across-mixed-lines"), + pytest.param(lambda n: ("a\r\nb\n" * 50 * n, "a\r\nb\n", "A\nB\n", True), 20, id="replace-all-of-a-mixed-snippet"), + pytest.param(lambda n: ("ab\r\n" * 50 * n + "c\n", "b", "b\nc", True), 20, id="lines-inserted-after-many-matches"), + ], +) +def test_str_replace_matching_is_linear_in_the_file_and_the_snippet(make, size) -> None: + assert growth(lambda n: _replace_keeping_line_endings(*make(n)), size) < LINEAR_LIMIT diff --git a/docs/guide/sandbox.md b/docs/guide/sandbox.md index f52f0025a6..7c3a2a839b 100644 --- a/docs/guide/sandbox.md +++ b/docs/guide/sandbox.md @@ -401,7 +401,11 @@ On Linux and macOS, local sandbox `write_file` replacements and `str_replace` st Loop warnings let agents save collected results before their final answer. If the save is blocked by the read-before-write gate, the agent may read the target file and retry the save once. A looping or stopped tool must be replaced by an available alternative; if no permitted save path exists or the retry fails, the final answer includes the collected results and reports that the file was not saved. When `present_files` is available, the warning also asks the agent to present the files it already created in `/mnt/user-data/outputs` before answering, so finished outputs are delivered. Recovery calls still count toward the loop limits, and a hard stop prevents further tool execution. -Ranged `read_file` calls count lines the same way on every sandbox provider: a line ends only at a newline. On E2B, BoxLite, Tenki, and OpenSandbox, a file with bare carriage returns (such as a saved progress log), form feeds, or Unicode line separators therefore returns the same lines as on the local sandbox, and the `start_line` a truncated read suggests points at the next unread line. +Ranged `read_file` calls count lines the same way on every sandbox provider: a line ends only at a newline. On AIO, E2B, BoxLite, Tenki, and OpenSandbox, a file with bare carriage returns (such as a saved progress log), form feeds, or Unicode line separators therefore returns the same lines as on the local sandbox, and the `start_line` a truncated read suggests points at the next unread line. + +A full `read_file` returns line endings as stored, and `str_replace` changes only the text it matches: every other byte, line endings included, stays as stored. A file without CRLF, including an LF-only or CR-only file, is matched literally and `new_str` is written as given. In a file that contains CRLF, a CRLF counts as one line break. An `old_str` without `\r\n`, such as one copied from a ranged read (whose lines are joined with `\n`) or typed with `\n`, matches wherever its lines end in CRLF, LF or a mix of both. An `old_str` with `\r\n`, such as one copied from a full read, matches as written or with every line break spelled CRLF, and a leading `\n` may also be the end of a CRLF line. A snippet that mixes `\r\n` and `\n` therefore does not match lines whose endings mix in another way; accepting any mix would make the search quadratic, while every search is linear in the size of the file and of `old_str`. Matches are taken in file order: without `replace_all` only the first one changes, and with it every one does. Each line break in `new_str` is written in the ending of the corresponding line break in the matched text, so an edit that keeps the number of lines keeps every line's ending; extra lines take the ending of the last matched line break, and a match without one takes the ending of its line. A match never splits a CRLF. A line that ends in more than one `\r` before its `\n` matches only as stored, because a ranged read drops all of those `\r`. + +On AIO, `read_file` and `str_replace` read the stored bytes and fail on a file larger than 100 MB, leaving it unchanged. Because such a file can never be read back, the read-before-write check also blocks `write_file` over it. Read or change it with `bash` (`head`, `tail` or `sed -n`). Concurrent reads and writes to the same file share a gate across synchronous and asynchronous tool calls. Async callers waiting for that gate do not occupy worker threads needed to finish the current read or write. Cancelling a waiting call leaves the current operation running; a call that already started file inspection still waits for that work to finish before releasing its gate.