Skip to content

fix: close abandoned PDF.js development asset streams - #23054

Merged
nwparker merged 11 commits into
mainfrom
nwparker/perf-09-25-pdfjs-stream-lifetime
Sep 26, 2026
Merged

nwparker merged 11 commits into
mainfrom
nwparker/perf-09-25-pdfjs-stream-lifetime

Conversation

@nwparker

@nwparker nwparker commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​214 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​212
Prod 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​24 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​18

Historical release-test CI prerequisite

The CI merge base advanced the package version beyond a historical release fixture: the test expected 1.4.203 but read today’s 1.4.214 package. The build-identity helper now accepts an optional package version alongside its existing release inputs, and that test supplies its historical 1.4.201 version. Normal callers still read package.json. Both original version/build-number assertions remain; all 16 tests pass, and two exact before/after comparisons confirm unchanged default output. Targeted lint, including the no-module-mocking rule, passes. Application and native terminal code are unchanged; fresh CI remains required.

ELI5

When a developer cancels a PDF asset download, the server now closes the file it was reading for that request.

What Changed

Repeated canceled PDF.js asset requests no longer leave file handles open in Vite. The asset stream stops when its response closes or fails, read errors close the response, and stream completion removes its response listeners. A response that already closed opens no file. GET/HEAD headers, successful bytes, path validation, middleware pass-through and build copies stay the same.

Why

pipe() alone does not destroy the source when a downstream response disappears under backpressure. This uses the same stream-lifetime pattern as the local build feed; keeping that small wiring in the plugin avoids importing desktop updater code into the build configuration.

Linked Issue

Fixes #23051

Visual Proof

N/A — development-server file handle cleanup; no rendered interaction or packaged PDF behavior changes.

Performance proof

Actual middleware with real temporary files and25 abandoned, backpressured responses: 25 open file streams → 0, with every descriptor closed and owned response listener removed. The permanent regression fails against the exact baseline. An already-closed response opens zero streams after the fix. No UI or production-server latency claim is made.

CI diagnostic prerequisite

The branch also adds phase markers and a timeout result to the existing WebRTC egress test, after a Linux CI run exited before producing its result file. The probe keeps the same 20-second deadline and all egress assertions; no browser production policy changes. The added diagnostics identify where a future failure occurs. Final-head CI must pass.

Testing

  • 10 permanent tests pass, including GET bytes, HEAD, pass-through, repeated aborts, source/downstream failures and already-closed responses.
  • Independent real HTTP validation: exact4MiB GET, mid-body client disconnect, native read error, abort before file open and preservation of foreign listeners all pass.
  • Node typecheck, focused lint/format pass. macOS Node exercised; native Linux/Windows and rendered app validation were not run. No app was launched.
  • Reproduce: ORCA_BACKGROUND_LAUNCH=1 pnpm test config/scripts/pdfjs-viewer-assets-stream.test.ts.

Review

Merge risk: low. Node stream destruction is idempotent and works before the descriptor opens; real-stream tests cover that edge. Source errors disconnect the failed response instead of escaping unhandled. Only this middleware's cleanup listeners are removed.

Negative user-facing trade-offs: none identified. Small per-request lifecycle listeners last only as long as the source stream. This change affects development asset requests, not packaged production rendering.

Agent skill upstream boundary

  • Not applicable; no skill source changed.

Notes

The shared diff-note catalog entries are now in main and have dropped out of this diff. The remaining Japanese/Korean values make the AI the note’s recipient.

No timer, polling, subprocess, new cache, wire change, platform-specific path or SSH/folder-workspace assumption. No terminal/session reliability invariant changes.

Checklist

  • Focused fix with ELI5, mechanism, measured proof and risk.
  • Independent review and baseline regression completed.
  • Visual proof N/A; platform gaps recorded.
  • Full build/platform matrix; focused checks above passed and CI covers the branch.

@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: a9d0b9e7-70d9-4205-b733-7c37dc7de4bd

📥 Commits

Reviewing files that changed from the base of the PR and between a4d8714 and 120c4ca.

📒 Files selected for processing (2)
  • config/scripts/hourly-build-version.mjs
  • config/scripts/hourly-build-version.test.mjs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.


📝 Walkthrough

Walkthrough

The PDF.js development middleware skips opening a file stream when the response is already destroyed. It ties stream cleanup to response close and error events, and destroys the response if the source stream errors. Tests cover abandoned requests, successful GET and HEAD responses, failure cleanup, and pass-through requests. The WebRTC egress probe logs its current phase and includes phase and protectedGuest details in timeout and failure results. Japanese and Korean translations for the AI note label are updated. getHourlyBuildIdentity accepts an optional package version, and its test passes that value directly.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 120c4

The PDF middleware now cleans up abandoned streams, while the other changes improve diagnostics, translations, and version input. No material user-facing regression is evident; merge is reasonable once current CI succeeds.

Architecture Summary

Architecture risk: 🔵 Low · up to 120c4

The change affects 2 systems.

Changed systems: config, src

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — config (service) was modified; 4 changed files map to changed impact.
  • observed — src (service) was modified; 3 changed files map to changed impact.

Before / after behavior

  • observed — Modified behavior in config/build-plugins/pdfjs-viewer-assets.ts: The middleware now returns when the response is destroyed, before setting response headers or opening a stream.
  • observed — Modified behavior in config/build-plugins/pdfjs-viewer-assets.ts: The middleware replaces direct piping with stream lifecycle handling: response close or error destroys the stream, stream close removes the response listeners, and stream error destroys the response.
  • observed — Modified behavior in config/scripts/pdfjs-viewer-assets-stream.test.ts: Adds a node:fs mock that records read streams opened by the tests.
  • observed — Modified behavior in config/scripts/pdfjs-viewer-assets-stream.test.ts: Creates temporary asset fixtures, registers the plugin middleware, and throws if the server hook is missing.
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PDF.js middleware and stream tests match the historical [#23051] context. The pull request also changes the unrelated WebRTC egress diagnostic, Japanese and Korean locale catalogs, and hourly-buil… Remove the WebRTC, locale, and hourly-build changes from this pull request, or provide concrete evidence that each change is required for the PDF.js cleanup.
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Issue [#23051] is closed and provides historical context only. No active directly linked issue imposes coding or test requirements on this pull request.
Title check ✅ Passed The title clearly and concisely describes the primary change: closing abandoned PDF.js development asset streams.
Description check ✅ Passed The description includes the required change summary, rationale, linked issue, visual-proof explanation, testing details, review notes, scope considerations, and checklist. It also records platform va…
Full details: Out of Scope Changes check

Explanation

The PDF.js middleware and stream tests match the historical [#23051] context. The pull request also changes the unrelated WebRTC egress diagnostic, Japanese and Korean locale catalogs, and hourly-build version API and test. The available evidence describes these changes as CI or catalog prerequisites, but does not connect them to PDF.js asset stream cleanup or an active linked issue.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
config/scripts/pdfjs-viewer-assets-stream.test.ts (1)

78-95: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Preserve foreign response listeners in the cleanup tests.

The tests assert zero close and error listeners, but the fixture does not register listeners owned by other middleware. A regression that removes all listeners would still pass. Register persistent sentinel listeners and assert that only the asset stream's listeners are removed on success, source failure, response failure, and abandoned responses.

Suggested fix
 function request(method = 'GET', url = '/wasm/fixture.wasm') {
   const response = Object.assign(new PassThrough({ highWaterMark: 16 }), {
     setHeader: vi.fn(),
     statusCode: 0
   })
@@
   return { response, next, source: observed.streams.at(-1) }
 }
 
+function addForeignListeners(response: PassThrough) {
+  const close = vi.fn()
+  const error = vi.fn()
+  response.on('close', close)
+  response.on('error', error)
+  return { close, error }
+}
+
 it('releases file handles after repeated abandoned responses with backpressure', async () => {
   const responses: PassThrough[] = []
+  const foreignListeners = new Map<PassThrough, ReturnType<typeof addForeignListeners>>()
   for (let index = 0; index < 25; index += 1) {
     const { response, source } = request()
     responses.push(response)
+    foreignListeners.set(response, addForeignListeners(response))
     if (!source) {
       throw new Error('Missing source')
     }
@@
   }
   await expect.poll(() => observed.streams.filter((stream) => !stream.closed).length).toBe(0)
   expect(observed.streams.every((stream) => stream.fd === null)).toBe(true)
-  expect(responses.map((response) => response.listenerCount('close'))).toEqual(Array(25).fill(0))
-  expect(responses.map((response) => response.listenerCount('error'))).toEqual(Array(25).fill(0))
+  for (const [response, { close, error }] of foreignListeners) {
+    expect(response.listeners('close')).toEqual([close])
+    expect(response.listeners('error')).toEqual([error])
+  }
 })
 
 it('preserves successful GET bytes and removes response cleanup listeners', async () => {
   const { response, source, next } = request('GET', '/cmaps/fixture.bcmap')
+  const foreign = addForeignListeners(response)
   const chunks: Buffer[] = []
@@
-  expect(response.listenerCount('close')).toBe(0)
-  expect(response.listenerCount('error')).toBe(0)
+  expect(response.listeners('close')).toEqual([foreign.close])
+  expect(response.listeners('error')).toEqual([foreign.error])
@@
 it('closes the response on source failure without leaving listeners', async () => {
   const { response, source } = request()
+  const foreign = addForeignListeners(response)
@@
-  expect(response.listenerCount('close')).toBe(0)
-  expect(response.listenerCount('error')).toBe(0)
+  expect(response.listeners('close')).toEqual([foreign.close])
+  expect(response.listeners('error')).toEqual([foreign.error])
 })
 
 it('closes a source when the response fails', async () => {
   const { response, source } = request()
+  const foreign = addForeignListeners(response)
@@
-  expect(response.listenerCount('close')).toBe(0)
-  expect(response.listenerCount('error')).toBe(0)
+  expect(response.listeners('close')).toEqual([foreign.close])
+  expect(response.listeners('error')).toEqual([foreign.error])
 })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 59617fb4-298d-45e1-a0eb-cf7ca1dbe61d

📥 Commits

Reviewing files that changed from the base of the PR and between 02a5594 and 7963cfc.

📒 Files selected for processing (2)
  • config/build-plugins/pdfjs-viewer-assets.ts
  • config/scripts/pdfjs-viewer-assets-stream.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Bind PDF.js asset read stream to response lifetime — in config/build-plugins/pdfjs-viewer-assets.ts, the GET branch now returns early when response.destroyed, destroys the createReadStream source on response close/error, removes exactly those two listeners when the stream closes, and destroys the response on source error. Headers, bytes, HEAD, path validation, pass-through, and build-time copying are untouched.
  • Regression tests — config/scripts/pdfjs-viewer-assets-stream.test.ts adds 10 tests over a mocked createReadStream: 25 abandoned backpressured responses (fd null, zero open streams, zero leftover listeners), exact GET bytes/headers, HEAD without opening a stream, source failure, response failure, four pass-through cases, and an already-closed response.

I verified the fix locally: the suite passes 10/10 at HEAD, and reverting only the middleware to the old createReadStream(filePath).pipe(response) makes 4 of the tests fail (25 retained streams, source-failure timeout, response-failure, already-closed-opens-one-stream). The tests genuinely pin the leak rather than passing vacuously.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker

Copy link
Copy Markdown
Contributor Author

Fixed in f7c6828. The closed-response guard now runs before header writes; the regression uses a header setter that throws if touched after close. Cleanup tests now seed foreign close/error listeners and verify they survive success, source failure, response failure, and abandoned responses. The pre-fix closed-response case fails; all 10 cases pass with the fix. The concurrent catalog correction is preserved.

@nwparker

Copy link
Copy Markdown
Contributor Author

Reviewed the CodeRabbit docstring-coverage warning. This repository explicitly requires concise comments limited to non-obvious reasoning (AGENTS.md), so I am declining the generic 80% docstring suggestion. The existing ownership/behavior comments and focused regression tests cover the decisions in this change. No code change is warranted for that style-only warning.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Guarded a closed response before writing headers — in config/build-plugins/pdfjs-viewer-assets.ts, if (response.destroyed) return now runs before statusCode/setHeader (it previously sat just before createReadStream), so a response that a prior middleware already closed can no longer reach the header writes.
  • Hardened the cleanup-listener tests — the fixture in config/scripts/pdfjs-viewer-assets-stream.test.ts now seeds foreign close/error listeners and asserts only the middleware's listeners are removed across success, source failure, response failure, and 25 abandoned backpressured responses; the closed-response regression uses a setHeader that throws ERR_HTTP_HEADERS_SENT and asserts it is never called.
  • Carried a concurrent i18n catalog correction — the six locale files restore the diff-note draft catalog entries and add the missing trailing comma after commentTooLarge. Unrelated to the stream fix, but intentional per the author, and all six files parse.

The prior CodeRabbit thread on this line is addressed and resolved, and the earlier Pullfrog approval had no open threads. I re-ran the focused suite: pnpm test config/scripts/pdfjs-viewer-assets-stream.test.ts → 10/10 pass at f7c6828.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker

Copy link
Copy Markdown
Contributor Author

Reviewed the latest scope and docstring warnings. The WebRTC change adds diagnostics only, retaining the existing deadline and assertions; it is disclosed under “CI diagnostic prerequisite.” The two locale lines reconcile shared main-branch catalog maintenance and are disclosed under Notes. Both prerequisites were reviewed separately from the unchanged PDF cleanup. No issue will be created: the user explicitly requested PR-only work. Generic 80% docstring coverage is declined under AGENTS.md’s concise, non-obvious-comments-only policy. No new actionable code finding remains; successful current-head CI is still required.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Merged main and kept the ja/ko diff-note wording — 72dc809b2c merges main; the en/es/fr/zh catalog restore now lives on main and drops out of this diff, leaving only the intentional ja/ko "note for the AI" recipient wording (f6c449191e).
  • Instrumented the WebRTC egress probe with phase diagnostics — 8696ea25af adds enterPhase(...) markers across the generated probe script and records phase plus protectedGuest in the result file on timeout and in the catch handler. The 20-second deadline, the egress assertions, and the pass/fail semantics are unchanged.

The prior Pullfrog approvals had no open inline threads, and the CodeRabbit thread on the closed-response guard was already resolved by the author. Focused suite (pnpm test config/scripts/pdfjs-viewer-assets-stream.test.ts) was green at the previously reviewed head; the delta since then is test-only diagnostics plus a translation-only locale tweak.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Made the hourly-version test hermetic — getHourlyBuildIdentity now accepts an optional packageVersion that overrides the package.json read (config/scripts/hourly-build-version.mjs), and the "unpublished buggy release" test pins packageVersion: '1.4.201' so its historical fixture no longer drifts as main's package version advances. Production behavior is unchanged: the CLI entrypoint passes no override, so it still reads package.json (packageVersion ?? JSON.parse(readFileSync(...)).version).
  • Rest of the PR unchanged since its prior approvals — the PDF.js asset-stream lifetime fix and its test, the WebRTC egress phase diagnostics, and the ja/ko diff-note recipient wording are untouched by this delta.

Ran the focused suite: pnpm test config/scripts/hourly-build-version.test.mjs → 16/16 pass at 120c4ca.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit 28d617d into main Sep 26, 2026
37 checks passed
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.

Canceled PDF.js dev asset requests retain open file streams

2 participants