Zuyi Zhou a40e911ddb
fix(agent): bound every tree walk and take it off the event loop (#566)
## Summary

On 2026-09-20 one `find` call froze the whole gateway for 2h21m. The
model asked for `find(pattern="**/gps_trilateration/index.html",
path="/Users/admin")`, and `FindTool` ran `Path.glob` synchronously on
the event loop, filtered the noise directories only after walking them,
and had no deadline. The registry's 300s ceiling is an
`asyncio.wait_for`, which cannot preempt synchronous code, so every
session and every subagent on the gateway stopped until the walk came
back (`gateway.log`: `Tool result: find duration=8476519ms`). `list_dir`
with `recursive=true` had the same shape through `rglob`.

The fix gives the three tree-walking tools one walk,
`raven.agent.tools.tree_walk`, with these bounds:

- noise directories (`node_modules`, `.git`, ...) are pruned before they
are entered, not filtered afterwards -- the pruning tests spy on
`os.scandir` and assert the noise directory is never opened;
- the walk yields one entry at a time and checks a 20s wall-clock budget
(the value grep's fallback already used) before every entry, so whatever
the caller does with one entry -- the `stat` per `find` match, the read
per grep file -- is covered by the check on the next. The budget cannot
be overrun by one large or slow directory: the probe with eight matches,
a 30ms stat each and a 50ms budget returns 2 matches and the notice.
When the budget is hit, `find` and `list_dir` append a `PARTIAL result:
... traversal budget ...` clause to their trailer, and a deadline that
fires before any match is not reported as a clean `No files found` /
`Directory is empty`;
- every caller runs the walk in `asyncio.to_thread`, so the loop keeps
serving other sessions while the walk runs. Cancelling the thread does
not stop the worker, which is why the deadline lives inside the walk.
The pure-Python `grep` fallback already had the prune and the deadline;
it moves onto the shared walk and off the loop with the others.

`find` matches each path component with `fnmatch.translate`, with a
component that is exactly `**` spanning any number of components; the
matcher is a position-set simulation (`_advance`), linear in components
times segments, so a pattern carrying many `**` cannot make one match
call slow. A pattern's leading literal components decide where the walk
starts: `src/**/*.py` begins inside `src` and never lists a sibling of
it, a pattern that is all literal (`src/lib/c.py`, `src/lib`) names
exactly one path and answers without a walk, and the prefix itself is a
match when the rest of the pattern can match nothing (`src/**` still
lists `src/`). It answers exactly what `Path.glob` answered for the same
pattern: pinned by a parametrized oracle test over twenty-seven patterns
on a fixture and nineteen on a fixture with links (a directory link out
of the tree, a link cycle, a file link, a noise directory beneath a
link), and checked by hand against `Path.glob` over `raven/` for 27
patterns including bracket edge cases and trailing slashes, 0
mismatches. Two deliberate differences: a trailing `**` also lists files
beneath its prefix (3.12's `Path.glob` listed only directories there),
and a pattern with `..` or a leading `/` is refused instead of followed,
since a pattern must not reach outside the directory the fence resolved.
A trailing slash keeps `Path.glob`'s directory-only meaning (`*/`,
`src/**/`). A symbolic link to a directory is entered where a single
component names or matches it and never under `**`, which is how
`Path.glob` read a pattern: `*/util/helper.py` reaches through a linked
`vendor`, `**/helper.py` does not, and a link cycle is entered once per
component the pattern spends on it, so `*/*/*/b.py` enters `src/loop ->
src` twice and stops. The walker asks its caller per link (`follow`),
`find` answers from the pattern and hands the link positions of a path
to the matcher so `**` cannot claim them, and `list_dir` and the grep
fallback never ask, staying as `rglob` and `os.walk` left them. A third
deliberate difference from the merge base: a noise directory inside a
pattern's literal prefix (`node_modules/*.js`, `src/node_modules/*.js`)
is walked, since the pattern asked for it, where `Path.glob`'s filter
dropped it; one met below the prefix is pruned as before
(`*/node_modules/*.js` answers nothing), `list_dir` on such a path lists
it, and the `find`, `list_dir` and code-flow `glob` descriptions state
that rule instead of an unconditional "skipped". Review found an earlier
wording of the two `find` descriptions one component short ("except one
the pattern starts with"), while the oracle helper already pruned below
the prefix; the sentences now say what the helper checks, and the oracle
has the `src/node_modules` shape on both sides.

The raven-code `glob` tool (`agents/raven-code/.../tools/search.py`)
parses trunk `find` output line by line and strips the trailer before
merging brace alternatives. It learns the new clause, so a cut-short
child is reported as cut short rather than as a tree that lacks the
files; its `is_notice` grammar covers the new line so it is never pasted
into a listing as a path. The code-flow tool guide
(`prompts/TOOLS_CODE.md`), the wrapper's description and its `limit`
parameter told the model that a PARTIAL `glob` result means "raise
`limit` or narrow the pattern"; a traversal-budget PARTIAL is now a
result `glob` can return and a higher limit does nothing for it, so all
three now tell the two notices apart. The seeded copy of the guide
refreshes through the receipt `seed_guide` keeps beside it, so no legacy
digest is added.

Fixed in passing, and now pinned: recursive `list_dir` filtered `rglob`
results on the components of the absolute path, so a workspace beneath a
directory named `build`, `dist`, `venv` or another noise name listed as
"Directory ... is empty" (reproduced at the merge base under
`<tmp>/build/proj`; this head lists it). The shared walk prunes below
the listed path only; `find` and the grep fallback already did.

Not changed: the 20s value. It is the budget grep's fallback already ran
under; this PR does not re-measure it, it makes it hold for every entry
of every walk.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

At head 8dade176, on origin/main at d50a13c1 (nine commits: the walk,
the grep pin, the changelog, the per-entry budget with the prefix start,
the literal-directory case, the symbolic-link reading with the
noise-prefix wording, the noise-name-above-the-path pin, the guide
wording, and the prefix-rule wording; `git range-diff` against bb836988:
all nine replayed `=` onto the moved main, which conflicted only at the
changelog anchor and touches no file this PR touches):

```
uv run pytest tests/test_file_search_traversal_guard.py tests/test_agents_code_tools_plugin.py \
  tests/test_search_tools.py tests/test_tools_workdir.py tests/test_tool_registry_execute.py tests/test_filesystem_tools.py -q
# 203 passed
COLORTERM=truecolor uv run --frozen --python 3.12 --all-extras pytest -q --ignore=tests/integration   # in a throwaway worktree
# 24652 passed, 110 skipped in 382.30s (0:06:22) at head 8dade176, in a throwaway worktree with COLORTERM=truecolor
uv run pytest tests/test_agents_code_launcher.py tests/test_agents_code_tools_plugin.py -q   # the guide's seeding and wording tests, the glob wrapper
# 119 passed
make lint-python lint-imports lint-types lint-deps          # all pass
git diff --check origin/main...HEAD                         # clean
scripts/check_source_language.py origin/main...HEAD         # exit 0
scripts/check_large_files.py origin/main...HEAD             # exit 0
git merge-tree --write-tree HEAD origin/main                # clean
```

Revert-to-red, with the tests kept (101 tests in
`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`):

```
the three production files reverted to the previously reviewed head (fd5663ee)   19 failed
file_search.py + filesystem.py reverted to origin/main, tree_walk.py removed      collection error
```

Mutation, each mutant applied alone, control restored between runs:

```
deadline checked once per directory (the reviewed placement)   10 failed
walk starts at the root instead of the pattern's prefix          2 failed
trailing slash matches files too                                 4 failed
a pattern naming one file still walks                            1 failed
the prefix itself is never a match                               7 failed
a pattern naming one directory walks beneath it                  1 failed
control (nothing mutated)                                      101 passed
```

From the first review round (still holding at this head): find without
`to_thread` 1 failed; list_dir without `to_thread` 1 failed; grep
fallback without `to_thread` 1 failed; pruning removed 6 failed; fork
drops the PARTIAL clause 1 failed.

Fourth round, the symbolic-link reading
(`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`, 128 tests, `-n 0`; a mutant that
lets `**` sweep a link, or forgets the link positions, re-enters the
cycle until the OS refuses the path and answers paths `Path.glob` never
did):

```
baseline                                                 128 passed
MUTANT  ** may sweep a link                                8 failed   (7 oracle cases, and the link the pattern ends at is opened)
MUTANT  find never asks to enter a link                    6 failed   (the six oracle patterns that pass through a link)
MUTANT  a link is entered even when the pattern ends at it 1 failed   (scandir spy on **/vendor)
MUTANT  ancestor links forgotten (links_of empty)          1 failed   (a cycle case answers a path Path.glob never did)
MUTANT  the walker consults follow but never enters        7 failed
MUTANT  each followed root gets a fresh deadline           9 failed   (every deadline test, and the walker's one-budget test)
REVERT  production files to reviewed head d67184c8         7 failed
CONTROL restored                                         128 passed
```

Revert-to-red for the noise-name pin: with
`raven/agent/tools/filesystem.py` at the merge base and the test kept,
`test_a_noise_name_above_the_searched_path_hides_nothing` fails on the
`Directory ... is empty` answer (1 failed); at this head it passes. The
`agents/**` change is two prose strings and a guide line, outside the
coverage gate's `raven/**` and `plugins-dist/**` pathspecs; the guide's
name-list test and its seeding tests (`test_agents_code_launcher.py`)
cover the file.

The prefix rule is pinned by mutation, the other policy (prune a noise
directory inside the prefix) against the two guard files (131 tests, `-n
0`):

```
baseline                                                 131 passed
MUTANT  a noise directory inside the prefix is pruned    5 failed
      test_find_matches_what_path_glob_matched[node_modules/**/*.py], test_find_matches_what_path_glob_matched[node_modules/*/], test_find_matches_what_path_glob_matched[node_modules/*/d.py], test_find_matches_what_path_glob_matched[node_modules/x/d.py], test_find_matches_what_path_glob_matched[src/node_modules/*.py]
CONTROL restored                                         131 passed
```

The symlink oracle is the reviewer's own test shape over a fixture with
links: `vendor -> outside/real`, `src/loop -> src`, `alias.py -> a.py`,
a `node_modules` beneath the link; 19 patterns, 0 mismatches against
`Path.glob` on 3.12, plus a scandir spy pinning that `**/vendor` never
opens the link, a walker test pinning that the default walk yields a
link and does not enter it while a `follow`ed link is walked after the
tree under one deadline, and a `list_dir` and grep test pinning
`rglob`/`os.walk` parity through a link.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed (CHANGELOG
`Unreleased / Fixed` entry)

## Risk

User-visible behaviour changes, all in tool output the model reads:

- `find` and `list_dir` (recursive) can now return a partial listing
with a `PARTIAL result` clause in the trailer where they previously
either returned everything or hung. The clause tells the model the
absence of a match is not conclusive and to narrow the search.
- A path-prefixed `find` pattern spends its budget only inside its
prefix, so on a large tree it finds what a root-anchored walk used to
miss.
- `find` refuses patterns containing `..` or starting with `/` with an
`Error running find:` line; `Path.glob` used to raise on the second and
could climb on the first.
- `find` with a trailing `**` lists files as well as directories beneath
the prefix; a trailing `/` lists directories only, as before.
- `find` reaches through a symbolic link to a directory where a literal
or single-wildcard component names or matches it, as it did at the merge
base; the earlier revisions of this PR had lost that and returned a
clean miss with no notice. `**` never enters a link, as before.
- A noise directory inside a `find` pattern's literal prefix, or named
as the `list_dir` path, is walked: `find('node_modules/*.js')` and
`find('src/node_modules/*.js')` answer its files and
`list_dir('node_modules', recursive=true)` lists it, where the merge
base answered nothing and "empty". One met below the prefix is pruned as
before. Both descriptions state the rule.
- Recursive `list_dir` on a workspace beneath a directory named like a
noise directory (`/tmp/build/proj`) lists it instead of answering "is
empty".
- The code-flow `glob` description, its `limit` parameter and the tool
guide tell a limit cut from a traversal-budget PARTIAL; the notices
themselves are unchanged.
- `list_dir` flat listings are unchanged; the empty-directory message is
unchanged.

Rollback: revert the squash commit. The new module has no other
consumers, and no state or schema is involved.

- [x] Security impact considered (a pattern can no longer climb out of
the fenced directory via `..`; a directory link is entered exactly where
`Path.glob` entered it at the merge base, one non-`**` component, and
never under `**`, so the fence's reach is what it was and not wider;
`list_dir` and grep never enter one)
- [x] Backward compatibility considered (the fork's trailer grammar is
extended, not changed; existing fork tests pass unchanged)
- [x] Rollback path is clear for risky changes

## Related Issues

N/A

---------

Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-22 10:59:01 +08:00

211 lines
8.8 KiB
Python

"""``glob``: the fork's spelling of trunk's pathname-pattern tool.
Same engine, one name and one description: the fork measured that models
trained on the common convention reach for ``glob`` and read its output as a
listing, not as a command to run. The product config withholds trunk's
``find`` so the face carries one spelling.
Brace alternation (``*.{ts,tsx}``) is part of that convention and trunk's
engine takes one pattern, so it is expanded here and the listings are merged.
The engine returns paths together with status text. The merge preserves
errors, carries any child truncation into the final notice, deduplicates the
paths and sorts them by recency before applying the caller's total limit.
"""
from __future__ import annotations
import re
from typing import Any
from raven.agent.tools import file_search as trunk
#: How many patterns one brace expression may expand to. Past it the call is
#: refused rather than silently searching a subset -- a listing that quietly
#: omits half the alternatives reads exactly like a directory that lacks them.
BRACE_CAP = 20
#: The engine's own lines, which are not paths. Matched, not guessed: each is
#: a literal the engine writes (``file_search.FindTool``).
_NOTICE_RE = re.compile(
r"^\(showing first \d+(?: of \d+ results| results across \d+ patterns)(?:; PARTIAL.*)?\)$"
r"|^\(PARTIAL result: .*\)$"
r"|^No files found matching pattern(?:\.|: .*)$"
r"|^Error: |^Error running find: ",
)
#: The engine's one trailing notice, which carries a clause per condition: the
#: listing was cut at the limit, the walk hit its traversal budget, or both.
_CHILD_CUT_RE = re.compile(r"^\(showing first \d+ of \d+ results(?:; PARTIAL result: .*)?\)$")
_CHILD_INCOMPLETE_RE = re.compile(r"^\((?:showing first \d+ of \d+ results; )?PARTIAL result: .*\)$")
_NO_FILES = "No files found matching pattern."
def is_notice(line: str) -> bool:
"""Whether this output line is the engine talking, not a path."""
return bool(_NOTICE_RE.match(line.strip()))
def expand_braces(pattern: str) -> list[str]:
"""Every ``{a,b}`` group expanded, innermost-first, in listed order.
Returns the pattern unchanged when it carries no group, and raises
``ValueError`` when the expansion would exceed :data:`BRACE_CAP` or the
braces do not pair -- the caller turns either into a refusal the model can
act on.
"""
if "{" not in pattern:
return [pattern]
start = pattern.find("{")
depth = 0
end = -1
for index in range(start, len(pattern)):
if pattern[index] == "{":
depth += 1
elif pattern[index] == "}":
depth -= 1
if depth == 0:
end = index
break
if end < 0:
raise ValueError(f"unbalanced braces in pattern {pattern!r}")
alternatives = _split_top_level(pattern[start + 1 : end])
out: list[str] = []
for alt in alternatives:
for rest in expand_braces(pattern[:start] + alt + pattern[end + 1 :]):
if rest not in out:
out.append(rest)
if len(out) > BRACE_CAP:
raise ValueError(
f"pattern {pattern!r} expands to more than {BRACE_CAP} patterns; "
"search the alternatives in separate calls"
)
return out
def _split_top_level(body: str) -> list[str]:
"""Split on commas that are not inside a nested group."""
parts: list[str] = []
depth = 0
current: list[str] = []
for char in body:
if char == "{":
depth += 1
elif char == "}":
depth -= 1
if char == "," and depth == 0:
parts.append("".join(current))
current = []
continue
current.append(char)
parts.append("".join(current))
return parts
class GlobTool(trunk.FindTool):
@property
def name(self) -> str:
return "glob"
@property
def description(self) -> str:
return (
"Find files by glob pattern (e.g. '*.py', 'src/**/*.ts' or '*.{ts,tsx}'). Prefer this over "
"running find/ls through exec. Returns paths relative to the search root, "
"most-recently-modified first. Noise directories (.git, node_modules, etc.) are "
"skipped below the pattern's literal path prefix; one named inside that prefix, as in "
"'src/node_modules/*.js', is entered. "
"Use it to locate a file before reading or editing it instead of "
"guessing at the path. Brace alternatives share one limit after deduplication and sorting. "
"A notice naming the limit means the result was cut there: raise limit or narrow the pattern. "
"A notice naming the traversal budget means the walk ran out of time: absence of a match is not "
"conclusive there, and only a narrower path or pattern helps."
)
@property
def parameters(self) -> dict[str, Any]:
base = super().parameters
props = dict(base["properties"])
if "pattern" in props:
props["pattern"] = {
**props["pattern"],
"description": "Glob pattern, e.g. '*.py', 'src/**/*.ts' or '*.{ts,tsx}'",
}
if "path" in props:
props["path"] = {**props["path"], "description": "Directory to search in (default: workspace root)"}
props["limit"] = {
**props["limit"],
"description": "Maximum unique entries across all patterns (default 1000). "
"Raise it when a notice says the result was cut at the limit; a traversal-budget notice "
"needs a narrower path or pattern instead.",
}
return {**base, "properties": props}
async def execute(self, pattern: str = "", limit: int | None = None, **kwargs: Any): # type: ignore[override]
if not pattern:
return "Error: missing required parameter 'pattern'."
try:
alternatives = expand_braces(pattern)
except ValueError as exc:
return f"Error: {exc}"
if len(alternatives) == 1:
return await super().execute(pattern=alternatives[0], limit=limit, **kwargs)
try:
base = self._resolve(kwargs.get("path", "."))
except PermissionError as exc:
return f"Error: {exc}"
ceiling = limit if limit is not None else self._DEFAULT_LIMIT
paths: list[str] = []
seen: set[str] = set()
cut = False
incomplete = False
for one in alternatives:
result = await super().execute(pattern=one, limit=limit, **kwargs)
text = result.model_text if hasattr(result, "model_text") else str(result)
if text.startswith(("Error: ", "Error running find: ")):
return result
if text == _NO_FILES:
continue
lines = text.splitlines()
# FindTool puts its notice after a blank line. A filename that
# merely starts with a notice's words is still a path.
if (
len(lines) >= 2
and not lines[-2]
and (_CHILD_CUT_RE.fullmatch(lines[-1]) or _CHILD_INCOMPLETE_RE.fullmatch(lines[-1]))
):
cut = cut or bool(_CHILD_CUT_RE.fullmatch(lines[-1]))
incomplete = incomplete or bool(_CHILD_INCOMPLETE_RE.fullmatch(lines[-1]))
lines = lines[:-2]
# A walk that hit its budget before any match still carries
# the engine's no-files line above the notice.
if lines == [_NO_FILES]:
lines = []
for line in lines:
if line and line not in seen:
seen.add(line)
paths.append(line)
budget_clause = (
"PARTIAL result: a pattern hit the search's traversal budget before finishing, "
"so absence of a match is not conclusive -- narrow the path or pattern"
)
if not paths:
missing = f"No files found matching pattern: {pattern}"
return f"{missing}\n\n({budget_clause})" if incomplete else missing
paths.sort(key=lambda path: self._mtime(base / path), reverse=True)
cut = cut or len(paths) > ceiling
shown = paths[:ceiling]
listing = "\n".join(shown)
if incomplete:
listing += (
f"\n(showing first {len(shown)} results across {len(alternatives)} patterns; "
f"{budget_clause}{', or raise limit' if cut else ''})"
)
elif cut:
listing += (
f"\n(showing first {len(shown)} results across {len(alternatives)} patterns; "
"PARTIAL result, raise limit or narrow the pattern)"
)
return listing
__all__ = ["BRACE_CAP", "GlobTool", "expand_braces", "is_notice"]