worldmonitor icon indicating copy to clipboard operation
worldmonitor copied to clipboard

fix(sidecar): release fetch-semaphore slots when upstreams stall mid-body (#5441)

Open rajanpanth opened this issue 4 months ago • 2 comments

Closes #5441

Problem

The globalThis.fetch wrapper in src-tauri/sidecar/local-api-server.mjs throttles all outbound requests through the 6-slot global semaphore, releasing the slot in a finally after the wrapped http(s).request Promise settles. That Promise only settled on res 'end' or req 'error'. An upstream that accepts the connection, sends headers, then stalls or truncates mid-body — a routine failure for rate-limited feeds — fires neither event: the Promise never settles, the finally never runs, and one slot leaks permanently. After ~6 such stalls, every data fetch parks forever on acquireUpstreamSlot() while in-memory RPCs (which never call fetch) keep responding — exactly the ~hourly wedge described in the issue.

Fix

Following the direction suggested in the issue (credit to @mosabsayyed for the excellent diagnosis): settle the Promise idempotently on every terminal event —

  • res 'error' and res 'aborted' → reject (stalled/truncated body)
  • req 'close' → reject as a catch-all for destroyed sockets (a no-op after a clean res 'end' resolve, guarded by the settled flag)
  • the abort-signal listener now rejects directly (with { once: true }) instead of relying on req.destroy() to surface an error

With every path settling, finally { releaseUpstreamSlot() } always runs and the semaphore can no longer be exhausted by stuck upstreams.

Testing

tests/sidecar-fetch-semaphore.test.mjs + a small __testing__ seam (mirroring the existing __testing__ pattern in list-feed-digest.ts):

  1. stands up a local server whose /stall endpoint sends headers + a partial body, then destroys the socket;
  2. fires MAX_CONCURRENT_UPSTREAM + 1 concurrent fetches at it — each must reject, not hang (a watchdog race fails the test explicitly if any are left pending);
  3. then fetches a healthy endpoint and asserts it goes straight through — proving all slots were released.

Red/green verified: the test fails against the pre-fix wrapper with stalled upstream responses left fetches pending (semaphore leak) and passes with the fix.

Note: as the issue observes, the same end/error-only pattern exists in a couple of other non-semaphored http(s).request wrappers in this file; left out of scope here since only the globalThis.fetch wrapper is load-bearing for the wedge.

rajanpanth avatar Jul 22 '26 16:07 rajanpanth

@rajanpanth is attempting to deploy a commit to the World Monitor Team on Vercel.

A member of the Team first needs to authorize it.

vercel[bot] avatar Jul 22 '26 16:07 vercel[bot]

Greptile Summary

This PR fixes a semaphore-slot leak in the globalThis.fetch wrapper inside the Node.js sidecar. Previously, the wrapping Promise settled only on res 'end' or req 'error', so an upstream that sent headers then stalled mid-body caused the Promise to hang permanently — exhausting all 6 concurrency slots after ~6 such failures and wedging every subsequent data fetch.

  • The fix introduces a settled flag with an idempotent settle() helper and adds res.on('error'), res.on('aborted'), and req.on('close') (catch-all) as additional terminal-event listeners, ensuring finally { releaseUpstreamSlot() } always runs.
  • The abort-signal handler is also tightened: it now rejects directly with { once: true } instead of relying on the req.destroy() → req.error chain, and a new regression test (tests/sidecar-fetch-semaphore.test.mjs) verifies both slot release and post-fix healthy-fetch throughput with an 8 s watchdog.

Confidence Score: 4/5

Safe to merge. The settle/settled pattern is the correct idiomatic fix for this class of Promise leak, and the test validates both the rejection path and slot release end-to-end.

The core logic change is small and well-contained: a settled flag and four additional event listeners. Ordering guarantees in Node.js's HTTP stack ensure res.on('end') always fires before req.on('close') on a successful response, so the no-op path is reliable. The only observation is the deprecated res.on('aborted') handler, which is harmless but dead code on modern Node.js runtimes.

No files require special attention; the change is isolated to the fetch wrapper and its new test.

Important Files Changed

Filename Overview
src-tauri/sidecar/local-api-server.mjs Adds idempotent settle() pattern with a settled flag, plugging the semaphore-slot leak on stalled mid-body responses. Introduces req.on('close') as a catch-all terminal event; for successful responses res.on('end') fires first (settled = true), so the subsequent close is a no-op. Also includes a small testing export seam.
tests/sidecar-fetch-semaphore.test.mjs New regression test: stands up a local stall server, fires MAX_CONCURRENT_UPSTREAM+1 concurrent fetches at the /stall endpoint, and asserts all reject within an 8 s watchdog. Then verifies a healthy fetch goes through, confirming all slots were released.

Sequence Diagram

sequenceDiagram
    participant Caller
    participant Semaphore
    participant Promise
    participant req as http.ClientRequest
    participant res as IncomingMessage

    Caller->>Semaphore: acquireUpstreamSlot()
    Semaphore-->>Caller: slot granted
    Caller->>Promise: new Promise(resolve, reject)
    Caller->>req: mod.request(...)
    req->>res: response callback

    alt Healthy response
        res->>res: data events (chunks)
        res->>Promise: end → settle(resolve, buildSafeResponse)
        Note over Promise: settled = true
        req->>Promise: close → settle(reject, ...) [NO-OP]
    else Stalled / truncated mid-body (bug fixed)
        res->>res: data events (partial)
        Note over res: end never fires
        req->>Promise: close → settle(reject, Error) [FIRES]
        Note over Promise: settled = true
    else req error / abort signal
        req->>Promise: error → settle(reject, error)
        Note over Promise: settled = true
        req->>Promise: close → settle(reject, ...) [NO-OP]
    end

    Promise->>Semaphore: "finally { releaseUpstreamSlot() }"
    Semaphore-->>Caller: next queued fetch unblocked

Reviews (1): Last reviewed commit: "fix(sidecar): release fetch-semaphore sl..." | Re-trigger Greptile

greptile-apps avatar Jul 22 '26 16:07 greptile-apps

Closing as a duplicate of #5489, which fixes the exact same root cause with an equivalent patch (idempotent settle() on res 'error'/res 'aborted'/req 'close') — both were independently verified to fix the reported wedge and merge cleanly against current main. #5489's regression test additionally exercises the fix through the real request-handling path (createLocalApiServer + handler dispatch) rather than calling fetch() directly, matching the issue's literal repro more closely, so we're taking that one forward.

Thanks for the fast, correct diagnosis and fix, @rajanpanth — this was a well-scoped PR and you got there first.

koala73 avatar Jul 25 '26 10:07 koala73