Skip to content

The agent that grows with you

fix(agent): reader/writer path roles in parallel batch planner — search_files no longer races batched writes

Tekniumcb1e059a989a
diff --git a/agent/tool_dispatch_helpers.py b/agent/tool_dispatch_helpers.py
index 07b2c2e65e7..4ff46e10eb7 100644
--- a/agent/tool_dispatch_helpers.py
+++ b/agent/tool_dispatch_helpers.py
@@ -57,8 +57,17 @@ _PARALLEL_SAFE_TOOLS = frozenset({
"web_search",
})
+# Filesystem tools whose parallel admission is decided by path overlap.
+# Readers may share a subtree with other readers; a writer conflicts with
+# ANY overlapping reservation (reader or writer). This is what keeps a
+# batched ``search_files``/``read_file`` from observing pre-mutation file
+# state when the model batches it alongside the ``patch``/``write_file``
+# it depends on (the classic same-block write→read race).
+_PATH_SCOPED_READERS = frozenset({"read_file", "search_files"})
+_PATH_SCOPED_WRITERS = frozenset({"write_file", "patch"})
+
# File tools can run concurrently when they target independent paths.
-_PATH_SCOPED_TOOLS = frozenset({"read_file", "write_file", "patch"})
+_PATH_SCOPED_TOOLS = _PATH_SCOPED_READERS | _PATH_SCOPED_WRITERS
# Patterns that indicate a terminal command may modify/delete files.
_DESTRUCTIVE_PATTERNS = re.compile(
@@ -116,10 +125,16 @@ def _plan_tool_batch_segments(tool_calls, *, execution_cwd: Optional[Path] = Non
* ``_NEVER_PARALLEL_TOOLS`` (interactive tools) → barrier.
* Unparseable / non-dict arguments → barrier.
- * Path-scoped tools (``read_file``/``write_file``/``patch``) join a
- parallel run only when their target path does not overlap another
- path already reserved in the same run; an overlap closes the run so
- the conflicting call starts a NEW run after the first completes.
+ * Path-scoped tools (``read_file``/``search_files``/``write_file``/
+ ``patch``) join a parallel run only when their target path does not
+ CONFLICT with a path already reserved in the same run. Reservations
+ carry a reader/writer role: reader↔reader overlap is harmless (two
+ reads of the same file commute) and stays parallel; any overlap
+ involving a writer closes the run so the conflicting call starts a
+ NEW run after the first completes. ``search_files`` reserves its
+ search root (default ``.``) as a reader — a search batched after a
+ write into the searched subtree is ordered behind that write instead
+ of racing it.
* Anything not in ``_PARALLEL_SAFE_TOOLS`` and not an opted-in MCP
tool → barrier.
@@ -129,7 +144,8 @@ def _plan_tool_batch_segments(tool_calls, *, execution_cwd: Optional[Path] = Non
"""
segments: list[list] = [] # [kind, calls] pairs, normalized to tuples on return
current: list = []
- reserved_paths: list[Path] = []
+ # (canonical_path, is_writer) reservations for the current parallel run.
+ reserved_paths: list[tuple[Path, bool]] = []
def _close_parallel() -> None:
nonlocal current, reserved_paths
@@ -177,11 +193,18 @@ def _plan_tool_batch_segments(tool_calls, *, execution_cwd: Optional[Path] = Non
if scoped_path is None:
_add_sequential(tool_call)
continue
- if any(_paths_overlap(scoped_path, existing) for existing in reserved_paths):
+ is_writer = tool_name in _PATH_SCOPED_WRITERS
+ if any(
+ (is_writer or existing_is_writer)
+ and _paths_overlap(scoped_path, existing)
+ for existing, existing_is_writer in reserved_paths
+ ):
# Same-subtree conflict inside this run: close it so this
# call starts a fresh run AFTER the conflicting one lands.
+ # Reader↔reader overlap never conflicts — concurrent reads
+ # of the same subtree commute.
_close_parallel()
- reserved_paths.append(scoped_path)
+ reserved_paths.append((scoped_path, is_writer))
current.append(tool_call)
continue
@@ -250,6 +273,12 @@ def _extract_parallel_scope_path(
raw_path = function_args.get("path")
if not isinstance(raw_path, str) or not raw_path.strip():
+ # ``search_files`` defaults its search root to the cwd when
+ # ``path`` is omitted — reserve that root rather than falling
+ # back to a sequential barrier (returning None here would demote
+ # every bare search to a barrier and destroy read parallelism).
+ if tool_name == "search_files":
+ return _canonical_path(".", execution_cwd)
return None
return _canonical_path(raw_path, execution_cwd)
@@ -634,6 +663,8 @@ __all__ = [
"_NEVER_PARALLEL_TOOLS",
"_PARALLEL_SAFE_TOOLS",
"_PATH_SCOPED_TOOLS",
+ "_PATH_SCOPED_READERS",
+ "_PATH_SCOPED_WRITERS",
"_DESTRUCTIVE_PATTERNS",
"_REDIRECT_OVERWRITE",
"_is_destructive_command",
diff --git a/tests/run_agent/test_tool_batch_segmentation.py b/tests/run_agent/test_tool_batch_segmentation.py
index 217dcfb7bc5..a89ee25aaaa 100644
--- a/tests/run_agent/test_tool_batch_segmentation.py
+++ b/tests/run_agent/test_tool_batch_segmentation.py
@@ -147,6 +147,104 @@ class TestPlanToolBatchSegments:
assert _flatten_ids(segments) == ["b1", "r1", "c1", "r2", "r3"]
+class TestReaderWriterPathRoles:
+ """Reader/writer reservation semantics on path-scoped tools.
+
+ The originating bug: ``search_files`` was in ``_PARALLEL_SAFE_TOOLS``
+ with no path reservation, so ``patch(path=X)`` + ``search_files(path=dir(X))``
+ landed in ONE parallel segment and the search could observe pre-patch
+ file content (stale-read race). Fix: ``search_files`` reserves its
+ search root as a READER; overlap conflicts only when a WRITER is on
+ either side.
+ """
+
+ def test_search_files_after_patch_same_subtree_splits(self, tmp_path, monkeypatch):
+ """The exact smoke-test race: patch a file, search its directory."""
+ monkeypatch.chdir(tmp_path)
+ calls = [
+ _tc("patch", '{"path":"scratch/sample.txt","old_string":"a","new_string":"patched"}', call_id="w1"),
+ _tc("search_files", '{"pattern":"patched","path":"scratch"}', call_id="s1"),
+ ]
+ segments = _plan_tool_batch_segments(calls, execution_cwd=tmp_path)
+ # Both calls survive, but never in the same PARALLEL segment.
+ # (A shared *sequential* segment is fine — sequential is ordered.)
+ assert _flatten_ids(segments) == ["w1", "s1"]
+ for kind, seg_calls in segments:
+ ids = [tc.id for tc in seg_calls]
+ assert not (kind == "parallel" and {"w1", "s1"} <= set(ids)), (
+ "write and dependent search must not share a parallel segment"
+ )
+
+ def test_search_files_default_root_conflicts_with_write_into_cwd(self, tmp_path, monkeypatch):
+ """search_files with NO path arg reserves the cwd — a write anywhere
+ under the cwd must not share its segment."""
+ monkeypatch.chdir(tmp_path)
+ calls = [
+ _tc("write_file", '{"path":"out/notes.txt","content":"x"}', call_id="w1"),
+ _tc("search_files", '{"pattern":"notes"}', call_id="s1"),
+ ]
+ segments = _plan_tool_batch_segments(calls, execution_cwd=tmp_path)
+ for kind, seg_calls in segments:
+ ids = [tc.id for tc in seg_calls]
+ assert not (kind == "parallel" and {"w1", "s1"} <= set(ids))
+
+ def test_reader_reader_same_file_stays_parallel(self, tmp_path, monkeypatch):
+ """Two reads of the same file commute — the old planner needlessly
+ split them; they must now share one parallel segment."""
+ monkeypatch.chdir(tmp_path)
+ calls = [
+ _tc("read_file", '{"path":"a.py"}', call_id="r1"),
+ _tc("read_file", '{"path":"a.py"}', call_id="r2"),
+ ]
+ segments = _plan_tool_batch_segments(calls, execution_cwd=tmp_path)
+ assert _kinds(segments) == ["parallel"]
+ assert [tc.id for tc in segments[0][1]] == ["r1", "r2"]
+
+ def test_read_file_and_search_files_overlapping_stay_parallel(self, tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ calls = [
+ _tc("read_file", '{"path":"src/a.py"}', call_id="r1"),
+ _tc("search_files", '{"pattern":"foo","path":"src"}', call_id="s1"),
+ ]
+ segments = _plan_tool_batch_segments(calls, execution_cwd=tmp_path)
+ assert _kinds(segments) == ["parallel"]
+
+ def test_search_files_disjoint_from_write_stays_parallel(self, tmp_path, monkeypatch):
+ """A search rooted outside the written subtree has no conflict."""
+ monkeypatch.chdir(tmp_path)
+ calls = [
+ _tc("write_file", '{"path":"src/a.py","content":"x"}', call_id="w1"),
+ _tc("search_files", '{"pattern":"foo","path":"docs"}', call_id="s1"),
+ ]
+ segments = _plan_tool_batch_segments(calls, execution_cwd=tmp_path)
+ assert _kinds(segments) == ["parallel"]
+ assert [tc.id for tc in segments[0][1]] == ["w1", "s1"]
+
+ def test_writer_writer_same_path_still_splits(self, tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ calls = [
+ _tc("write_file", '{"path":"a.py","content":"1"}', call_id="w1"),
+ _tc("write_file", '{"path":"a.py","content":"2"}', call_id="w2"),
+ ]
+ segments = _plan_tool_batch_segments(calls, execution_cwd=tmp_path)
+ for kind, seg_calls in segments:
+ ids = [tc.id for tc in seg_calls]
+ assert not (kind == "parallel" and {"w1", "w2"} <= set(ids))
+
+ def test_read_then_write_same_file_still_splits(self, tmp_path, monkeypatch):
+ """Reader followed by writer on the same path keeps the pre-existing
+ split (write must not clobber a file mid-read)."""
+ monkeypatch.chdir(tmp_path)
+ calls = [
+ _tc("read_file", '{"path":"a.py"}', call_id="r1"),
+ _tc("write_file", '{"path":"a.py","content":"x"}', call_id="w1"),
+ ]
+ segments = _plan_tool_batch_segments(calls, execution_cwd=tmp_path)
+ for kind, seg_calls in segments:
+ ids = [tc.id for tc in seg_calls]
+ assert not (kind == "parallel" and {"r1", "w1"} <= set(ids))
+
+
class TestShouldParallelizeBackwardCompat:
"""The boolean gate is now a view over the planner — same answers as before."""