Skip to content

fix: close function pages when user code fails - #5554

Merged
Xrazik1 merged 3 commits into
mainfrom
fix/close-function-page-on-error
Sep 1, 2026
Merged

Xrazik1 merged 3 commits into
mainfrom
fix/close-function-page-on-error

Conversation

@artiom

@artiom artiom commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

What changed

Function runs now close their page before disconnecting when user code throws or rejects. Cleanup failures are logged without replacing the original user error, and the runner module remains importable in Node for focused tests.

Why

A failed function run could leave its page alive until the surrounding browser was eventually released. Closing the page while its CDP transport is still connected releases those resources immediately.

Testing

  • npm run build:tests
  • npx mocha --no-package build/shared/utils/function/client.spec.js — 4 passing
  • Existing Chromium, Chrome, and Edge function route regressions plus context validation — 38 passing, with 7 pre-existing schema-fixture cases pending

Devin Review

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling during browser-based function execution.
    • Ensured pages and browser connections are cleaned up when execution fails.
    • Added safeguards for synchronous and asynchronous errors, including failures while closing pages.
    • Prevented browser-only setup from running in unsupported environments.

@coderabbitai

coderabbitai Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Team

Run ID: 2bf3e447-5546-425d-bb6d-881da04c5a5f

📥 Commits

Reviewing files that changed from the base of the PR and between cb94894 and f35cdb1.

📒 Files selected for processing (2)
  • src/shared/utils/function/client.spec.ts
  • src/shared/utils/function/client.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


Walkthrough

FunctionRunner now centralizes handler execution, response serialization, page cleanup, browser disconnection, and error logging. Cleanup has a timeout, and original execution errors remain the thrown result. Tests cover success and failure paths.

Changes

FunctionRunner cleanup

Layer / File(s) Summary
Centralized execution and cleanup
src/shared/utils/function/client.ts
runWithBrowser configures downloads, executes handlers, serializes responses, closes pages with a timeout, disconnects browsers on failures, logs cleanup errors, and preserves execution errors. start delegates to it. Browserless runner registration checks for window.
Cleanup behavior tests
src/shared/utils/function/client.spec.ts
Tests cover page closure, setup failures, cleanup timeouts, synchronous and asynchronous errors, cleanup error logging, browser disconnection, and unbound rejection logging.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Merge Risk: ⚪ Minimal · up to f35cd

The change closes function pages before disconnecting when user code fails, while preserving the original error and logging cleanup failures; no actionable merge-blocking risk remains after normal checks and review.

Suggested reviewers: ashwinsingh2007

Poem

A rabbit watched the page close tight
Errors stayed with names just right
The browser disconnected clean
Timeout guards kept paths serene
Tests hopped through each case
Cleanup finished in good grace

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: closing function pages when user code fails.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 2…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 2 files.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/close-function-page-on-error

Warning

Your free Security trial is over. An organization admin can upgrade to Advanced for continuous pull request security review or dismiss this notice.


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

@devin-ai-integration devin-ai-integration 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.

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Devin Review

artiom commented Aug 28, 2026

Copy link
Copy Markdown
Contributor Author

Current-head status:

  • Devin Review reported no issues; CodeRabbit completed with no unresolved threads.
  • Checks: 14 passed; the optional Dependabot automerge job was skipped; none are pending or failing.
  • Mergeability: mergeable; human approval is still required.

No further code changes were needed.

@artiom
artiom requested a review from ashwinsingh2007 August 28, 2026 20:26
@ashwinsingh2007

Copy link
Copy Markdown
Contributor

Code review — PLT-1524 (OSS half)

Reviewed against the ticket's items 11-13. All three are implemented as specified, and the ordering constraint that matters (close the page before disconnect(), since disconnect() tears down the very CDP transport close() needs) is correct and covered by the first test's calls ordering assertion.

Notes:

1. MINOR — page.close() on the error path is unbounded

src/shared/utils/function/client.ts:30

} catch (error) {
  console.error(`Error running code: ${error}`);
  await this.page?.close().catch(this.log);
  this.browser?.disconnect();
  throw error;
}

If the user's code failed because the page crashed, the target went away, or the CDP transport hung, page.close() is now awaited with no bound of its own — it settles only when puppeteer's protocolTimeout fires (options.protocolTimeout, or puppeteer's default when unset). Before this change the error surfaced immediately.

So the /function error response can be delayed by up to that timeout on exactly the failure modes most likely to hit it. The status and body are unchanged, which is what DoD 23 checks, but the latency is not.

Suggest racing it: await Promise.race([this.page?.close().catch(this.log), sleep(2_000)]) or similar, so a dead transport cannot hold the request open.

2. Good

  • log correctly became a this-free arrow property, so .catch(this.log) at :80 now actually logs instead of silently discarding the rejection (it previously returned a bound console.log and ignored its argument). The unbound-callback case is tested directly.
  • Moving the invocation into runCode with try { return await code(...) } also catches synchronous throws from user code, which the old .catch() did not — so the page is closed and the browser disconnected on that path too. Covered by the "throws synchronously" test.
  • "preserves the user error when closing the page fails" is the right guarantee to pin: cleanup failure must not replace the user's error.
  • The typeof window !== 'undefined' guard is inert in the esbuild bundle (scripts/build-function.js), so static/function/client.js still registers on window.

No blocking issues here. The enterprise half of PLT-1524 (browserless/enterprise#2331) is where the blocking findings are.

@ashwinsingh2007

Copy link
Copy Markdown
Contributor

Fix itself is right — awaiting page.close() before disconnect() is exactly the ordering that was broken, and the log change is a real improvement (the old catch(this.log) handed puppeteer a function that returned a logger and logged nothing, so close failures were silently swallowed).

Two spots the same reasoning applies but didn't get covered:

1. The success path still doesn't await the close (client.ts:82):

const response = await this.runCode(code, context);
console.debug(`... closing page.`);
this.page.close().catch(this.log);   // <- not awaited

Once start() resolves, page.evaluate resolves in handler.ts, and function.http.ts:74 closes the outer runner page right after — which kills the in-page WebSocket that Target.closeTarget was just queued on. Same disconnect-races-close shape you just fixed, only on the path that runs on every successful call instead of the failing one. Usually the close wins, but it's the same one-line await.

2. Setup between newPage() and runCode() isn't covered. If Page.setDownloadBehavior throws (client.ts:69-75), or newPage() itself succeeds and something after it fails, this.page leaks and the browser stays connected — the outer handler's catch closes the outer page, but nothing closes the inner one. Wrapping from newPage() onward rather than just the code() call would close that off. Worth doing since it's the identical leak, just one branch up.

Minor, not blocking: the Node v24.19.0 → v24.20.0 / npm 11.19.0 → 11.19.1 bumps across all the Dockerfiles and workflows are unrelated to the fix — if this needs reverting, the runtime bump goes with it.

@artiom
artiom force-pushed the fix/close-function-page-on-error branch from cb94894 to f35cdb1 Compare September 1, 2026 11:01

artiom commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Addressed both human review follow-ups on the rebased head.

  • Page cleanup is bounded to two seconds and awaited on both successful and failed function runs.
  • The runner now owns cleanup from newPage() onward, so download-setup failures close the inner page and disconnect the browser.
  • Synchronous and asynchronous user errors remain the exact errors returned even if page close or browser disconnect also fails.
  • Added focused coverage for successful close ordering, setup failure cleanup, bounded cleanup, sync/async error preservation, and disconnect failure.
  • The Node/npm changes are already present on main and are absent from this branch's diff, so there is no unrelated runtime bump to revert or split from this PR.

Rebase and verification:

  • Rebased onto origin/main 07358b1a636714972e2d2346f0251a226c80ac9b.
  • Current head: f35cdb163bfee271f7a792d5b669544e3df04647.
  • npm run build:tests passed.
  • Focused runner tests: 7 passing.
  • Chromium/Chrome/Edge function and context tests: 34 passing, 7 expected pending.
  • Production-source ESLint, Prettier, and diff checks passed.

The findings were top-level PR comments, not review threads, so GitHub provides nothing to mark resolved.

@Xrazik1
Xrazik1 merged commit a36bb85 into main Sep 1, 2026
15 checks passed
@Xrazik1
Xrazik1 deleted the fix/close-function-page-on-error branch September 1, 2026 14:20
artiom pushed a commit that referenced this pull request Sep 2, 2026
🤖 I have created a release *beep* *boop*
---


##
[2.56.1](v2.56.0...v2.56.1)
(2026-09-01)


### Bug Fixes

* **AUTO-288:** preserve raw profile paths during token shimming
([#5547](#5547))
([2222d9f](2222d9f))
* close function pages when user code fails
([#5554](#5554))
([a36bb85](a36bb85))


### Build System & Runtime

* bump Node to 24.20.0 and npm to 11.19.1
([#5553](#5553))
([f1e5077](f1e5077))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

---------

Co-authored-by: browserless-actions-bot[bot] <186328842+browserless-actions-bot[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
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.

4 participants