fix(opensandbox): report a missing file as FileNotFoundError (#8470)

* fix(opensandbox): report a missing file as FileNotFoundError

OpenSandboxSandbox.read_file turned every failed read into an "Error: ..."
string and logged it at ERROR, including an HTTP 404 FILE_NOT_FOUND for a file
that simply doesn't exist yet. The read-before-write gate reads the target
before every write_file, so each new file an agent writes logged an ERROR, and
the gate had to fail open because "missing" and "unreadable" looked the same.

A not-found answer (a 404 anywhere in the cause chain, the provider's existing
_is_not_found) now raises FileNotFoundError from the SDK error, like
LocalSandbox; the gate and read_file already handle it (write_file creates the
file, read_file reports not_found). It is logged at debug. Other read errors
keep the "Error: ..." string and the ERROR log. A 404 still doesn't evict the
sandbox.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(opensandbox): keep a renewal 404 as a dead sandbox, not a missing file

Review follow-up (willem-bd): _file_op re-raises a failed renewal through the
same path as the operation's own error, so a renewal 404 (sandbox expired
server-side) was evicted correctly but then surfaced as FileNotFoundError, and
the read-before-write gate treated a dead sandbox like a file that doesn't
exist yet.

The not-found translation now lives in _file_op behind missing_path and
applies only to the operation's own failure; a renewal failure keeps its
error. read_file and append-mode write_file opt in. Tests pin the renewal-404
read (red on the previous head) and append behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(opensandbox): let the remote line-number test's _file_op stub take keyword arguments

_file_op now takes missing_path; the stub in test_remote_read_file_line_numbers.py accepted only the operation, so the
two opensandbox cases failed with an unexpected keyword argument (CI backend-unit-tests (4)).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bas Cancrinus 2026-11-22 03:07:21 +01:00 committed by GitHub
parent 7b84fd0998
commit b6b0be211e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 60 additions and 9 deletions

View File

@ -227,7 +227,12 @@ class OpenSandboxSandbox(Sandbox):
self._note_failure(failure, api_not_found_is_terminal=True)
raise failure
def _file_op(self, operation):
def _file_op(self, operation, *, missing_path: str | None = None):
"""Run a file API call, renewing the sandbox first when it has a server-side timeout.
With ``missing_path``, a not-found answer from the operation itself raises FileNotFoundError (LocalSandbox's
contract). A failed renewal keeps its own error even when it is a 404: the sandbox is gone, not the file.
"""
with self._operation_lock:
with self._state_lock:
if self._closed:
@ -245,6 +250,8 @@ class OpenSandboxSandbox(Sandbox):
failure = exc
renewal_failed = False
self._note_failure(failure, api_not_found_is_terminal=renewal_failed)
if missing_path is not None and not renewal_failed and _is_not_found(failure):
raise FileNotFoundError(f"File not found: {missing_path}") from failure
raise failure
@staticmethod
@ -296,7 +303,13 @@ class OpenSandboxSandbox(Sandbox):
def read_file(self, path: str, start_line: int | None = None, end_line: int | None = None) -> str:
resolved = self._resolve_path(path)
try:
content = self._file_op(lambda files: files.read_file(resolved))
content = self._file_op(lambda files: files.read_file(resolved), missing_path=path)
except FileNotFoundError as exc:
# Same contract as LocalSandbox: callers tell "missing" from "unreadable" by the exception type
# (read_file reports not_found, the read-before-write gate lets write_file create the file).
# A missing file is an expected answer, not an error to log.
logger.debug("OpenSandbox file %s not found: %s", resolved, exc.__cause__)
raise
except Exception as exc:
logger.error("Failed to read OpenSandbox file %s: %s", resolved, exc)
return f"Error: {exc}"
@ -316,10 +329,8 @@ class OpenSandboxSandbox(Sandbox):
return
with self._append_lock:
try:
previous = self._file_op(lambda files: files.read_bytes(resolved))
except Exception as exc:
if not _is_not_found(exc):
raise
previous = self._file_op(lambda files: files.read_bytes(resolved), missing_path=path)
except FileNotFoundError:
previous = b""
data = previous + content.encode("utf-8")
self._file_op(lambda files: files.write_file(resolved, data, mode=644))

View File

@ -1711,15 +1711,30 @@ def test_download_rejects_outside_virtual_prefix_before_sdk_call() -> None:
assert remote.files.calls == []
def test_missing_file_api_404_does_not_evict_sandbox() -> None:
@pytest.mark.parametrize("line_range", [{}, {"start_line": 2, "end_line": 3}])
def test_missing_file_api_404_raises_file_not_found_without_evicting(caplog: pytest.LogCaptureFixture, line_range: dict) -> None:
# Same contract as LocalSandbox: the read-before-write gate and read_file tell "missing" from "unreadable" by the
# exception type, and a file an agent is about to create is not an error worth an ERROR log line.
invalidated: list[tuple[str, str]] = []
remote = _FakeRemote("remote")
remote.file_error = _TerminalApiError("file not found", status_code=404)
box = _box(remote, on_terminal_failure=lambda sandbox_id, reason: invalidated.append((sandbox_id, reason)))
assert box.read_file("/mnt/user-data/workspace/missing.txt").startswith("Error:")
with caplog.at_level(logging.DEBUG), pytest.raises(FileNotFoundError, match="/mnt/user-data/workspace/missing.txt") as raised:
box.read_file("/mnt/user-data/workspace/missing.txt", **line_range)
assert raised.value.__cause__ is remote.file_error
assert not [record for record in caplog.records if record.levelno >= logging.WARNING]
assert invalidated == []
def test_unreadable_file_still_returns_the_error_string(caplog: pytest.LogCaptureFixture) -> None:
remote = _FakeRemote("remote")
remote.file_error = _TerminalApiError("internal error", status_code=500)
box = _box(remote)
with caplog.at_level(logging.ERROR):
assert box.read_file("/mnt/user-data/workspace/x.txt").startswith("Error:")
assert any("Failed to read OpenSandbox file" in record.getMessage() for record in caplog.records)
def test_terminal_renewal_failure_evicts_before_operation() -> None:
invalidated: list[tuple[str, str]] = []
remote = _FakeRemote("remote")
@ -1734,6 +1749,31 @@ def test_terminal_renewal_failure_evicts_before_operation() -> None:
assert remote.commands.calls == []
def test_renewal_404_on_read_reports_the_dead_sandbox_not_a_missing_file() -> None:
# A renewal 404 means the sandbox expired server-side: evict it and keep its error, so neither read_file's
# not_found answer nor the read-before-write gate mistakes a dead sandbox for a file that doesn't exist yet.
invalidated: list[tuple[str, str]] = []
remote = _FakeRemote("remote")
remote.renew_error = _TerminalApiError("sandbox expired")
box = _box(
remote,
sandbox_timeout=timedelta(minutes=5),
on_terminal_failure=lambda sandbox_id, reason: invalidated.append((sandbox_id, reason)),
)
assert box.read_file("/mnt/user-data/workspace/notes.md") == "Error: sandbox expired"
assert invalidated == [("sandbox-id", "sandbox expired")]
assert remote.files.calls == []
def test_renewal_404_on_append_raises_instead_of_starting_an_empty_file() -> None:
remote = _FakeRemote("remote")
remote.renew_error = _TerminalApiError("sandbox expired")
box = _box(remote, sandbox_timeout=timedelta(minutes=5))
with pytest.raises(_TerminalApiError, match="sandbox expired"):
box.write_file("/mnt/user-data/workspace/notes.md", "more", append=True)
assert remote.files.calls == []
def test_terminal_error_evicts_active_sandbox(monkeypatch: pytest.MonkeyPatch) -> None:
provider, sdk = _install(monkeypatch)
sandbox_id = provider.acquire("thread-1", user_id="user-1")

View File

@ -53,7 +53,7 @@ def _remote_sandbox(name: str, monkeypatch: pytest.MonkeyPatch, remote_files: di
from deerflow.community.opensandbox.sandbox import OpenSandboxSandbox
sandbox = OpenSandboxSandbox("line-contract", SimpleNamespace(), run_command_opts_cls=SimpleNamespace)
monkeypatch.setattr(sandbox, "_file_op", lambda operation: operation(SimpleNamespace(read_file=lambda path, **_kwargs: read_text(path))))
monkeypatch.setattr(sandbox, "_file_op", lambda operation, **_kwargs: operation(SimpleNamespace(read_file=lambda path, **_kwargs: read_text(path))))
return sandbox
raise AssertionError(f"Unregistered provider: {name}")