Skip to content

fix(grep): use extended regular expressions in the system fallback - #4984

Open
RivenZhang01 wants to merge 7 commits into
OpenHands:mainfrom
RivenZhang01:fix/grep-extended-regex
Open

RivenZhang01 wants to merge 7 commits into
OpenHands:mainfrom
RivenZhang01:fix/grep-extended-regex

Conversation

@RivenZhang01

@RivenZhang01 RivenZhang01 commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

HUMAN:

I want the grep fallback to return reliable results on machines without ripgrep. Common search patterns should not silently miss matches or select the wrong files when the Agent falls back to system grep.


AGENT:

Why

When ripgrep is unavailable, the system grep fallback uses basic regular expressions. Patterns such as ^(foo|bar)+[0-9]{2}$ miss valid matches, while escaped punctuation can match the wrong file. On Windows, Git/MSYS argument processing can also remove regex backslashes.

Summary

  • Enable extended regular expressions in GrepExecutor and the SDK terminal-compatibility fallback.
  • Pass GrepExecutor patterns through binary stdin with grep -f -, preserving backslashes and avoiding Windows newline translation.
  • Add regression coverage for extended operators, escaped punctuation, and empty patterns using actual system grep.

Issue Number

Fixes #4983.

How to Test

After make build:

  • uv run pytest tests/tools/grep tests/sdk/agent/test_tool_call_compatibility.py -q

The standalone reproduction script is preserved in dc7024af. Run .venv/bin/python .pr/repro_grep_regex.py from that revision to repeat the historical comparison. The 17 temporary .pr/ files were removed from this branch as requested during review.

The recorded macOS run passed all 86 focused tests and both reproduction cases. The automated review repeated the focused suite on dc7024a: 74 passed, 12 skipped because ripgrep was unavailable.

The native Windows probe reproduced the escaped-pattern failure. The binary-stdin validation passed the transport cases and the Windows tools test group: 732 passed, 105 skipped, using the upstream job's exclusions. CI for head dc7024a has passed tools-tests, sdk-tests, windows-tests, and pre-commit.

Live Agent comparison — October 5

The same OpenHands Agent conversation ran against base 76e9e25 and patched revision 486b46f, using DeepSeek Flash on macOS 15.6. Both used the same prompt and fixtures, with PATH containing only a symlink to /usr/bin/grep, making rg unavailable.

  • ^(foo|bar)+[0-9]{2}$: base returned no matches; the patched revision returned matching.txt.
  • ^foo\(bar\)\+$: base returned other.txt; the patched revision returned matching.txt.

Each conversation made the two requested grep calls, received both observations, then finished normally without pattern retries or Python fallback.

Environment, tool events, summaries, logs, and frozen harness · Reproduction instructions

Production code is unchanged from the live-tested revision. Subsequent changes add a POSIX guard to the terminal integration test and strengthen the evidence validator. The two saved conversations pass the stronger checks; the validator's 12 offline tests also pass.

Video/Screenshots

CLI output, actual Agent tool events, and Windows CI logs are linked above.

Design Doc

Reproduction and transport details.

Type

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

Notes

The live comparison covers the macOS GrepTool path. No live Windows conversation, live terminal-compatibility conversation, or repository benchmark was run. VascoSch92 confirmed the fix works against current main and requested the artifact cleanup before merge.

This fixes common extended-regex syntax and pattern transport; it does not make all regex dialects equivalent. No public API, persisted schema, dependency, prompt, or tool-description changes.

Co-authored-by: openhands <openhands@all-hands.dev>
@github-actions

github-actions Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor
  ✅ **PR Artifacts Cleaned Up**

  This PR no longer adds or changes files under `.pr/`.

@RivenZhang01
RivenZhang01 marked this pull request as ready for review September 12, 2026 06:12
@all-hands-bot

Copy link
Copy Markdown
Collaborator

🚦 CI is currently failing on this PR's latest commit.

Please fix the failing checks before OpenHands reviews it - this is re-checked automatically once you push a new commit. (A maintainer can also request @all-hands-bot as a reviewer to have it reviewed regardless of CI status.)

This is an automated check - no AI was used to generate this comment.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This review was posted by an AI agent (OpenHands).

Review of 2a5d21633050ea05b54fe14f9241b2c6917e571b

Change under review: +207/-4 across 8 files. Production changes are limited to
openhands-sdk/openhands/sdk/agent/utils.py (adds -E to the system-grep terminal
fallback) and openhands-tools/openhands/tools/grep/impl.py (adds -E, reads the
pattern via grep -f - with binary stdin, drops text=True, decodes stdout with
os.fsdecode). The remaining files are tests plus .pr/ evidence.

What I verified in the workspace

  • Repository guidance read: root AGENTS.md and .agents/skills/custom-codereview-guide.md.
  • uv run pytest tests/tools/grep tests/sdk/agent/test_tool_call_compatibility.py -q
    → 74 passed, 12 skipped (the skips are the ripgrep-consistency class, since
    rg is not installed here). The new -E and -f - cases pass.
  • .venv/bin/python .pr/repro_grep_regex.py → both cases pass; system grep now
    resolves ^(foo|bar)+[0-9]{2}$ and ^foo\(bar\)\+$ against the intended file.
  • Independent comparison of rg vs grep (BRE) vs grep -E (ERE) on representative
    patterns (a{2}, a\+b, x\|y, a+b) confirms -E brings the system-grep
    backend materially closer to the ripgrep backend, which is the stated intent.
  • Spot-checked the new stdin transport (pattern + "\n"): empty patterns still
    match only non-empty files, and a trailing newline does not expand into an extra
    empty pattern. Behavior is consistent with the previous argv path and with
    ripgrep / the Python fallback. No regression found.

No material code defects found

I did not find a demonstrated bug, security issue, or breaking behavior change on
this head. The -E switch is the correct alignment with the ripgrep primary
backend, and routing the pattern through binary stdin is a sound way to preserve
escapes on Windows and avoid LF→CRLF translation.

Two process points for the maintainer (no inline findings)

  1. Eval-risk policy. This modifies tool execution and stdin/stdout handling,
    which custom-codereview-guide.md explicitly lists as eval-risk. The PR states
    "No agent benchmark was run" and provides no openhands-eval-monitor link, so
    per the repo review policy I am leaving a COMMENT rather than an APPROVE, for a
    maintainer to run lightweight evals before merge.
  2. Upstream CI has not executed on this head. For 2a5d2163, the workflow runs
    for Run tests, Pre-commit checks, Agent Server, etc. are all
    action_required (fork approval pending). The only completed checks are the
    PR-description/artifact checks. The validation cited in the PR comes from the
    author's fork, so the upstream suite and the Windows tools group still need to
    run on the exact head.

Verdict: no changes requested on the code itself; deferring the eval/CI items to a
human maintainer.

✅ APPROVED

@neubig neubig left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This review was submitted by an AI agent (OpenHands) on behalf of @neubig.

The low-level implementation and validation are strong: the public GrepExecutor reproduction uses real system grep, the native Windows run demonstrates the argv/text-stdin failure and binary-stdin recovery, and the focused suites pass. However, this changes agent tool execution and the terminal compatibility path, and the current evidence does not show the affected behavior in a live OpenHands conversation.

Before approval, please provide a small authentic before/after live-agent run with ripgrep unavailable:

  1. On the base revision, ask a running OpenHands agent to perform a search using an affected extended or escaped regex and show the incorrect/missing result.
  2. Repeat the same prompt/workflow on this PR head and show the correct result.
  3. Include the emitted grep tool call or normalized terminal action and the resulting observation returned to the agent, so it is clear the real agent/tool/terminal path—not only a constructed test invocation—was exercised.
  4. State the runtime environment and how rg was made unavailable.

The existing Windows probe remains good evidence for the transport mechanism, but it does not exercise an actual agent conversation. Per the repository review policy for tool execution and stdin/stdout changes, I am withholding approval pending this live evidence and human eval review.

Add a maintainer-run base/head conversation with strict tool-event validation. Live model execution remains pending.

Co-authored-by: openhands <openhands@all-hands.dev>
@RivenZhang01
RivenZhang01 force-pushed the fix/grep-extended-regex branch from 4f5b0db to 486b46f Compare September 26, 2026 02:20
@RivenZhang01

Copy link
Copy Markdown
Contributor Author

Thanks for clarifying the missing evidence. I added a real Agent reproduction script and run instructions in 486b46fb.

It runs the same prompt and fixtures on the base and PR head, with rg unavailable. It records the model-generated grep calls and the observations returned to the Agent, and checks both patterns without retries. This covers the GrepTool path; the existing Windows transport tests are separate evidence.

I do not have a working model API available, so the live Agent validation is still pending. Fixture preparation, offline conversation construction, and the applicable pre-commit checks pass, but those do not satisfy the requested live run.

Could a maintainer run the two commands with a configured model and attach the resulting environment, event, and summary files? The instructions include the base revision and expected results for both versions. Thanks!

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This review was posted by an AI agent (OpenHands).

Review of 486b46fb8c9a0fadb544fbc1854f3a177c1022dc

Scope: this change belongs in this repository (SDK tool execution + the SDK
terminal-compatibility fallback), and the linked issue #4983 is open, bug,
tools, sdk, ready-for-dev. The production diff is unchanged from
2a5d2163: openhands-sdk/openhands/sdk/agent/utils.py adds -E to the
system-grep terminal fallback, and openhands-tools/openhands/tools/grep/impl.py
adds -E and reads the pattern via grep -f - with binary stdin. This new commit
(486b46fb) only adds .pr/ evidence files — no production or test code changed.

What I verified on this head

  • uv run pytest tests/tools/grep tests/sdk/agent/test_tool_call_compatibility.py -q
    → 74 passed, 12 skipped (skips are the ripgrep-consistency class; rg is
    not installed here).
  • .venv/bin/python .pr/repro_grep_regex.py → both cases pass against real system
    grep with rg unavailable.
  • GitHub Actions for this exact head are now green: Run tests, Pre-commit checks, Agent Server, REST API breakage checks, Persisted settings compatibility checks, TypeScript client CI, and Review Thread Gate all
    report success.
  • No material code defect, security issue, or behavior regression found. The -E
    flag is the right alignment with the ripgrep primary backend, and the binary
    stdin transport preserves escapes and avoids Windows newline translation.

Outstanding requested evidence (why this is a COMMENT, not an approval)

The existing maintainer review on this PR requested an authentic before/after
live-agent run with ripgrep unavailable, including the emitted grep tool call and
the observation returned to the agent. That request is still unmet on this head:

  • .pr/live-grep-agent.md line 3 states "Status: not run against a real model."
  • The PR body's "Real Agent validation (pending)" section says no live model run
    has been performed and asks a maintainer to run it.
  • The contributor's latest comment confirms the live Agent validation is still
    pending and that only fixture preparation and offline object construction pass.

The new script is a well-formed harness, but a harness plus pending instructions is
not the requested evidence. Per custom-codereview-guide.md, changes to tool
execution and terminal stdin/stdout handling are eval-risk and must not be approved
without eval evidence (an openhands-eval-monitor link plus maintainer
confirmation). No such evidence is present, and the maintainer has explicitly
withheld approval pending the live run and human eval review.

No inline findings: the gap is evidence/validation, not a defect on a changed line.
Recommend a maintainer run the two documented commands (base and head) and attach
the resulting environment.json, events.jsonl, and summary.json, then complete
the human eval review before merge.

🔄 CHANGES REQUESTED

Co-authored-by: openhands <openhands@all-hands.dev>
@RivenZhang01

Copy link
Copy Markdown
Contributor Author

Thanks for clarifying what was missing. I’ve now run the same conversation on the base and PR head using a real OpenHands Agent with DeepSeek Flash.

Both runs used macOS 15.6, Python 3.13.13, the same prompt and fixtures, and a PATH containing only a symlink to /usr/bin/grep, so rg was unavailable.

Pattern Base 76e9e250 PR head 486b46fb
^(foo|bar)+[0-9]{2}$ No matches — missed the correct file matching.txt
^foo\(bar\)\+$ other.txt — matched the wrong file matching.txt

Each Agent made the two requested grep calls without changing or retrying the patterns, received the observations, and finished with an accurate report of those results. Both conversations completed normally, with no system-grep failure or Python fallback.

The evidence and reproduction notes include each run’s environment.json, events.jsonl, summary.json, and runtime log. Local path prefixes are sanitized. The new commit only strengthens the validation harness and adds evidence; the production fix is unchanged.

This covers the real GrepTool path on macOS. The earlier native Windows transport checks are separate; I haven’t run a live Windows conversation, the terminal compatibility path, or a benchmark.

Could you take another look when you have a chance?

Co-authored-by: openhands <openhands@all-hands.dev>

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This review was posted by an AI agent (OpenHands).

Review of dc7024af36859bfc8cd52f00f3e567bb3bd3f8f9

Scope: this change belongs in this repository (SDK tool execution plus the SDK
terminal-compatibility fallback), and the linked issue #4983 is open with bug,
priority:low, tools, sdk, and ready-for-dev. The production diff is
identical to the previously reviewed 486b46fb: openhands-sdk/openhands/sdk/agent/utils.py
adds -E to the system-grep terminal fallback, and
openhands-tools/openhands/tools/grep/impl.py adds -E and reads the pattern via
grep -f - with binary stdin (os.fsencode / os.fsdecode, no text=True).

The maintainer-requested live-agent evidence is now provided and checks out

The prior review on this PR asked for an authentic before/after live-agent run
with ripgrep unavailable, including the emitted grep call and the returned
observation. That gap is now closed. I verified the new artifacts directly in the
workspace:

  • .pr/live-grep-2026-10-05/base/summary.json and head/summary.json each show
    exactly two real grep calls plus a later finish, final_status: finished,
    empty conversation_errors, grep_fallbacks, and validation_errors, and
    matches_expected_revision_behavior: true.
  • Base reproduces the defect: ^(foo|bar)+[0-9]{2}$ returns no matches and
    ^foo\(bar\)\+$ returns escaped/other.txt. Head returns matching.txt for
    both patterns. The finish messages accurately report the observations.
  • Recorded provenance is self-consistent and matches the real code:
    grep_source_sha256 in head/environment.json is
    469cca61…982ad959, which is exactly the current
    openhands-tools/openhands/tools/grep/impl.py; base records
    904f785c…6054e2a3, which matches 76e9e250:…/grep/impl.py. The frozen
    harness hash 7c7e1ae7…8706bdbc matches the preserved script, and uv.lock
    matches the recorded uv_lock_sha256.
  • git diff --stat 486b46fb dc7024af -- openhands-sdk openhands-tools tests shows
    the only production/test change since the live-tested revision is a 4-line
    POSIX guard on the terminal compatibility test, so the live evidence still
    covers the reviewed code.
  • .pr/test_live_grep_event_sequence.py passes locally (12 passed) and revalidates
    the two recorded streams. No API key or authorization header is present in the
    published evidence.

Verification on this head

  • uv run pytest tests/tools/grep tests/sdk/agent/test_tool_call_compatibility.py -q
    → 74 passed, 12 skipped (the skips are the ripgrep-consistency class; rg
    is not installed here).
  • All GitHub Actions checks for dc7024af are green, including tools-tests,
    sdk-tests, windows-tests, agent-server-tests, pre-commit,
    coverage-report, REST API (OpenAPI), and unresolved-review-threads.
  • No material code defect, security issue, or behavior regression found. -E
    aligns the fallback with the ripgrep primary backend, and the binary stdin
    transport preserves escapes while avoiding Windows newline translation. The new
    os.name == "nt" skip is appropriate for a test that depends on POSIX shell
    quoting.

Why this remains a COMMENT rather than an approval

custom-codereview-guide.md treats tool execution and terminal stdin/stdout
handling as eval-risk and requires eval evidence — an openhands-eval-monitor
link plus a human maintainer comment confirming the results — before approval.
This PR still states "No agent benchmark was run", there is no eval-monitor link,
and the maintainer review explicitly withheld approval pending this live evidence
and human eval review. The live evidence portion is now satisfied; the human
eval/human maintainer confirmation is the remaining item, which is not mine to
grant.

No inline findings: the remaining item is validation/handoff, not a defect on a
changed line. Recommend the maintainer confirm the live evidence and complete the
human eval review before merge.

🔄 CHANGES REQUESTED

@VascoSch92

Copy link
Copy Markdown
Member

Hey @BORAN002, thanks for this fix and for the live-agent runs. I tested it against current main and it works on my side, so I'd like to get it merged.

One small change before that: could you remove the 17 files under .pr/ from this branch? Otherwise they land on main and stay there until the next release, and the evidence stays linked from this thread through the earlier commits. I tried to push that commit myself, but maintainer edits are turned off on this PR. If you'd rather I do it, enable "Allow edits by maintainers" in the PR sidebar and let me know.

The push will also refresh CI, since the last run is from October 5. Thanks again!

Co-authored-by: openhands <openhands@all-hands.dev>
@RivenZhang01 RivenZhang01 reopened this Nov 9, 2026
@RivenZhang01

Copy link
Copy Markdown
Contributor Author

Thanks for testing this against current main, @VascoSch92! I've removed all 17 .pr/ files in c49f036. The earlier evidence links still work.

The push didn't start the test workflows, so I briefly reopened the PR to trigger them. The refreshed CI is now green, and all 86 focused tests also pass locally.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This review was posted by an AI agent (OpenHands).

Review of c49f0367ed85c91ed4cbaa26dd323a92b08f018b

Scope gate: this change belongs in this repository — it touches SDK tool
execution (openhands-tools/openhands/tools/grep/impl.py) and the SDK
terminal-compatibility fallback (openhands-sdk/openhands/sdk/agent/utils.py).
The linked issue #4983 is open with bug, priority:low, tools, sdk, and
ready-for-dev.

Technical verification on this head (fresh pass)

  • The production diff is unchanged from the previously reviewed 486b46fb/dc7024af;
    the only delta on c49f0367 is removal of the 17 .pr/ evidence files,
    which the maintainer explicitly requested.
  • I re-verified the fix behavior against real system grep:
    • ^(foo|bar)+[0-9]{2}$ with -E now matches FooBAR12 and correctly
      rejects foo12 extra.
    • ^foo\(bar\)\+$ matches the literal text foo(bar)+ and not foobar,
      confirming the binary-stdin transport (grep -f - with os.fsencode/
      os.fsdecode) preserves escaped punctuation that argv passing lost.
    • An empty pattern arrives as a single blank line and matches all lines
      (rc=0), consistent with the Python fallback's empty-string regex search.
  • The return-code contract is unchanged: 0/1 are treated as success, other
    codes still fall back to the Python search, so the new flags introduce no
    new failure path.
  • Focused suite:
    uv run pytest tests/tools/grep tests/sdk/agent/test_tool_call_compatibility.py -q
    → 74 passed, 12 skipped (skips are the ripgrep-consistency class; rg
    is not installed in this environment). The new regression tests run real
    system grep rather than mocks.
  • All GitHub Actions checks for c49f0367 are green, including tools-tests,
    sdk-tests, windows-tests, agent-server-tests, and pre-commit.

No material code defect, security issue, or behavior regression was found on
this head. The maintainer has also independently confirmed the fix works
against current main and requested the artifact cleanup that this commit
performs.

Why this remains a COMMENT rather than an approval

custom-codereview-guide.md classifies tool calling/execution and terminal
stdin/stdout handling as eval-risk: approval requires eval evidence — an
openhands-eval-monitor.vercel.app link showing a completed benchmark run
plus a human maintainer comment confirming the results. This PR still states
"No agent benchmark was run" and contains no eval-monitor link; the maintainer
comment here confirms functional correctness but not a completed benchmark
run. This matches the prior review on dc7024af, which withheld approval for
the same reason.

No inline findings: the remaining item is the eval-risk evidence/human
maintainer handoff, not a defect on a changed line. Recommend a human
maintainer complete the eval review before merge.

🔄 CHANGES REQUESTED

@RivenZhang01

RivenZhang01 commented Nov 16, 2026 via email

Copy link
Copy Markdown
Contributor Author

@RivenZhang01

Copy link
Copy Markdown
Contributor Author

Thanks for testing the fix, @VascoSch92. I’ve removed the 17 files under .pr/ and enabled maintainer edits on this branch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: system grep fallbacks misinterpret extended regular expressions

4 participants