puppeteer: [Bug]: Browser.close does not shutdown the process immediately

Error string

MaxListenersExceededWarning: Possible EventEmitter memory leak detected.

Bug behavior

  • Flaky
  • PDF

Background

The code example above is a simplified version of our Lambda function. Basically. we don’t do anything tricky, only load the page, giving it reasonable time to load while monitoring the ready state of the page and its source code, and get the data from it.

The crawler works great except sometimes the browser freezes. In most cases, we catch this when closing the browser. We scrape hundreds of thousands of pages and weren’t able to make it work reliably reusing the same browser instance, even with periodical restarts. Therefore, we close and open the browser on each crawl.

At some point, it freezes on the browser.close() so we had to implement a timeout function and try to kill the process, which doesn’t work well. Even after sending the SIGKILL signal, the process stays. Probably in a zombie state or just stucks somewhere, I don’t know and we have no instruments to investigate. Must be an upstream bug in the chrome itself.

Expectation

There should be a way to get rid of a faulty process. Disregarding the nature of the failure, we should be able to kill it and start a new one.

Reality

The fact we’re sending SIGKILL and it brings us nowhere tells me the child process is spawned incorrectly and wasn’t properly detached from its parent. When something goes wrong, such processes stay as long as their parent, which can take forever as we have no control over Lambda’s lifecycle (almost). The only solution I can think of is to call exit in the main function, which will forcefully restart the Lambda. Then we handle a faulty response and restart the job.

We started seeing this problem after upgrading to 112+. We are on 122 now but the picture is the same.

Screenshot 2024-03-31 at 17 22 51

Puppeteer configuration file (if used)

No response

Puppeteer version

22.4.1

Node version

20.11.1

Package manager

npm

Package manager version

10.2.4

Operating system

Linux

About this issue

Most upvoted comments

So I tried dumpio: true but did not find anything suspicious there. Some GPU-related complaints when the graphicsMode is set to false. When set to true, those complaints are gone but that doesn’t change the main picture.

A typical log would look like this:

2024-04-02T11:41:29.560Z	2f9f5ec4-58fd-4dce-a2ec-7de890e1981a	INFO	Starting: https://canpromos.ca/size/3xl
2024-04-02T11:41:29.560Z	2f9f5ec4-58fd-4dce-a2ec-7de890e1981a	INFO	Launching browser
START RequestId: 2f9f5ec4-58fd-4dce-a2ec-7de890e1981a Version: $LATEST
2024-04-02T11:41:29.561Z puppeteer:browsers:launcher Launching /tmp/chromium --allow-pre-commit-input --disable-background-networking --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-component-update --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-field-trial-config --disable-hang-monitor --disable-infobars --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-search-engine-choice-screen --disable-sync --enable-automation --export-tagged-pdf --generate-pdf-document-outline --force-color-profile=srgb --metrics-recording-only --no-first-run --password-store=basic --use-mock-keychain --disable-features=Translate,AcceptCHFrame,MediaRouter,OptimizationHints,ProcessPerSiteUpToMainFrameThreshold,Translate,BackForwardCache,AcceptCHFrame,MediaRouter,OptimizationHints,AudioServiceOutOfProcess,IsolateOrigins,site-per-process --enable-features=NetworkServiceInProcess2,NetworkServiceInProcess2,SharedArrayBuffer --headless=new --hide-scrollbars --mute-audio about:blank --allow-pre-commit-input --disable-background-networking --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-component-update --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --enable-automation --enable-blink-features=IdleDetection --export-tagged-pdf --force-color-profile=srgb --metrics-recording-only --no-first-run --password-store=basic --use-mock-keychain --disable-domain-reliability --disable-print-preview --disable-speech-api --disk-cache-size=33554432 --mute-audio --no-default-browser-check --no-pings --single-process --font-render-hinting=none --hide-scrollbars --ignore-gpu-blocklist --in-process-gpu --window-size=1920,1080 --disable-webgl --allow-running-insecure-content --disable-setuid-sandbox --disable-site-isolation-trials --disable-web-security --no-sandbox --no-zygote --headless='chrome-headless-shell' --disk-cache-size=268435456 --window-size=1366,4608 --ignore-certificate-errors --disable-remote-fonts --user-data-dir=/tmp/chrome-user-data --remote-debugging-pipe {
detached: true,
env: 
{}
,
stdio: [ 'ignore', 'pipe', 'pipe', 'pipe', 'pipe' ]
}
2024-04-02T11:41:29.563Z puppeteer:browsers:launcher Launched 176
[0402/114129.574263:ERROR:egl_util.cc(44)] Failed to load GLES library: /tmp/libGLESv2.so: /tmp/libGLESv2.so: cannot open shared object file: No such file or directory
[0402/114129.600608:ERROR:check.cc(319)] Check failed: false. NOTREACHED log messages are omitted in official builds. Sorry!
[0402/114129.600646:ERROR:gpu_channel_manager.cc(955)] Failed to create GLES3 context, fallback to GLES2.
[0402/114129.600652:ERROR:check.cc(319)] Check failed: false. NOTREACHED log messages are omitted in official builds. Sorry!
[0402/114129.600657:ERROR:gpu_channel_manager.cc(966)] ContextResult::kFatalFailure: Failed to create shared context for virtualization.
[0402/114129.600661:ERROR:shared_image_stub.cc(728)] SharedImageStub: unable to create context
[0402/114129.600668:ERROR:gpu_channel.cc(767)] GpuChannel: Failed to create SharedImageStub
[0402/114129.600686:ERROR:check.cc(319)] Check failed: false. NOTREACHED log messages are omitted in official builds. Sorry!
[0402/114129.600692:ERROR:gpu_channel_manager.cc(955)] Failed to create GLES3 context, fallback to GLES2.
[0402/114129.600695:ERROR:check.cc(319)] Check failed: false. NOTREACHED log messages are omitted in official builds. Sorry!
[0402/114129.600700:ERROR:gpu_channel_manager.cc(966)] ContextResult::kFatalFailure: Failed to create shared context for virtualization.
[0402/114129.600704:ERROR:shared_image_stub.cc(728)] SharedImageStub: unable to create context
[0402/114129.600708:ERROR:gpu_channel.cc(767)] GpuChannel: Failed to create SharedImageStub
2024-04-02T11:41:29.621Z	2f9f5ec4-58fd-4dce-a2ec-7de890e1981a	INFO	Opening page
2024-04-02T11:41:29.646Z	2f9f5ec4-58fd-4dce-a2ec-7de890e1981a	INFO	Loading: https://canpromos.ca/size/3xl
[0402/114138.505549:INFO:CONSOLE(403)] "Turbo mode file downloaded!", source: https://canpromos.ca/wp-content/plugins/woocommerce-products-filter/ext/turbo_mode/js/turbo_mode.js?ver=1.3.4.5 (403)
[0402/114138.560148:INFO:CONSOLE(0)] "Third-party cookie will be blocked. Learn more in the Issues tab.", source: https://canpromos.ca/size/3xl/ (0)
[0402/114139.783212:INFO:CONSOLE(0)] "Third-party cookie will be blocked. Learn more in the Issues tab.", source: https://canpromos.ca/size/3xl/ (0)
[0402/114139.803421:INFO:CONSOLE(0)] "Third-party cookie will be blocked. Learn more in the Issues tab.", source: https://canpromos.ca/size/3xl/ (0)
[0402/114139.919333:INFO:CONSOLE(1)] "[OptinMonster] The origin header was not set in the request.", source: https://a.omappapi.com/app/js/api.min.js (1)
[0402/114141.388245:INFO:CONSOLE(0)] "Third-party cookie will be blocked. Learn more in the Issues tab.", source: https://canpromos.ca/size/3xl/ (0)
[0402/114141.724074:INFO:CONSOLE(0)] "Third-party cookie will be blocked. Learn more in the Issues tab.", source: https://canpromos.ca/size/3xl/ (0)
[0402/114142.900913:INFO:CONSOLE(24)] "[Meta Pixel] - An invalid email address was specified for 'em'. This data will not be sent with any events for this Pixel.", source: https://connect.facebook.net/en_US/fbevents.js (24)

When calling browser.close() this line puppeteer:browsers:launcher Browser process 176 onExit never appears.

In my opinion, the problem is that the page keeps loading. So I set the timeout of 25 seconds which aborts the promise but the page keeps loading, then I close it and something doesn’t go according to the plan.

So instead of closing the page, I did this:

// Close the pages, unbind browser events, and close it.
async function shutdown(browser) {
  console.log("Shutting down");

  try {
    const pages = await browser.pages();
    let page;

    console.log("Pages open:", pages.length);

    for (let i = 0; i < pages.length; i++) {
      page = pages[i];

      if (page.crawler_cdp_client)
        page.crawler_cdp_client.off('Network.requestIntercepted');

      page.off("request");
      page.off("response");
      page.off("framenavigated");

      await page.goto("about:blank");
    }
  } catch(e) {
    console.error("Unexpected error when closing page:", e);
  }

  if (browser) {
    try {
      browser.off('disconnected');

      // Give the browser 5 seconds to shut down
      await timeout(
        browser.close().catch((e) => { console.error("Error closing browser:", e) }), 5000
      ).catch(async () => monitorBrowserStop(browser));
    } catch(e) {
      console.error("Unexpected error when closing browser:", e);
    }
  }
}

And that worked!

A reproducible script would probably be to load a heavy page that takes too long, preferably in a limited environment with a slow vCPU, set a navigation timeout, and try closing the page and the browser.

Thanks, I see that Browser.close sends a success response but actually does not close the browser.