Skip to content

refactor(betterglob): smaller, faster glob with unified process handling - #15

Merged
dhaern merged 29 commits into
mainfrom
refactor/betterglob-reduction
Sep 28, 2026
Merged

dhaern merged 29 commits into
mainfrom
refactor/betterglob-reduction

Conversation

@dhaern

@dhaern dhaern commented Sep 28, 2026 •

Copy link
Copy Markdown
Owner

This branch rewrites the glob plugin (opencode-betterglob) from the inside: same matches, less code, faster, and importing it no longer touches the host process. No features removed.

Numbers

Measure Before Now
Production lines 4746 3892
Files 28 26
Tests 177 187
Bundle 146.5 KB 85,628 B
Commits 26

The bundle drops 40% because which and proper-lockfile moved out of the bundle and load from the host only when needed.

What got simplified

Three different child-process machines (supervisor, compat, output) became one (managed-process) with a single run function. The memo, previously tripled, is one with a stable key. ripgrep download streams with bounded memory and a single hash. Timers always cleaned up.

Fast stops

Any interrupted search (limit, cancel, timeout) took ~5 seconds to stop on a generic 5000 ms grace. Search grace is now 250 ms and stops land around 0.3 seconds. Runner abort grace dropped from 7250 to 2250 ms.

Case Before Now
Run a search 250 ms 44 ms
Early stop ~5 s ~0.3 s

Fixed bugs

  • Install temp dirs were abandoned on crashes. Older than 24 h are now purged under lock.
  • Importing the plugin patched host globals (process.emit, fs.close) through static imports. Loading is now lazy and import has no side effects.
  • Timeouts reported stage permission instead of normalize. The stage is now correct.
  • The stage was set before checking budget. The order is now correct.
  • Stream read errors in Windows searches are no longer lost.
  • Signal-death to exit-code conversion has its POSIX tests.

Dependencies

plugin 1.18.32, exact effect beta.83, 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 with APTO verdict and 0 open findings, 56 mutants killed by assertion, 187/0 suite with no hangs, byte-identical bundle across rounds, and a 6000-file smoke test on Node and Bun. Importing the plugin has no side effects.

Mutation red: omitting stream-error stop fails runner.spawn; 9216-byte stderr cap fails cap test; reordering truncate/status notes fails golden format.

Test typecheck rejects injected TS2322; 3 full suites and randomized seed 3757896726 pass; stream-error rerun-each=30 passes.
Port tests to async normalization, resolver, and cache validation; drop dead sync hash/read, sync probe, unused supervisor kill and hook branch.

Mutation red: deleting cache on read, inverting system/managed precedence, dropping absolute root anchoring, signalling saved PGID after stop (spied), and inverting parsed.truncated each fails its targeted regression. Test resolver concurrent install has injected runtime preflight to remove unrelated probe-timing race.
FF red: abort.test could not import abort primitive before implementation. Mutation red: dropping late rejection observation, skipping listener removal, shifting exact-cap comparison, reducing cap by one, and altering AbortWaitError message each failed focused tests. Full suite/typecheck/biome/build and declaration snapshot pass.
FF red: two default resolutions probed system/managed binaries twice and repeated runtime preflight; unsupported Linux arch platform test could not import candidates. Keep which per call; stamp dev/ino/size/mtime/ctime and managed metadata; unify version probe. Include early platform candidates, install IO, permission and runner reductions to meet phase LOC ceiling.

Mutation red: disabled memo, removed ctime/inode, cached negatives, skipped PATH lookup, omitted metadata stamp, omitted PATH from runtime key, and mapped EACCES as absence each failed focused regression tests. Suite 174 pass/9 skip, random seed 73910362; e2e stable median 42.8ms, stable strace 2 execve.
FF red: isolated Bun subprocess observed eager effect/lockfile imports and patched process.emit/reallyExit/fs.close. Mutation red: static effect or lock imports, unconditional effect import and bypassing non-thenable Effect each fail isolated/Effect tests. Promise asks do not import effect; Effect.sync/Effect.fail retain semantics.

Bun source import median 53.6ms (5 samples); Node dist import patches no globals. Suite 174 pass/9 skip, typecheck/biome/build and declaration snapshot pass; LOC 4373.
FF red: normal supervised success sent two release controls before removing crossSpawn auto-release; one-release test now passes. Port compat scenarios to process-output.test and preserve error identity/precedence, TERM→KILL, drain and watchdog behavior across direct and supervised collection.

Mutation red: reversed error precedence, omitted post-SIGKILL reader close (timeout), released on abort, wrapped original errors, duplicated release, and dropped tar extraction stderr. Combined process-output/runner.spawn rerun-each=30: 2220 pass; 3 full suites and randomized run green. Production 4165/4200 LOC, process-output 399/400; suite timing above final 7s target remains for F7.
…r interrupts

Pin exit-code fallback table before changes: limit without task status remains 0 (0→1 mutant red); preserve timeout 124, cancel 130, partial exit-2 and error precedence. Share the byte-capped collector across process and runner stderr, reuse the guarded reader destroyer and drain constant, and collapse cancel/timeout races into one interrupt deferred.

Exact-cap mutation 8192→8191 red for runner and collection; 82 focused tests and full 174 pass/9 skip. Production 4132/4150 LOC; runner 425/425, runner-output 141/145, supervised-search 190/190; test count unchanged.
FF red: a Bun.serve endless archive stream hung until abort instead of rejecting with the cached-file size-limit error. The pipeline now caps during transfer, removes partial downloads, and accepts an exact-cap archive. PF: known SHA-256, read/hash caps, non-regular rejection, exact glob/external/install ask payloads, pre-ask symlink denial, and win32 separator translation.

Mutation red: late cap, off-by-one cap, omitted partial cleanup, missing ask always value and dropped separator replacement. Production 4117/4120 LOC, 26 files; install-io 145/145, tool-context 179/180, rg-release 174/210; suite 176 pass/9 skip (7.20s, final ≤7s timing gate pending). Types, biome, build and public declaration diff clean.
…ures

F7: exercise both drain-timer lifecycles under fake timers; port the bounded read/hash test into the downloader fixture and consolidate duplicate setup/assertions without dropping scenarios. Tests 4871/4875 LOC, production 4117/4120 LOC in 26 files; 186 tests (177 pass/9 skip, 186 with rg). Rerun-each=30 process-output+runner.spawn 2250 green; 3 full suites 6.16/6.17/6.22s, randomized seed 1668998326 6.38s, rg-enabled 6.21s. Typecheck, biome, bundle and declaration diff pass. Five full-suite mutations red: precedence, ctime stamp, static lockfile, both drain timer cleanups, and safe PGID signal-0 probe.

Direct baseline/post plugin outputs are byte-identical for eleven fixtures; stable e2e median 43.89ms with two execve and no managed-cache reads/hashes. Bun import median 47.28ms and Node dist import patch no globals. Isolated opencode 1.18.32 debug-agent matrix also matches byte-for-byte, but the command resolves native glob (identical to --pure and ignores follow_symlinks), so genuine host plugin activation remains unverified; no core changes.
@greptile-apps

greptile-apps Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 4/5

[High risk] Refactors glob tool with dependency and process handling changes.

The PR is not ready to merge while mtime recovery can run past a satisfied result limit and produce a timeout.

Fix All in Claude CodeFindings

  1. P2 Active installations can be deleted ▶
Fix with agent prompt
### Issue 1
packages/opencode-betterglob/src/tools/glob/rg-publication.ts:134-139
If an installation takes more than 24 hours and another publisher reaches this cleanup, the active `.install-*` directory can be deleted. Download and extraction happen outside the publication lock and do not refresh the directory’s own mtime, so this can remove files still in use and cause the installation to fail. The age check alone does not establish that an installation has been abandoned.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
Summary

The PR refactors glob process handling and installation, while the latest changes also restructure grep search execution and the read tool. The new mtime replay recovery needs an early limit check; grep’s resolver can retain a managed binary after a preferred system binary becomes available.

Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[mtime discovery] --> B[sort candidate files]
  B --> C[replay batches of 64]
  C -->|batch error| D[retry files individually]
  D --> E[check result limit]
  C -->|success| E
Loading

Reviews (3) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..."

Comment on lines +134 to +139
if (
installTemporary
? details.isDirectory() && details.mtimeMs <= installStaleBefore
: details.mtimeMs <= staleBefore
) {
await rm(orphan, { force: true, recursive: installTemporary });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Active installations can be deleted If an installation takes more than 24 hours and another publisher reaches this cleanup, the active .install-* directory can be deleted. Download and extraction happen outside the publication lock and do not refresh the directory’s own mtime, so this can remove files still in use and cause the installation to fail. The age check alone does not establish that an installation has been abandoned.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/opencode-betterglob/src/tools/glob/rg-publication.ts
Line: 134-139

Comment:
**Active installations can be deleted** If an installation takes more than 24 hours and another publisher reaches this cleanup, the active `.install-*` directory can be deleted. Download and extraction happen outside the publication lock and do not refresh the directory’s own mtime, so this can remove files still in use and cause the installation to fail. The age check alone does not establish that an installation has been abandoned.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Codex Fix in Claude Code

@dhaern

dhaern commented Sep 28, 2026

Copy link
Copy Markdown
Owner Author

@greptile-apps updated review requested: one finding fixed, one discarded with reasons below.

F1 (rg-publication purge deleting active installs): discarded. The premise does not hold on this code. The .install-* mtime refreshes at creation, at download start and at staging, so only the middle stretch (body download, SHA, extract, locate) is uncovered. Cleanup only runs inside publishStagedBinary, called in production solely from downloader.ts:240 with an already downloaded, SHA-verified binary, under the publication lock. If run B deletes run A's directory, B is about to publish a valid binary, A's attempt is already superseded (it would find existingValid and no-op), nothing corrupts (metadata first, then binary, readers check SHA), and the next call picks up B's binary since failures are never memoized. Reaching the 24 h threshold with A alive needs a pathological 24 h+ download chain, a process freeze or a 24 h clock jump. The design already accepts the same failure model for the publication lock at 60 s stale; 24 h is 1440x more conservative. A real abandonment proof is not portable (no flock without native deps, PID checks break on reuse and shared caches, heartbeats share the freeze problem).

F2 (cleanup hiding download errors): fixed in 3970382. The partial-file rm is now best-effort (same pattern as the other cleanup rms), so the original error (size limit, HTTP/stream, ENOSPC/EIO, cancellation cause) survives in the log and in "Auto-install error". Pinned by an EISDIR assertion in the existing bounds test: red before, green after.

@greptile-apps

greptile-apps Bot commented Sep 28, 2026

Copy link
Copy Markdown

F1 is reasonably discarded. Given the mtime refresh points, cleanup runs only after a verified download under the publication lock, and the existing-valid check makes a superseded publisher a no-op, the 24-hour orphan threshold does not establish a practical active-install deletion bug under the stated invariants. The remaining risk requires an extreme download/freeze or clock-jump scenario and is consistent with the existing stale-lock failure model.

F2 is fixed in 3970382: partial archive removal is now best-effort, so the original download, size-limit, cancellation, or filesystem error remains observable. The added EISDIR regression assertion also directly covers the cleanup-failure path. I have no remaining finding from the previous review.

Tip: You can customize Greptile's behavior for this repo with .greptile/rules.md and .greptile/config.json.

@dhaern
dhaern merged commit 5c7e0a0 into main Sep 28, 2026
1 check passed
@dhaern
dhaern deleted the refactor/betterglob-reduction branch September 28, 2026 20:26
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