Skip to content

refactor(bettergrep): smaller, faster and deterministic search - #13

Merged
dhaern merged 38 commits into
mainfrom
refactor/bettergrep-reduction
Sep 28, 2026
Merged

dhaern merged 38 commits into
mainfrom
refactor/bettergrep-reduction

Conversation

@dhaern

@dhaern dhaern commented Sep 28, 2026 •

Copy link
Copy Markdown
Owner

This branch rewrites the search plugin (opencode-bettergrep) from the inside: same features, less code, faster, with several fixed bugs. Nothing about what the plugin does or how it is used changes.

Numbers

Measure Before Now
Production lines 8270 7316
Files 39 32
Tests ~270 300, with 79 snapshots
Bundle 159,537 B 159,394 B
Commits 34

Less code means less surface for bugs to hide in and less work for maintainers.

What got simplified

The plugin had several pieces doing almost the same thing through different paths. There is now one path per job: a single JSON stream reader, one pipe for running ripgrep or the GNU grep fallback, one factory for matches, one place for summaries. The custom logger, the process-compatibility shim and duplicated runners are gone. The worker pool is dynamic (16) and mtime replay works in batches of 64 instead of file by file.

Day to day use feels the same. Behavior is now uniform across paths because only one remains.

Fixed bugs

Each of these reproduced on the old code and now has its test:

  • Windows line endings (CRLF): the GNU grep fallback discarded those lines as unreadable. They now read fine.
  • Non-JSON ripgrep output hung the search forever and held a semaphore slot. It now fails fast and releases the slot.
  • Failed ripgrep auto-install (e.g. no network) was retried on every search and could block for 80 seconds. The failure is now remembered for 30 seconds.
  • Huge lines (1 MB): fully escaped and normalized before trimming to 2000 chars, about 800 ms and 349 MB of memory. Trimming happens first now: about 8 ms.
  • U+2028, U+2029 and carriage returns: GNU grep dropped those lines. They are now accepted.
  • Failed stat on two or more files while sorting by date produced NaN and left the order to chance. It is now pinned and tested.
  • A synchronous system failure (e.g. ETXTBSY) reported the wrong backend. It now reports grep for GNU grep.
  • Files deleted mid-search now always sort last, pinned by test in both orders.
  • A redundant guard in the retry memo was removed (−5 lines, no tests since there is nothing left to pin).

Deterministic ordering

Date sorting now tie-breaks on path bytes, and child processes run with LC_ALL=C.UTF-8 and an empty LANGUAGE so messages always parse in English on any machine. In practice: the same search returns the same results in the same order on Linux, under Bun or Node, with the system in any language.

Measured performance

Case Before Now
Hot ripgrep resolve 3.72 ms 0.009 ms
mtime replay serial, process by process batches of 64, ~20x faster
Non-JSON output search hang 33 ms failing fast
1 MB line ~800 ms 8.5 ms

Dependencies

plugin 1.18.32, exact effect beta.83 (no nested copies), TypeScript 7.0.2, Biome 2.5.14, @types/node from v24, bun-types 1.4.2, which 7 and packageManager [email protected].

Verification

Severity review (P0–P3) with an independent APTO verdict, full mutant matrix killed by assertion, 300/0 suite with unchanged 79 snapshots, clean check and typecheck, and a 6000-file smoke test on Node and Bun. No behavior changes: everything it did before still works.

@greptile-apps

greptile-apps Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[High risk] Refactors search tool with broad dependency and internal API changes.

The PR appears safe to merge based on the changes since the previous review.

Summary

The PR consolidates grep execution, parsing, fallback handling, and result formatting while adding deterministic ordering and broader tests. Since the previous review, it adds a ten-minute expiry for a cached rejected ripgrep candidate so the resolver can probe it again. No new actionable issue was established.

Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Search requests CLI] --> B{Cached CLI valid?}
  B -- Yes --> C[Use cached backend]
  B -- No --> D[Probe system ripgrep]
  D -- Supported --> E[Use ripgrep]
  D -- Unavailable --> F[Check managed ripgrep]
  F -- Available --> E
  F -- Unavailable --> G[Use GNU grep if supported]
  G --> H{Install retry due?}
  H -- No --> C
  H -- Yes --> I[Attempt ripgrep install]
Loading

Reviews (4) · Last reviewed commit: "fix(bettergrep): expire rejected rg afte..."

@dhaern

dhaern commented Sep 28, 2026

Copy link
Copy Markdown
Owner Author

@greptile-apps updated review requested: both findings were real regressions from this PR, both fixed.

F1 (probe timeout can hang): confirmed. The exit wait relied on close, which never arrives while a descendant holds stdio open, so the timeout kill never took effect and the existing bounded drain never ran. Fixed in 4613f15: the wait now races against the termination stopped promise, so the probe resolves on kill and the bounded drain works again. Pinned by a fake-spawn test (PassThrough pipes that never close, no real processes): times out before the fix, passes after.

F2 (cached fallback hides ripgrep): confirmed. The memo only invalidated on PATH text, cacheDir or binary stamp, so an rg installed into an already-listed PATH directory never displaced a cached GNU grep. Fixed in bda4069: memo validity now also requires a stored rg backend or no rg on PATH (one spawnless lookup, only on the GNU-memo path). GNU is still memoized, preserving the intentional ETXTBSY behavior. Pinned by an injected-deps test: grep first, rg after it appears.

@greptile-apps

greptile-apps Bot commented Sep 28, 2026

Copy link
Copy Markdown

Both reported regressions are confirmed fixed.

  • Probe timeout can hang: runProbe now races the exit wait against termination.stopped, so a timeout or cancellation resolves immediately even when descendants keep stdio open. The bounded drain then destroys inherited pipes if needed. The added fake-spawn test covers pipes that never close.
  • Cached fallback hides ripgrep: GNU fallback memo validation now performs a spawnless rg lookup and invalidates the memo when rg becomes available, allowing the normal supported-version probe to select it. The added injected-dependency test covers GNU first, then rg appearing on the same PATH.

The fixes in 4613f15 and bda4069 address both findings; I have no remaining issue for either comment.

@dhaern

dhaern commented Sep 28, 2026

Copy link
Copy Markdown
Owner Author

@greptile-apps updated review requested: the follow-up finding was real, fixed.

F3 (unsupported rg defeats fallback caching): confirmed against our own F2 fix. The validity check treated any rg on PATH as a reason to drop the cached GNU result, so an unsupported or hanging rg forced a re-probe on every search (up to the 5 s probe timeout each). Fixed in 2743bf2: the memo now stores the rejected rg candidate's stamp (ino/size/mtime/mode), and GNU stays memoized while that candidate is unchanged. A new, moved or updated rg still invalidates the cache, and the hanging-rg case now costs one bounded probe instead of one per search. The rewritten F2 test pins both directions with zero new tests: one probe across searches while the candidate is unchanged, rg picked up after it changes.

@greptile-apps

greptile-apps Bot commented Sep 28, 2026

Copy link
Copy Markdown

Confirmed. F3 is fixed in 2743bf2: the GNU fallback memo now records the rejected rg candidate’s filesystem stamp and reuses the fallback while that candidate is unchanged, avoiding repeated bounded probes. Changes to the candidate invalidate the memo so a newly supported rg is picked up. The rewritten resolver test covers both unchanged-candidate reuse and subsequent rg activation. I have no remaining issue for this finding.

@dhaern

dhaern commented Sep 28, 2026

Copy link
Copy Markdown
Owner Author

@greptile-apps updated review requested: the follow-up finding was real, fixed.

F4 (transient failure locks in fallback): confirmed. A transient rg --version failure (load-time timeout, EAGAIN/EMFILE) with no auto-install pinned GNU grep indefinitely when the binary recovered unchanged. Our prior tradeoff acceptance was wrong: expiry was avoidable with the existing 10-minute negative-cache TTL, keeping at most one re-probe per 10 minutes. Fixed in 25ab21e: the memo records its creation time and the GNU branch expires after the TTL unless the rejected candidate changed. A transient rg now recovers within 10 minutes, same as the managed binary; a hanging one costs one bounded probe per 10 minutes. The existing TTL test covers both directions with zero new tests.

@dhaern
dhaern merged commit 5323c2c into main Sep 28, 2026
1 check passed
@dhaern
dhaern deleted the refactor/bettergrep-reduction branch September 28, 2026 20:20
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.

1 participant