Repository navigation
Conversation
|
Warning Review limit reached
Next review available in: 10 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (8)
Comment |
|
Found 2 issues this PR may fix:
🤖 Generated with Claude Code |
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🟡
src/watcher/WindowsWatcher.rs:503-517— Theplatform_scratchsnapshot is taken once per completion, but whenevent_id >= 128triggers a mid-loopprocess_watch_event_batch→on_file_update→flush_evictions(),swap_removereorders the live watchlist while the innerfor item_idx in 0..n_itemsloop keeps emitting indices from the frozen snapshot. SubsequentWatchEvent.indexvalues then point at whatever entryswap_removemoved into that slot in the live watchlist, so the wrong file can be dispatched (or a real change dropped by the bounds check). Re-snapshottingplatform_scratchunder the mutex right after the mid-batchprocess_watch_event_batchcall would keep indices consistent.Extended reasoning...
What the bug is
watch_loop_cyclenow snapshotswatchlist.file_pathintothis.platform_scratchonce per outer-loop iteration (once perReadDirectoryChangesWcompletion), andn_itemsis captured from that snapshot. The innerfor item_idx in 0..n_itemsloop then writesitem_idxintoWatchEvent.indexviacreate_watch_event(&event, item_idx as WatchItemIndex).However, when the 128-slot
watch_eventsbuffer fills (event_id >= this.watch_events.len()),process_watch_event_batchis called mid inner loop. That reachesdispatch_file_updates→hot_reloader::on_file_update, whose_flushscopeguard (hot_reloader.rs:885-888) unconditionally callsctx.flush_evictions(). On Windows aFILE_ACTION_REMOVEDmaps toOp::DELETE, which triggersctx.remove_at_index(...)(hot_reloader.rs:919), soflush_evictions()executesself.watchlist.swap_remove(item)— reordering and shrinking the live watchlist.Control then returns to the inner loop, which keeps matching against the unchanged
platform_scratchsnapshot and emittingWatchEvent { index: item_idx }. The nextprocess_watch_event_batchhands those events plus&self.watchlist(post-swap_remove) toon_file_update, which readsfile_paths[event.index],hashes[event.index],kinds[event.index]from the live watchlist.event.indexnow resolves to whatever entryswap_removemoved into that slot.Step-by-step example
- Watchlist has 200 entries;
platform_scratchsnapshots paths[P0, P1, …, P199],n_items = 200. - A large completion (e.g.
git checkout) delivers many events. The first event isFILE_ACTION_REMOVEDforP50; the inner loop matchesitem_idx = 50(Equal) plus its parent dir, and continues accumulating matches untilevent_idhits 128. - Mid-loop
process_watch_event_batchruns →on_file_updateseesOp::DELETEat index 50 →remove_at_index→ scopeguard drop →flush_evictions()→watchlist.swap_remove(50). Now live slot 50 holds what wasP199; live length is 199. - Loop resumes with
event_id = 0, still using the frozen snapshot. A later event in the same completion is aModifiedonP50(common: many editors emit remove+create/write on save; git checkout deletes then recreates).platform_scratch[50]still equalsP50, sois_parent_or_equalreturnsEqualandWatchEvent { index: 50, op: WRITE }is emitted. - In the second
process_watch_event_batch,on_file_updatereadsfile_paths[50]from the live watchlist — that's nowP199. The reloader enqueues a reload for the wrong module (or, if index 50 now holds a directory entry, walks the directory branch instead). Meanwhile a change to oldP199matched at snapshot index 199 is silently dropped by theevent.index >= file_paths.len()guard at hot_reloader.rs:901. - Additionally, if a later event in the same completion is a DELETE that matches snapshot index 50,
remove_at_index(File, 50, …)evicts the wrong live entry permanently.
Why existing code doesn't prevent it
The bounds check at hot_reloader.rs:901 (
event.index as usize >= file_paths.len()) only prevents an OOB panic; it can't detect that a still-in-bounds index now names a different entry afterswap_remove. Nothing between the mid-batch flush and the resumed loop refreshesplatform_scratchorn_items.Regression vs. pre-PR
Pre-PR, the path (
this.watchlist.items_file_path()[item_idx]) andn_itemswere re-read live on every inner iteration. After a mid-batchswap_remove, the next event's item scan therefore matched against the post-swap layout — the same layouton_file_updatereads — so indices stayed consistent (at the cost of the unlocked-realloc race this PR fixes, and a possible OOB panic ifitem_idxran past the shrunk length within the same event's item scan). The PR trades that for a wider window of silent wrong-index dispatch: the staleness now spans the entire remaining completion, not just the tail of one event's item scan.Impact & severity
Windows-only, dev-tool watcher, and requires ≥128 matched
(event × watched-item)pairs from a single 64 KiBReadDirectoryChangesWbuffer with at least oneFILE_ACTION_REMOVEDin the first 128 — realistic mainly duringgit checkout/ branch switch in a large watched tree, but still an edge case. Consequence is a spurious or missed hot reload (self-correcting on the next save), or in the worst case a wrong watchlist entry evicted so one file stops hot-reloading until restart. No crash/UB (bounds-checked). Given pre-PR was also broken on the same trigger (potential panic), this is a lateral trade rather than a clean regression, so nit — not worth blocking a PR that fixes the far more common workspace-not-watched bug.Suggested fix
After the mid-batch
process_watch_event_batch(this, event_id)?;call (inside theif event_id >= this.watch_events.len()block), re-take the snapshot under the mutex and updaten_items:process_watch_event_batch(this, event_id)?; { let _guard = this.mutex.lock_guard(); this.platform_scratch.clear(); for p in this.watchlist.items_file_path() { this.platform_scratch.push(p.as_ref().to_vec().into_boxed_slice()); } } // n_items must be mutable at its declaration n_items = this.platform_scratch.len();
(and
breakout of the currentfor item_idxloop so it restarts against the freshn_items). Alternatively, hoist the snapshot to a small helper and call it both at the top of the outer loop and after each mid-batch flush. - Watchlist has 200 entries;
-
🔴
src/watcher/WindowsWatcher.rs:428-436—stop()now iterates&self.watcherswithoutWatcher.mutex, but this PR madeself.watchersaVecthat transpiler threads push to (viaadd_file→ensure_watch_root_covers→add_root) under that mutex. On thewatch_loopErrpathrunningis still set, so a concurrentVec::pushrealloc whilestop()is iterating is a UAF on the freed backing buffer. Takeme.mutex.lock_guard()inthread_mainaroundme.platform.stop()(or take it insidestop()itself).Extended reasoning...
What the bug is
WindowsWatcher::stop()readsself.watcherswithout holdingWatcher.mutex:pub(crate) fn stop(&mut self) { unsafe { for dw in &self.watchers { w::CloseHandle(dw.dir_handle); } w::CloseHandle(self.iocp); } }
The field's own doc comment says "Appended under
Watcher.mutex; never shrunk", and every other accessor of the Vec (covers(),add_root()) is documented and called with that mutex held.stop()is the one accessor that skips it.Code path that triggers the race
Writer (transpiler / JS thread, mutex held):
RuntimeTranspilerStore::run_from_worker_thread→Watcher::add_file(takesself.mutex.lock()) →append_file_maybe_lock::<_, false>→append_file_assume_capacity→ensure_watch_root_covers(parent_dir)→self.platform.add_root(dir)→self.watchers.push(dw).Vec::pushmay reallocate the backing storage.Reader (watch thread, mutex NOT held):
Watcher::thread_main→me.watch_loop()returnsErr(err)(e.g.prepare()/GetQueuedCompletionStatus/ null-overlappedfailure) →me.platform.stop()→for dw in &self.watchers.thread_maindoes not holdme.mutexaround this call:Err(err) => { me.watchloop_handle.store(false); me.platform.stop(); // <-- no lock if me.running.load() { ... } }
Why nothing prevents it
On the
Errpathrunninghas not been cleared — onlyshutdown()clears it — so a transpiler thread insideadd_fileproceeds normally.add_filedoes not checkrunningorwatchloop_handlebefore pushing. And unlikenext(), which was carefully designed to identify the firingDirWatcherfrom the boxedlpOverlappedaddress so it never touches the Vec,stop()iterates the Vec directly.Before this PR the Windows
append_file_assume_capacity/append_directory_assume_capacitybranches only calledis_parent_or_equal(self.top_level_dir(), file_path)and never touchedself.platform, andstop()closed a single fixed inlineself.watcher.dir_handle. Soself.platformwas watch-thread-only andstop()was safe. This PR is what madeplatform.watchersa cross-thread Vec, sostop()becomes the first (and only) unlocked accessor — the race is newly introduced here.Step-by-step proof
- The watch thread is inside
watch_loop_cycle→this.platform.next(Timeout::Infinite).GetQueuedCompletionStatusreturnsrc == 0with a non-timeout error (orrc != 0withoverlapped == null), sonext()returnsErr, which propagates throughwatch_loop_cycle→watch_loop→thread_main. thread_mainenters theErr(err)arm, storeswatchloop_handle = false, and callsme.platform.stop().me.mutexis not held;me.runningis stilltrue.- Concurrently, a transpiler thread resolves an import to a workspace package outside every existing root (the exact scenario this PR enables) and calls
add_file. It takesself.mutex— which the watch thread is not contending — and reachesself.platform.add_root(dir). add_rootcallsself.watchers.push(dw). The Vec is at capacity, sopushallocates a new buffer,memcpys theBox<DirWatcher>pointers over, and frees the old buffer.- The watch thread's
for dw in &self.watchersslice iterator is still holding the old(ptr, len)pair. It dereferences the freed backing storage to readdw.dir_handle→ use-after-free. Even without a realloc, the concurrent length/pointer write is a data race and UB.
Impact
Memory unsafety on Windows: reading freed heap memory and passing whatever is there to
CloseHandle. The window is narrow — a hardReadDirectoryChangesW/ IOCP error concurrent with an out-of-root import triggering Vec growth — but per REVIEW.md (Native code memory safety, the most-blocked category): "a mutex only counts if EVERY accessor takes it" and "benign same-value races are still UB".Fix
Trivial: take the same lock the writers take. Either wrap the call site in
thread_main:Err(err) => { me.watchloop_handle.store(false); { let _guard = me.mutex.lock_guard(); me.platform.stop(); } if me.running.load() { ... } }
or snapshot the handles under the lock inside
stop()before closing them. Either restores the invariant the field's doc comment already claims. - The watch thread is inside
-
🟡
src/watcher/WindowsWatcher.rs:346-350— Now that there are N watch roots, any single root's I/O failure still propagatesErrthroughnext()→watch_loop→thread_mainand callsplatform.stop(), terminating watching for all roots including the cwd. Concretely: if a userrm -rf packages/db(opened withFILE_SHARE_DELETE, so it can go delete-pending), the next re-arm on that root fails and the cwd watcher silently stops too. Not blocking — pre-PR these dirs weren't watched at all so this is a strict improvement, andon_errordoes fire — but per-root isolation (drop the failing extra root, keep the rest alive) would be a good follow-up.Extended reasoning...
What the bug is
Before this PR the Windows watcher had exactly one root — the cwd — so an error from
ReadDirectoryChangesW/GetQueuedCompletionStatusmeant the project directory itself was gone, and treating that as fatal was reasonable. This PR generalizes to N roots (one per external directory reached via a workspace symlink /bun link/file:dep) but keeps the single-root error propagation: every error path innext()still returnsErr, which bubbles throughwatch_loop_cycle→watch_loop→thread_main, callsplatform.stop()(closing all dir handles), and exits the watcher thread.The specific code paths
There are three per-root error paths, all newly reachable for extra roots:
needs_rearmre-arm at the top ofnext()(WindowsWatcher.rs:346-350):If the extra root's directory was deleted/renamed since the last drain,if let Some(dw) = self.needs_rearm.take() { unsafe { dw.as_ptr().as_mut().unwrap_unchecked() }.prepare()?; }
ReadDirectoryChangesWfails (typicallyERROR_ACCESS_DENIEDon a delete-pending dir) and the?kills the whole watcher.- Buffer-overflow re-arm in the
nbytes == 0branch — sameprepare()?short-circuit. GetQueuedCompletionStatusreturningrc == 0with a non-timeout error for one root's completion (e.g. after its directory is removed) — returnsErrfor the whole watcher.
Why existing code doesn't prevent it
The pre-PR code had the identical
?/return Errpropagation, but only one root existed. The PR adds roots on directories users are far more likely to delete mid-session than the cwd (workspace packages, linked deps) without adding per-root isolation. The dir handle is opened withFILE_SHARE_DELETE, so deletion is permitted while the handle is open — the directory enters delete-pending, and the nextReadDirectoryChangesWon it fails.Step-by-step proof
- Run
bun --watch index.jsfromapps/myapp, which imports@test/db(junction →packages/db). PR opens root[0] =apps/myapp\, root[1] =packages/db\. - User runs
rm -rf packages/db(orgit checkoutto a branch without it, or renames it) to regenerate the package. The handle on root[1] was opened withFILE_SHARE_DELETE, so the delete succeeds and the directory enters delete-pending. - The delete produces a completion on root[1];
next()returns itsEventIteratorand setsneeds_rearm = Some(root[1]). watch_loop_cycledrains the iterator, then callsnext()again. Theneeds_rearmblock callsroot[1].prepare()→ReadDirectoryChangesWon a delete-pending directory → fails (ERROR_ACCESS_DENIEDor similar).prepare()?propagatesErrout ofnext()→watch_loop_cyclereturnsErr→watch_loopreturnsErr→thread_maincallsplatform.stop()(closes root[0]'s handle too) and(on_error)(ctx, err), then the watcher thread exits.- Edits to
apps/myapp/index.js— under root[0], which was still perfectly valid — no longer trigger a reload. For DevServer the user sees "hot-reloading is disabled until a restart"; for--watch/--hotthe file-watcher thread is simply gone.
Impact and why this is a nit
This is a real limitation but I'd flag it as a nit / follow-up, not blocking:
- Strict net improvement: pre-PR,
packages/dbwasn't watched at all — deleting it couldn't affect the watcher, but edits to it were never picked up either. The PR fixes the common case (#9547) and only introduces this edge on an operation that would break the running app's next reload anyway. - Not silent:
on_erroris invoked, so DevServer prints a diagnostic; it's "watcher stops, user restarts bun", not data loss or a crash. - Edge trigger: deleting an entire directory the running process currently imports from is plausible but not the everyday flow.
How to fix
Isolate errors per root: when
prepare()on an extra root (index > 0) fails, or GQCS returns a non-timeout error for its completion, log once, close that root'sdir_handle, mark the entry dead (e.g. setdir_handle = INVALID_HANDLE_VALUEand skip it instop()/covers()), andcontinue— while the remaining roots, especially root[0] (the cwd), keep watching. Only a failure on root[0] should remain fatal. Matches REVIEW.md § Error handling: "Every error/abort/timeout path actively completes the operation" — one root's expected, user-reachable failure shouldn't cascade to unrelated roots. -
🟡
test/cli/hot/watch.test.ts:107— Theawait using watcher = spawn(...)on line 80 already registers disposal (Subprocess's[Symbol.asyncDispose]kills and awaits exit), so this trailingwatcher.kill()is redundant — REVIEW.md's hermetic-tests section says "no manual close alongsideusing". Neighboringawait using runner = spawn(...)tests in hot.test.ts don't add a manual.kill(). Just delete this line.Extended reasoning...
What the issue is
REVIEW.md's "Tests reviewers reject → hermetic" section states: "Release every resource via
using/await usingor try/finally registered BEFORE the assertions …; no manual close alongsideusing". The new test declaresawait using watcher = spawn({...})at line 80, which registers automatic disposal viaSubprocess[Symbol.asyncDispose](kills the process and awaitsexited). Then at line 107 — the last statement before the function scope closes — it also callswatcher.kill()explicitly. That is precisely the "manual close alongsideusing" pattern the guideline prohibits.Step-by-step
- Line 80:
await using watcher = spawn({...})bindswatcherand pushes an async disposer onto the scope's dispose stack. - Lines 85–105: the test drives five reload generations and runs its assertions.
- Line 107:
watcher.kill()sends the kill signal. - Immediately after line 107 the function body ends, the
await usingdisposer runs, andSubprocess[Symbol.asyncDispose]callsthis.kill()+await this.exited— which would have killed the process anyway. Step 3 therefore does nothing that step 4 doesn't do one statement later.
Why nothing else prevents it
The pre-existing test in this same file (line 47) does call
process.kill(), but that test does not useawait using— it uses a plainconst process = spawn(...)— so the manual kill there is the only cleanup and is not the same pattern. It doesn't establish precedent for pairingawait usingwith a manual kill.Neighboring convention
Sibling tests in
test/cli/hot/hot.test.ts(lines 547, 601, 647, 726) andtest/cli/hot/watch-many-dirs.test.ts:48all useawait using runner = spawn(...)and none of them add a trailing.kill()— they let the disposer handle it. So the repo convention is consistently enforced in neighboring code.Impact
None at runtime.
kill()on a subprocess that's about to be disposed is idempotent; the test behaves identically with or without this line. This is purely a style/convention violation, hence nit severity — not blocking.Fix
Delete line 107 (
watcher.kill();). Theawait usingon line 80 already handles teardown on both the pass and fail paths. - Line 80:
…tiring a root mark_dead now reads every box field before publishing the dead flag, since a transpiler thread may reuse the slot once the store lands.
|
Rebased onto main and reworked per the review, force-pushed as one commit (now 1eb7048 after two follow-up nits):
|
alii
left a comment
There was a problem hiding this comment.
The earlier items are addressed; two things left, inline.
…dOwnership docs The test now only passes after the recreated package's edit reloads; EOF during the last phase fails the assertion. The two comments that still described the old cwd pin now describe the root-open failure.
|
Both addressed in 6653b89: the hot lifecycle test now requires the final phase (EOF during it fails), and the two stale cwd-pin comments in append_file_maybe_lock and the FdOwnership::Caller doc are updated. Re-verified on Windows: watch.test.ts 4/4. |
There was a problem hiding this comment.
I reviewed this revision and didn't find any new bugs. alii's two latest comments (phase-6 assertion in the --hot test, stale FdOwnership/append_file_maybe_lock comment text) look addressed in 6653b89. Given the scope — multi-root IOCP lifecycle, cross-thread unsafe around pending kernel I/O, dead-slot reuse — human sign-off is still the right call.
What was reviewed:
mark_deadnow reads/logs everything beforedead.store(true), closing the reuse-slot race flagged last round.stop()cancels + waits per live root under the mutex and invalidatesiocp;add_rootearly-returns onINVALID_HANDLE_VALUE.pick_watch_rootusesPKG.len()for the probe bounds;snapshot_watchlist_pathsre-snapshots after mid-batch dispatch so raw slices stay valid across evictions.
Extended reasoning...
Overview
This PR reworks the Windows --watch/--hot filesystem watcher from a single recursive ReadDirectoryChangesW rooted at the cwd to a set of per-root Box<DirWatcher>s sharing one IOCP, so files resolved outside the project root (workspace packages via junctions, bun link, file: deps) are actually watched. It touches WindowsWatcher.rs (substantial rewrite), Watcher.rs (cross-platform stop() ordering, new ensure_watch_root_covers / unwatchable_roots / platform_scratch fields), sys/windows/mod.rs (CancelIoEx/GetOverlappedResult externs), plus comment updates in DevServer.rs/path_watcher.rs, a dead filter removal in bake-harness.ts, and two new tests in watch.test.ts.
Security risks
None in the traditional sense — no untrusted-input parsing or auth surface. The real risk category is memory safety: pending overlapped kernel I/O against heap buffers that get freed, cross-thread access to Vec<Box<DirWatcher>> where the watch thread reaches boxes via raw lpOverlapped pointers while transpiler threads mutate the Vec under Watcher.mutex, and dead-slot reuse racing mark_dead. Prior review rounds surfaced and fixed several concrete UAFs here (unlocked stop() iteration, Ok-exit not calling stop(), CloseHandle not waiting for cancellation, missing SYNCHRONIZE in the access mask, post-publish field reads in mark_dead). This run's bug-hunting pass found nothing new.
Level of scrutiny
High. This is native Windows async-I/O lifecycle code with extensive unsafe, raw-pointer identity tricks (OVERLAPPED at offset 0 of a boxed struct), and a threading model where the mutex covers only some accessors by design. It has already gone through ~8 review rounds with multiple UAF/race findings; alii (human maintainer) has done two substantive review passes and the second one's feedback was just addressed in the head commit. This is exactly the class of change that should not be auto-approved.
Other factors
- alii's two most recent inline comments (2026-08-13T18:10) are not yet marked resolved, though the head commit 6653b89 appears to address both: the
--hottest now advances tophase = 6on[app] 3 4and assertstoBe(6), and theFdOwnership::Caller/append_file_maybe_lockcomments now describe the new "watch root could not be opened" semantics. - The two new tests are stated to fail on main on Windows and pass with the build; the
--hotlifecycle test now covers the dead-slot-reuse path that alii specifically called out. - The many unresolved
github-actions"comment-cop" inline notes are automated lint noise on doc-comment length, not substantive review feedback.
alii
left a comment
There was a problem hiding this comment.
Both remaining items are fixed in 6653b89 (the --hot test now fails on EOF during its last phase, and the two FdOwnership comments describe the new root-open failure); the interdiff contains nothing else. Merges cleanly onto current main. Windows behaviour is unverified from this side; looks ready to merge pending CI.
|
Two findings from #39832. That PR fixes the same warning for files inside the project when the cwd is spelled differently from the real path: an 8.3 short name such as
If this PR lands first, #39832 becomes those two changes plus its tests on top of it. |
…austed (#39183) ### Problem - The `Comment Cop` check is red on every claude-labeled PR whenever the repo's GraphQL quota is used up. The step dies before it scans anything: ``` GraphqlResponseError: Request failed due to following response errors: - API rate limit already exceeded for site ID installation. ##[error]Unhandled error: GraphqlResponseError: ... ``` with `x-ratelimit-resource: graphql`, `x-ratelimit-limit: 10000`, `x-ratelimit-remaining: 0` (run [31898901053](https://github.com/oven-sh/bun/actions/runs/31898901053) on #39139). All 33 comment-cop failures on Aug 15 are this error (197 runs succeeded, 171 were skipped); they hit unrelated PRs at the same time because the quota is shared by every workflow run in the repo, and they come back whenever PR volume is high. - Cause, `.github/workflows/comment-cop.yml:124` on main: the step reads the PR's existing review threads with `github.graphql()`, outside any `try`, and dedup and posting both sit behind that call. The REST call just before it (`pulls.listFiles`) had succeeded in each failing run, so the step had the diff; it only lacked the dedup data, which it was reading from the exhausted quota. - The same thread data also fed an auto-resolve of stale threads. That part does not work: under the Actions `GITHUB_TOKEN` every `resolveReviewThread` mutation fails with `Resource not accessible by integration`, after which the step still logs `Resolved N stale comment-cop thread(s).` Two successful runs from today: [31900717034](https://github.com/oven-sh/bun/actions/runs/31900717034) (20 attempted, 20 failed, "Resolved 20") and [31900354924](https://github.com/oven-sh/bun/actions/runs/31900354924) (4 attempted, 4 failed, "Resolved 4"). #36959 documents the same thing and is the PR that moves resolution to a token that can do it. So the GraphQL query was paying for one thing REST can provide and one thing that does not happen. ### Fix - Dedup reads the PR's review comments with `pulls.listReviewComments` (REST) and collects the `<!-- comment-cop:KEY -->` markers from them. Every comment the step posts starts with that marker, so the review comments carry the same keys the thread roots did; REST is the quota the step already needs for `listFiles` and `createReviewComment`, and it was available in every failing run. - The GraphQL query and the resolve loop are removed, so the step makes no GraphQL request at all; the failure in the Problem section cannot happen, rather than being caught. Nothing observable is lost: the mutations the loop issued all fail today, and the only other thing it did was log `Resolved N stale comment-cop thread(s).` after they had failed. Resolving stale threads stays with #36959, which will also need to move its thread lookup into its token step, since this PR removes the `GITHUB_TOKEN` lookup it currently reuses (noted there). - What the step posts is unchanged: the script on main and the REST dedup were dry-run (real reads, writes recorded) against 9 PRs carrying existing comment-cop threads (#35988, #36956, #36713, #35635, #33632, #35596, #39139, #30609, #36959) and chose the same comments to post on every one of them; the canned scenarios below show the same thing with GraphQL working and with it exhausted. - Test: `test/internal/source-lints/comment-cop.test.ts` extracts the script from the workflow and runs it the way `actions/github-script` does, against a fake `github` whose GraphQL requests all fail with the rate limit error above. It checks that groups not yet flagged are posted with the right line ranges, that a group already flagged (and a stale marker) are left alone, that a second run recognizes the comments the first run posted and posts nothing, and that no GraphQL request is made. Both tests fail against the workflow on main (the script throws the error above) and pass with this change. `source-lints.yml` now also triggers on changes to `comment-cop.yml`, so the test runs whenever the script is edited; it is excluded from the Buildkite shards like the rest of that directory. - Also ran: `bun bd test test/internal/source-lints/comment-cop.test.ts`, `bun test test/internal/source-lints/` (whole directory green), prettier on the three files. The comment-cop run on this PR itself still executes the script from main (`pull_request_target`), so the `Source lints` job is the one that exercises the change here. - Does not overlap with #37948 (which groups are flagged) or #38127 (where the file list comes from); both touch other parts of the script. #36959 rewrites the block this PR deletes and will need a rebase either way. ### Background - Comment Cop (`.github/workflows/comment-cop.yml`): on each push to a claude-labeled PR it reads the PR diff, finds multi-line comments added under `src/`, and posts one review comment per comment block. Each bot comment starts with `<!-- comment-cop:KEY -->`, KEY being the file path plus a hash of the block's text; a block whose KEY is already on the PR is not posted again. The check is advisory (not required for merge). - GitHub API quotas: REST and GraphQL requests count against separate hourly quotas (`x-ratelimit-resource` is `core` for REST and `graphql` for GraphQL). For the `GITHUB_TOKEN` Actions hands out, each quota is per repository, so every workflow run in oven-sh/bun draws on the same two pools, and GraphQL-heavy automation (the `gh pr` / `gh issue` / `gh search` commands used by other workflows go through GraphQL) empties the GraphQL pool for everything else when PR volume is high. - Review threads vs review comments: a review thread is GraphQL's grouping of a line comment with its replies, and is the only place a thread's id (what `resolveReviewThread` takes) and its resolved flag exist. `GET /repos/{owner}/{repo}/pulls/{n}/comments` returns every review comment on the PR, including each thread's root comment, so the markers are reachable from REST; only resolving needs GraphQL, and under `GITHUB_TOKEN` GitHub refuses that mutation regardless of the `pull-requests: write` permission. <details> <summary>Script on main vs this branch against a fake github (the fake's resolve mutation fails the way GITHUB_TOKEN's does)</summary> ``` main | quota ok, stale threads present | exit 0 | posts ["src/foo.ts:5-6"] | resolve attempts ["T_STALE_OPEN"] | graphql ["query","query","mutation"] | warnings 1 main | graphql quota exhausted, stale threads present | step fails (unhandled rate limit error) | posts [] | resolve attempts [] | graphql ["query"] | warnings 0 main | graphql quota exhausted, nothing stale | step fails (unhandled rate limit error) | posts [] | resolve attempts [] | graphql ["query"] | warnings 0 main | graphql quota exhausted, PR has no review comments yet | step fails (unhandled rate limit error) | posts [] | resolve attempts [] | graphql ["query"] | warnings 0 fixed | quota ok, stale threads present | exit 0 | posts ["src/foo.ts:5-6"] | resolve attempts [] | graphql [] | warnings 0 fixed | graphql quota exhausted, stale threads present | exit 0 | posts ["src/foo.ts:5-6"] | resolve attempts [] | graphql [] | warnings 0 fixed | graphql quota exhausted, nothing stale | exit 0 | posts ["src/foo.ts:5-6"] | resolve attempts [] | graphql [] | warnings 0 fixed | graphql quota exhausted, PR has no review comments yet | exit 0 | posts ["src/foo.ts:2-3","src/foo.ts:5-6"] | resolve attempts [] | graphql [] | warnings 0 ``` </details> <details> <summary>Dry-run against live PRs: comments the script on main would post vs the REST dedup (real reads through a user token, writes recorded)</summary> ``` PR #35988: same posts (0 vs 0) 245 threads on the PR are stale; main attempts to resolve them, this branch does not PR #36956: same posts (0 vs 0) PR #36713: same posts (1832 vs 1832) the stale cached file list that #38127 fixes; identical on both PR #35635: same posts (0 vs 0) PR #33632: same posts (0 vs 0) PR #35596: same posts (0 vs 0) PR #39139: same posts (1 vs 1) the comment the failing run above did not get to post PR #30609: same posts (0 vs 0) PR #36959: same posts (0 vs 0) ``` </details> <details> <summary>Headers from the failing run</summary> ``` errors: [ { type: 'RATE_LIMIT', code: 'graphql_rate_limit', message: 'API rate limit already exceeded for site ID installation.' } ] variables: { owner: 'oven-sh', repo: 'bun', pr: 39139, after: null } 'x-ratelimit-limit': '10000' 'x-ratelimit-remaining': '0' 'x-ratelimit-resource': 'graphql' 'x-ratelimit-used': '10000' ``` </details>
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-08-13. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
Problem
ReadDirectoryChangesWrooted at the cwd, so a file that resolves outside it (a workspace package reached through anode_modulesjunction,bun link, afile:dependency) is appended to the watch list but its events never fire, and every reload printsFile ... is not in the project directory and will not be watchedonce per file. Fixes Bun doesnt pick changes in monorepos packages #9547.Fix
Box<DirWatcher>(its ownReadDirectoryChangesW) sharing one IOCP. A completion'slpOverlappedis the address of theDirWatcherthat fired, so the watch thread identifies the source without touching the roots Vec and without the mutex.node_modulescomponent if there is one, else the nearest enclosing directory with apackage.json, else the file's directory. Adist/rebuild no longer deletes its own root, andbun build --watchwith an out-of-cwd hoistednode_modulesopens one root total for it.add_rootreuses dead slots so kill/re-add cycles don't grow the Vec. With every root dead the thread parks on the IOCP until the next out-of-root import arms a new root, like inotify at watch_count zero.stop()runs on both watch-thread exits under the mutex; it marks roots dead, cancels pending I/O and waits for the cancellation (CancelIoEx+GetOverlappedResult(bWait), which needsSYNCHRONIZEin theNtCreateFilemask) before the buffers are freed, then invalidates the IOCP so a lateradd_rootfrom a still-running--hotprocess returns early instead of using a closed handle.needs_rearm), not inWatcher::init, so a shutdown beforestart()has no pending kernel I/O against a freed buffer.Cow::Ownedon Windows, so owned copies would malloc per path per completion) and re-snapshots after a mid-batch dispatch, whose evictionsswap_remove-reorder the live list.add_rootfailures map the NTSTATUS / Win32 code to an errno, so the once-per-root warning names the cause (for exampleENOENT) instead of an internal enum variant.bun bd test test/cli/hot/watch.test.ts(4/4),hot.test.ts(12/12),watch-many-dirs.test.tson Windows and Linux debug builds; the two new tests fail on main on Windows (warning printed, reload stalls) and pass with this build.Background
ReadDirectoryChangesWwatches one directory tree per call and reports paths relative to it; completions are delivered through an I/O completion port (IOCP) the handle is associated with. TheOVERLAPPEDpassed when arming comes back aslpOverlapped, which is why it sits at offset 0 ofDirWatcherand doubles as the root's identity.--watchreloads on Windows replace the process, so each generation re-registers roots from scratch; only--hotand the dev server exercise the in-process lifecycle (re-arm rotation, root death and reuse). The new--hottest deletes and recreates a linked package mid-session to cover that path.OVERLAPPEDasynchronously, which is whystop()must wait before theBox<Watcher>is dropped.no test proof · iteration 4 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/cli/hot/watch.test.ts