Repository: GoogleChrome/lighthouse
Pull request #6497 (2018-11-07 03:48:15)

core: throw fatally on page hang
**Summary**
I've spent way too much time waffling back and forth on how to handle this, so I thought I'd just put it up for discussion. This PR throws a fatal error if, after our maxWaitForLoad is reached, the page doesn't seem to respond.

Right now this basically gets us earlier exit than trying to do all the gathering and not much else. I agree with @brendankenny that it's a bit dangerous to try to kill JavaScript and continue. If we do anything else I think it might be alternative 1, but still feels risky.

Alternatives:
- Wait for maxWaitForLoad, kill JavaScript, wait and see if page is still hung, then either fatally throw or try to continue
- Wait for maxWaitForLoad, kill JavaScript, and try to continue right away
- Continuously check if page is hung, kill JavaScript as soon as we think it's hung, and do A or B


brendankenny: re: alternatives, I personally vote for what's here and then ramping up in the future if we think we can get away with them

Patch:
diff --git a/changelog.md b/changelog.md
index 97acb31c8..a08db519f 100644
--- a/changelog.md
+++ b/changelog.md
@@ -1,3 +1,38 @@
+ <a name="4.0.0-alpha.1"></a>
+# 4.0.0-alpha.1 (2018-11-15)
+[Full Changelog](https://github.com/googlechrome/lighthouse/compare/v4.0.0-alpha.0...v4.0.0-alpha.1)
+
+## Core
+
+* skip h2 audit in LR ([#6564](https://github.com/googlechrome/lighthouse/pull/6564))
+* config: faster category validation ([#6445](https://github.com/googlechrome/lighthouse/pull/6445))
+* driver: wait for Page.frameNavigated for about:blank ([#6446](https://github.com/googlechrome/lighthouse/pull/6446))
+* lib: add chrome-extension to URL allowedProtocols and add test ([#6447](https://github.com/googlechrome/lighthouse/pull/6447))
+* pwa: audit and report group renames ([#6494](https://github.com/googlechrome/lighthouse/pull/6494))
+* seo: properly handle anchors in SVG ([#6483](https://github.com/googlechrome/lighthouse/pull/6483))
+* increase protocol timeout to 30s ([#6505](https://github.com/googlechrome/lighthouse/pull/6505), [#6531](https://github.com/googlechrome/lighthouse/pull/6531))
+
+## Report
+
+* pwa: give badges to groups with all passing audits ([#6504](https://github.com/googlechrome/lighthouse/pull/6504))
+* pwa: add pwa-category-renderer ([#6486](https://github.com/googlechrome/lighthouse/pull/6486))
+* compat: add details-element polyfill for Edge ([#6465](https://github.com/googlechrome/lighthouse/pull/6465))
+* compat: fix support for edge ([#6459](https://github.com/googlechrome/lighthouse/pull/6459))
+* compat: ignore Edge's Invalid Argument error ([#6456](https://github.com/googlechrome/lighthouse/pull/6456))
+* compat: fix summary rendering in FF ([#6448](https://github.com/googlechrome/lighthouse/pull/6448))
+* handle underscored not_applicable scoreDisplayMode ([#6549](https://github.com/googlechrome/lighthouse/pull/6549))
+* css: make performance category more compact ([#6437](https://github.com/googlechrome/lighthouse/pull/6437))
+* rename clump classes; give classes to all audit groups ([#6482](https://github.com/googlechrome/lighthouse/pull/6482))
+* refactor rendering of top-level failed/passing/etc clumps ([#6460](https://github.com/googlechrome/lighthouse/pull/6460))
+
+## Misc
+
+* build: fix viewer deploy ([#6449](https://github.com/googlechrome/lighthouse/pull/6449))
+* timing: move timing-trace to async events ([#6440](https://github.com/googlechrome/lighthouse/pull/6440))
+* update puppeteer to version 1.10.0 ([#6493](https://github.com/googlechrome/lighthouse/pull/6493))
+* readme: use official appveyor badge ([#6443](https://github.com/googlechrome/lighthouse/pull/6443))
+* i18n: convert accessibility audits ([#6229](https://github.com/googlechrome/lighthouse/pull/6229))
+
  <a name="4.0.0-alpha.0"></a>
 # 4.0.0-alpha.0 (2018-10-31)
 [Full Changelog](https://github.com/googlechrome/lighthouse/compare/v3.2.0...v4.0.0-alpha.0)
diff --git a/clients/extension/manifest.json b/clients/extension/manifest.json
index 21bc64040..8093ed4b8 100644
--- a/clients/extension/manifest.json
+++ b/clients/extension/manifest.json
@@ -1,6 +1,6 @@
 {
   "name": "__MSG_appName__",
-  "version": "3.3.0.4000",
+  "version": "3.3.0.4001",
   "minimum_chrome_version": "66",
   "manifest_version": 2,
   "description": "__MSG_appDescription__",
diff --git a/lighthouse-cli/run.js b/lighthouse-cli/run.js
index 6a55fe5f5..52661c3dd 100644
--- a/lighthouse-cli/run.js
+++ b/lighthouse-cli/run.js
@@ -22,6 +22,7 @@ const opn = require('opn');
 
 const _RUNTIME_ERROR_CODE = 1;
 const _PROTOCOL_TIMEOUT_EXIT_CODE = 67;
+const _PAGE_HUNG_EXIT_CODE = 68;
 
 /**
  * exported for testing
@@ -70,6 +71,12 @@ function showProtocolTimeoutError() {
   process.exit(_PROTOCOL_TIMEOUT_EXIT_CODE);
 }
 
+/** @param {LH.LighthouseError} err */
+function showPageHungError(err) {
+  console.error('Page hung:', err.friendlyMessage);
+  process.exit(_PAGE_HUNG_EXIT_CODE);
+}
+
 /**
  * @param {LH.LighthouseError} err
  */
@@ -89,6 +96,8 @@ function handleError(err) {
     showConnectionError();
   } else if (err.code === 'CRI_TIMEOUT') {
     showProtocolTimeoutError();
+  } else if (err.code === 'PAGE_HUNG') {
+    showPageHungError(err);
   } else {
     showRuntimeError(err);
   }
diff --git a/lighthouse-core/config/default-config.js b/lighthouse-core/config/default-config.js
index 6fa2b3076..39ad7100f 100644
--- a/lighthouse-core/config/default-config.js
+++ b/lighthouse-core/config/default-config.js
@@ -372,7 +372,7 @@ const defaultConfig = {
         {id: 'is-on-https', weight: 2, group: 'pwa-installable'},
         {id: 'service-worker', weight: 1, group: 'pwa-installable'},
         {id: 'webapp-install-banner', weight: 2, group: 'pwa-installable'},
-        // Engaging
+        // PWA Optimized
         {id: 'redirects-http', weight: 2, group: 'pwa-optimized'},
         {id: 'splash-screen', weight: 1, group: 'pwa-optimized'},
         {id: 'themed-omnibox', weight: 1, group: 'pwa-optimized'},
diff --git a/lighthouse-core/config/lr-desktop-config.js b/lighthouse-core/config/lr-desktop-config.js
index 76bdafb63..36ba73592 100644
--- a/lighthouse-core/config/lr-desktop-config.js
+++ b/lighthouse-core/config/lr-desktop-config.js
@@ -18,6 +18,8 @@ const config = {
       throughputKbps: 10 * 1024,
       cpuSlowdownMultiplier: 1,
     },
+    // Skip the h2 audit so it doesn't lie to us. See #6539
+    skipAudits: ['uses-http2'],
   },
 };
 
diff --git a/lighthouse-core/config/lr-mobile-config.js b/lighthouse-core/config/lr-mobile-config.js
index 778acb403..264663542 100644
--- a/lighthouse-core/config/lr-mobile-config.js
+++ b/lighthouse-core/config/lr-mobile-config.js
@@ -10,6 +10,8 @@ const config = {
   extends: 'lighthouse:default',
   settings: {
     maxWaitForLoad: 35 * 1000,
+    // Skip the h2 audit so it doesn't lie to us. See #6539
+    skipAudits: ['uses-http2'],
   },
 };
 
diff --git a/lighthouse-core/gather/driver.js b/lighthouse-core/gather/driver.js
index 52a0b2ef3..7444607e6 100644
--- a/lighthouse-core/gather/driver.js
+++ b/lighthouse-core/gather/driver.js
@@ -30,7 +30,7 @@ const DEFAULT_NETWORK_QUIET_THRESHOLD = 5000;
 // Controls how long to wait between longtasks before determining the CPU is idle, off by default
 const DEFAULT_CPU_QUIET_THRESHOLD = 0;
 // Controls how long to wait for a response after sending a DevTools protocol command.
-const DEFAULT_PROTOCOL_TIMEOUT = 5000;
+const DEFAULT_PROTOCOL_TIMEOUT = 30000;
 
 /**
  * @typedef {LH.Protocol.StrictEventEmitter<LH.CrdpEvents>} CrdpEventEmitter
@@ -369,6 +369,7 @@ class Driver {
       includeCommandLineAPI: true,
       awaitPromise: true,
       returnByValue: true,
+      timeout: 60000,
       contextId,
     };
 
@@ -687,6 +688,25 @@ class Driver {
     };
   }
 
+  /**
+   * Returns whether the page appears to be hung.
+   * @return {Promise<boolean>}
+   */
+  async isPageHung() {
+    try {
+      this.setNextProtocolTimeout(1000);
+      await this.sendCommand('Runtime.evaluate', {
+        expression: '"ping"',
+        returnByValue: true,
+        timeout: 1000,
+      });
+
+      return false;
+    } catch (err) {
+      return true;
+    }
+  }
+
   /**
    * Returns a promise that resolves when:
    * - All of the following conditions have been met:
@@ -736,11 +756,18 @@ class Driver {
     const maxTimeoutPromise = new Promise((resolve, reject) => {
       maxTimeoutHandle = setTimeout(resolve, maxWaitForLoadedMs);
     }).then(_ => {
-      return function() {
-        log.warn('Driver', 'Timed out waiting for page load. Moving on...');
+      return async () => {
+        log.warn('Driver', 'Timed out waiting for page load. Checking if page is hung...');
         waitForLoadEvent.cancel();
         waitForNetworkIdle.cancel();
         waitForCPUIdle && waitForCPUIdle.cancel();
+
+        if (await this.isPageHung()) {
+          log.warn('Driver', 'Page appears to be hung, killing JavaScript...');
+          await this.sendCommand('Emulation.setScriptExecutionDisabled', {value: true});
+          await this.sendCommand('Runtime.terminateExecution');
+          throw new LHError(LHError.errors.PAGE_HUNG);
+        }
       };
     });
 
@@ -749,7 +776,7 @@ class Driver {
       loadPromise,
       maxTimeoutPromise,
     ]);
-    cleanupFn();
+    await cleanupFn();
   }
 
   /**
diff --git a/lighthouse-core/lib/lh-error.js b/lighthouse-core/lib/lh-error.js
index 2a09ba497..9b4049cf2 100644
--- a/lighthouse-core/lib/lh-error.js
+++ b/lighthouse-core/lib/lh-error.js
@@ -148,6 +148,12 @@ const ERRORS = {
     message: strings.pageLoadFailedInsecure,
     lhrRuntimeError: true,
   },
+  /* Used when the page stopped responding and did not finish loading. */
+  PAGE_HUNG: {
+    code: 'PAGE_HUNG',
+    message: strings.pageLoadFailedHung,
+    lhrRuntimeError: true,
+  },
 
   // Protocol internal failures
   TRACING_ALREADY_STARTED: {
diff --git a/lighthouse-core/lib/strings.js b/lighthouse-core/lib/strings.js
index 377a4117e..ead92c977 100644
--- a/lighthouse-core/lib/strings.js
+++ b/lighthouse-core/lib/strings.js
@@ -11,6 +11,7 @@ module.exports = {
   badTraceRecording: `Something went wrong with recording the trace over your page load. Please run Lighthouse again.`,
   pageLoadTookTooLong: `Your page took too long to load. Please follow the opportunities in the report to reduce your page load time, and then try re-running Lighthouse.`,
   pageLoadFailed: `Lighthouse was unable to reliably load the page you requested. Make sure you are testing the correct URL and that the server is properly responding to all requests.`,
+  pageLoadFailedHung: `Lighthouse was unable to reliably load the URL you requested because the page stopped responding.`,
   pageLoadFailedInsecure: `The URL you have provided does not have valid security credentials.`,
   internalChromeError: `An internal Chrome error occurred. Please restart Chrome and try re-running Lighthouse.`,
   requestContentTimeout: 'Fetching resource content has exceeded the allotted time',
diff --git a/lighthouse-core/report/html/renderer/pwa-category-renderer.js b/lighthouse-core/report/html/renderer/pwa-category-renderer.js
index 72d3a6fd5..57a5710b2 100644
--- a/lighthouse-core/report/html/renderer/pwa-category-renderer.js
+++ b/lighthouse-core/report/html/renderer/pwa-category-renderer.js
@@ -16,7 +16,7 @@
  */
 'use strict';
 
-/* globals self, CategoryRenderer */
+/* globals self, Util, CategoryRenderer */
 
 class PwaCategoryRenderer extends CategoryRenderer {
   /**
@@ -34,7 +34,7 @@ class PwaCategoryRenderer extends CategoryRenderer {
     // Regular audits aren't split up into pass/fail/not-applicable clumps, they're
     // all put in a top-level clump that isn't expandable/collapsable.
     const regularAuditRefs = auditRefs.filter(ref => ref.result.scoreDisplayMode !== 'manual');
-    const auditsElem = this.renderUnexpandableClump(regularAuditRefs, groupDefinitions);
+    const auditsElem = this._renderAudits(regularAuditRefs, groupDefinitions);
     categoryElem.appendChild(auditsElem);
 
     // Manual audits are still in a manual clump.
@@ -45,6 +45,45 @@ class PwaCategoryRenderer extends CategoryRenderer {
 
     return categoryElem;
   }
+
+  /**
+   * Returns the group IDs whose audits are all considered passing.
+   * @param {Array<LH.ReportResult.AuditRef>} auditRefs
+   * @return {Set<string>}
+   */
+  _getPassingGroupIds(auditRefs) {
+    const groupIds = auditRefs.map(ref => ref.group).filter(/** @return {g is string} */ g => !!g);
+    const uniqueGroupIds = new Set(groupIds);
+
+    // Remove any that have a failing audit.
+    for (const auditRef of auditRefs) {
+      if (!Util.showAsPassed(auditRef.result) && auditRef.group) {
+        uniqueGroupIds.delete(auditRef.group);
+      }
+    }
+
+    return uniqueGroupIds;
+  }
+
+  /**
+   * Render non-manual audits in groups, giving a badge to any group that has
+   * all passing audits.
+   * @param {Array<LH.ReportResult.AuditRef>} auditRefs
+   * @param {Object<string, LH.Result.ReportGroup>} groupDefinitions
+   * @return {Element}
+   */
+  _renderAudits(auditRefs, groupDefinitions) {
+    const auditsElem = this.renderUnexpandableClump(auditRefs, groupDefinitions);
+
+    // Add a 'badged' class to group if all audits in that group pass.
+    const passsingGroupIds = this._getPassingGroupIds(auditRefs);
+    for (const groupId of passsingGroupIds) {
+      const groupElem = this.dom.find(`.lh-audit-group--${groupId}`, auditsElem);
+      groupElem.classList.add('lh-badged');
+    }
+
+    return auditsElem;
+  }
 }
 
 if (typeof module !== 'undefined' && module.exports) {
diff --git a/lighthouse-core/report/html/renderer/util.js b/lighthouse-core/report/html/renderer/util.js
index 875a89f66..cd2cc4535 100644
--- a/lighthouse-core/report/html/renderer/util.js
+++ b/lighthouse-core/report/html/renderer/util.js
@@ -62,6 +62,15 @@ class Util {
     if (typeof clone.categories !== 'object') throw new Error('No categories provided.');
     clone.reportCategories = Object.values(clone.categories);
 
+    // The proto process turns 'not-applicable' into 'not_applicable'. Correct this to support both.
+    // TODO: remove when underscore/hyphen proto issue is resolved. See #6371, #6201.
+    for (const audit of Object.values(clone.audits)) {
+      // @ts-ignore tsc rightly flags that this value shouldn't occur.
+      if (audit.scoreDisplayMode === 'not_applicable') {
+        audit.scoreDisplayMode = 'not-applicable';
+      }
+    }
+
     // For convenience, smoosh all AuditResults into their auditDfn (which has just weight & group)
     for (const category of clone.reportCategories) {
       category.auditRefs.forEach(auditMeta => {
diff --git a/lighthouse-core/report/html/report-styles.css b/lighthouse-core/report/html/report-styles.css
index eb3eddc61..c9723c168 100644
--- a/lighthouse-core/report/html/report-styles.css
+++ b/lighthouse-core/report/html/report-styles.css
@@ -97,6 +97,10 @@
   --pwa-fast-reliable-gray-url: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="nonzero"><circle fill="#DAE0E3" cx="12" cy="12" r="12"/><path d="M12.3 4l6.3 2.8V11c0 3.88-2.69 7.52-6.3 8.4C8.69 18.52 6 14.89 6 11V6.8L12.3 4zm-.56 12.88l3.3-5.79.04-.08c.05-.1.01-.29-.26-.29h-1.96l.56-3.92h-.56L9.6 12.52c0 .03.07-.12-.03.07-.11.2-.12.37.2.37h1.97l-.56 3.92h.56z" fill="#FFF"/></g></svg>');
   --pwa-installable-gray-url: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="nonzero"><circle fill="#DAE0E3" cx="12" cy="12" r="12"/><path d="M12 5a7 7 0 1 0 0 14 7 7 0 0 0 0-14zm3.5 7.7h-2.8v2.8h-1.4v-2.8H8.5v-1.4h2.8V8.5h1.4v2.8h2.8v1.4z" fill="#FFF"/></g></svg>');
   --pwa-optimized-gray-url: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><rect fill="#DAE0E3" width="24" height="24" rx="12"/><path fill="#FFF" d="M12 15.07l3.6 2.18-.95-4.1 3.18-2.76-4.2-.36L12 6.17l-1.64 3.86-4.2.36 3.2 2.76-.96 4.1z"/><path d="M5 5h14v14H5z"/></g></svg>');
+
+  --pwa-fast-reliable-color-url: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><g fill-rule="nonzero" fill="none"><circle fill="#CCE3F6" cx="12" cy="12" r="12"/><path d="M12 4.3l6.3 2.8v4.2c0 3.88-2.69 7.52-6.3 8.4-3.61-.88-6.3-4.51-6.3-8.4V7.1L12 4.3zm-.56 12.88l3.3-5.79.04-.08c.05-.1.01-.29-.26-.29h-1.96l.56-3.92h-.56L9.3 12.82c0 .03.07-.12-.03.07-.11.2-.12.37.2.37h1.97l-.56 3.92h.56z" fill="#304FFE"/></g></svg>');
+  --pwa-installable-color-url: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><g fill-rule="nonzero" fill="none"><circle fill="#D4ECD5" cx="12" cy="12" r="12"/><path d="M12 5a7 7 0 1 0 0 14 7 7 0 0 0 0-14zm3.5 7.7h-2.8v2.8h-1.4v-2.8H8.5v-1.4h2.8V8.5h1.4v2.8h2.8v1.4z" fill="#009688"/></g></svg>');
+  --pwa-optimized-color-url: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><rect fill="#FCE4EC" width="24" height="24" rx="12"/><path d="M5 5h14v14H5z"/><path fill="#EC3F7A" d="M12 15.07l3.6 2.18-.95-4.1 3.18-2.76-4.2-.36L12 6.17l-1.64 3.86-4.2.36 3.2 2.76-.96 4.1z"/></g></svg>');
 }
 
 .lh-vars.lh-devtools {
@@ -636,6 +640,15 @@ details, summary {
   background-image: var(--pwa-optimized-gray-url);
   background-size: var(--lh-group-icon-background-size);
 }
+.lh-audit-group--pwa-fast-reliable.lh-badged .lh-audit-group__header::before {
+  background-image: var(--pwa-fast-reliable-color-url);
+}
+.lh-audit-group--pwa-installable.lh-badged .lh-audit-group__header::before {
+  background-image: var(--pwa-installable-color-url);
+}
+.lh-audit-group--pwa-optimized.lh-badged .lh-audit-group__header::before {
+  background-image: var(--pwa-optimized-color-url);
+}
 
 /* Removing too much whitespace */
 .lh-audit-group--metrics {
diff --git a/package.json b/package.json
index 7558182be..25ff3214f 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
 {
   "name": "lighthouse",
-  "version": "4.0.0-alpha.0",
+  "version": "4.0.0-alpha.1",
   "description": "Lighthouse",
   "main": "./lighthouse-core/index.js",
   "bin": {
diff --git a/proto/lighthouse-result.proto b/proto/lighthouse-result.proto
index befb32303..a34ce7abb 100644
--- a/proto/lighthouse-result.proto
+++ b/proto/lighthouse-result.proto
@@ -47,6 +47,8 @@ enum LighthouseError {
   INSECURE_DOCUMENT_REQUEST = 16;
   // Used when protocol command times out.
   PROTOCOL_TIMEOUT = 17;
+  // Used when the page is not responding after maxWaitForLoad.
+  PAGE_HUNG = 18;
 }
 
 // The overarching Lighthouse Response object (LHR)
diff --git a/proto/sample_v2_round_trip.json b/proto/sample_v2_round_trip.json
index 07a2b4974..551bb7fb9 100644
--- a/proto/sample_v2_round_trip.json
+++ b/proto/sample_v2_round_trip.json
@@ -3289,7 +3289,7 @@
             "warningHeader": "Warnings: "
         }
     }, 
-    "lighthouseVersion": "4.0.0-alpha.0", 
+    "lighthouseVersion": "4.0.0-alpha.1", 
     "requestedUrl": "http://localhost:10200/dobetterweb/dbw_tester.html", 
     "runWarnings": [], 
     "timing": {


Test patch:
diff --git a/lighthouse-cli/test/fixtures/infinite-loop.html b/lighthouse-cli/test/fixtures/infinite-loop.html
new file mode 100644
index 000000000..2b77d7f1c
--- /dev/null
+++ b/lighthouse-cli/test/fixtures/infinite-loop.html
@@ -0,0 +1,22 @@
+<!doctype html>
+<!--
+ * Copyright 2018 Google Inc. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+-->
+<html>
+<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
+<body>
+  This is the function that never ends
+  Yes, it just goes on and on my friends.
+  Some people started computing it, not knowing what it was.
+  And they'll continue computing it forever just because,
+  This is the function that never ends.
+
+  <script>
+    while (true) {
+      for (let i = 0; i < 1000000; i++) ;
+    }
+  </script>
+</body>
+</html>
diff --git a/lighthouse-cli/test/smokehouse/error-config.js b/lighthouse-cli/test/smokehouse/error-config.js
new file mode 100644
index 000000000..771bdf604
--- /dev/null
+++ b/lighthouse-cli/test/smokehouse/error-config.js
@@ -0,0 +1,19 @@
+/**
+ * @license Copyright 2018 Google Inc. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+ */
+'use strict';
+
+/**
+ * Config file for sites with various errors, just fail out quickly.
+ */
+module.exports = {
+  extends: 'lighthouse:default',
+  settings: {
+    maxWaitForLoad: 5000,
+    onlyAudits: [
+      'first-contentful-paint',
+    ],
+  },
+};
diff --git a/lighthouse-cli/test/smokehouse/error-expectations.js b/lighthouse-cli/test/smokehouse/error-expectations.js
new file mode 100644
index 000000000..40d057806
--- /dev/null
+++ b/lighthouse-cli/test/smokehouse/error-expectations.js
@@ -0,0 +1,18 @@
+/**
+ * @license Copyright 2018 Google Inc. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+ */
+'use strict';
+
+/**
+ * Expected Lighthouse audit values for sites with various errors.
+ */
+module.exports = [
+  {
+    requestedUrl: 'http://localhost:10200/infinite-loop.html',
+    finalUrl: 'http://localhost:10200/infinite-loop.html',
+    errorCode: 'PAGE_HUNG',
+    audits: {},
+  },
+];
diff --git a/lighthouse-cli/test/smokehouse/run-smoke.js b/lighthouse-cli/test/smokehouse/run-smoke.js
index 93e71efae..12f2cb86d 100644
--- a/lighthouse-cli/test/smokehouse/run-smoke.js
+++ b/lighthouse-cli/test/smokehouse/run-smoke.js
@@ -29,6 +29,11 @@ const SMOKETESTS = [{
   config: smokehouseDir + 'a11y/a11y-config.js',
   expectations: 'a11y/expectations.js',
   batch: 'parallel-first',
+}, {
+  id: 'errors',
+  expectations: smokehouseDir + 'error-expectations.js',
+  config: smokehouseDir + 'error-config.js',
+  batch: 'errors',
 }, {
   id: 'pwa',
   expectations: smokehouseDir + 'pwa-expectations.js',
diff --git a/lighthouse-cli/test/smokehouse/smokehouse.js b/lighthouse-cli/test/smokehouse/smokehouse.js
index 8510b4c0b..c3bf337e9 100755
--- a/lighthouse-cli/test/smokehouse/smokehouse.js
+++ b/lighthouse-cli/test/smokehouse/smokehouse.js
@@ -15,6 +15,7 @@ const yargs = require('yargs');
 const log = require('lighthouse-logger');
 
 const PROTOCOL_TIMEOUT_EXIT_CODE = 67;
+const PAGE_HUNG_EXIT_CODE = 68;
 const RETRIES = 3;
 const NUMERICAL_EXPECTATION_REGEXP = /^(<=?|>=?)((\d|\.)+)$/;
 
@@ -87,7 +88,7 @@ function runLighthouse(url, configPath, isDebug) {
   if (runResults.status === PROTOCOL_TIMEOUT_EXIT_CODE) {
     console.error(`Lighthouse debugger connection timed out ${RETRIES} times. Giving up.`);
     process.exit(1);
-  } else if (runResults.status !== 0) {
+  } else if (runResults.status !== 0 && runResults.status !== PAGE_HUNG_EXIT_CODE) {
     console.error(`Lighthouse run failed with exit code ${runResults.status}. stderr to follow:`);
     console.error(runResults.stderr);
     process.exit(runResults.status);
@@ -98,10 +99,14 @@ function runLighthouse(url, configPath, isDebug) {
     console.error(`STDERR: ${runResults.stderr}`);
   }
 
+  if (runResults.status === PAGE_HUNG_EXIT_CODE) {
+    return {requestedUrl: url, finalUrl: url, errorCode: 'PAGE_HUNG', audits: {}};
+  }
+
   const lhr = fs.readFileSync(outputPath, 'utf8');
   if (isDebug) {
     console.log('LHR output available at: ', outputPath);
-  } else {
+  } else if (fs.existsSync(outputPath)) {
     fs.unlinkSync(outputPath);
   }
 
diff --git a/lighthouse-core/test/report/html/renderer/pwa-category-renderer-test.js b/lighthouse-core/test/report/html/renderer/pwa-category-renderer-test.js
index 92500c311..11a12a0cd 100644
--- a/lighthouse-core/test/report/html/renderer/pwa-category-renderer-test.js
+++ b/lighthouse-core/test/report/html/renderer/pwa-category-renderer-test.js
@@ -39,7 +39,12 @@ describe('PwaCategoryRenderer', () => {
     pwaRenderer = new PwaCategoryRenderer(dom, detailsRenderer);
 
     sampleResults = Util.prepareReportResult(sampleResultsOrig);
-    category = sampleResults.reportCategories.find(cat => cat.id === 'pwa');
+  });
+
+  beforeEach(() => {
+    // Clone category to allow modifications.
+    const pwaCategory = sampleResults.reportCategories.find(cat => cat.id === 'pwa');
+    category = JSON.parse(JSON.stringify(pwaCategory));
   });
 
   afterAll(() => {
@@ -90,4 +95,82 @@ describe('PwaCategoryRenderer', () => {
         `trouble with selector '${selector}'`);
     });
   });
+
+  describe('badging groups', () => {
+    let auditRefs;
+    let groupIds;
+
+    beforeEach(() => {
+      auditRefs = category.auditRefs
+        .filter(audit => audit.result.scoreDisplayMode !== 'manual');
+
+      // Expect results to all be scorable.
+      for (const auditRef of auditRefs) {
+        assert.strictEqual(auditRef.result.scoreDisplayMode, 'binary');
+      }
+
+      groupIds = [...new Set(auditRefs.map(ref => ref.group))];
+    });
+
+    it('only gives a group a badge when all the group\'s audits are passing', () => {
+      for (const auditRef of auditRefs) {
+        auditRef.result.score = 0;
+      }
+
+      const targetGroupId = groupIds[2];
+      assert.ok(targetGroupId);
+      const targetAuditRefs = auditRefs.filter(ref => ref.group === targetGroupId);
+
+      // Try every permutation of audit scoring.
+      const totalPermutations = Math.pow(2, targetAuditRefs.length);
+      for (let i = 0; i < totalPermutations; i++) {
+        for (let j = 0; j < targetAuditRefs.length; j++) {
+          // Set as passing if jth bit in i is set.
+          targetAuditRefs[j].result.score = i >> j & 1;
+        }
+
+        const categoryElem = pwaRenderer.render(category, sampleResults.categoryGroups);
+        const badgedElems = categoryElem.querySelectorAll(`.lh-badged`);
+
+        // Only expect a badge on last permutation (all bits are set).
+        const expectedBadgeCount = i === totalPermutations - 1 ? 1 : 0;
+        assert.strictEqual(badgedElems.length, expectedBadgeCount);
+      }
+    });
+
+    it('renders all badges when all audits are passing', () => {
+      for (const auditRef of auditRefs) {
+        auditRef.result.score = 1;
+      }
+
+      const categoryElem = pwaRenderer.render(category, sampleResults.categoryGroups);
+      assert.strictEqual(categoryElem.querySelectorAll('.lh-badged').length, groupIds.length);
+    });
+
+    it('renders no badges when no audit groups are passing', () => {
+      for (const auditRef of auditRefs) {
+        auditRef.result.score = 0;
+      }
+
+      const categoryElem = pwaRenderer.render(category, sampleResults.categoryGroups);
+      assert.strictEqual(categoryElem.querySelectorAll('.lh-badged').length, 0);
+    });
+
+    it('renders all but one badge when all groups but one are passing', () => {
+      for (const auditRef of auditRefs) {
+        auditRef.result.score = 1;
+      }
+      auditRefs[0].result.score = 0;
+      const failingGroupId = auditRefs[0].group;
+
+      const categoryElem = pwaRenderer.render(category, sampleResults.categoryGroups);
+
+      for (const groupId of groupIds) {
+        const expectedCount = groupId === failingGroupId ? 0 : 1;
+
+        const groupElems = categoryElem.querySelectorAll(`.lh-audit-group--${groupId}.lh-badged`);
+        assert.strictEqual(groupElems.length, expectedCount);
+      }
+    });
+  });
 });
diff --git a/lighthouse-core/test/report/html/renderer/report-renderer-test.js b/lighthouse-core/test/report/html/renderer/report-renderer-test.js
index 87c072f2d..37850907f 100644
--- a/lighthouse-core/test/report/html/renderer/report-renderer-test.js
+++ b/lighthouse-core/test/report/html/renderer/report-renderer-test.js
@@ -16,9 +16,6 @@ const DOM = require('../../../../report/html/renderer/dom.js');
 const DetailsRenderer = require('../../../../report/html/renderer/details-renderer.js');
 const ReportUIFeatures = require('../../../../report/html/renderer/report-ui-features.js');
 const CategoryRenderer = require('../../../../report/html/renderer/category-renderer.js');
-// lazy loaded because they depend on CategoryRenderer to be available globally
-let PerformanceCategoryRenderer = null;
-let PwaCategoryRenderer = null;
 const CriticalRequestChainRenderer = require(
     '../../../../report/html/renderer/crc-details-renderer.js');
 const ReportRenderer = require('../../../../report/html/renderer/report-renderer.js');
@@ -39,16 +36,12 @@ describe('ReportRenderer', () => {
     global.CriticalRequestChainRenderer = CriticalRequestChainRenderer;
     global.DetailsRenderer = DetailsRenderer;
     global.CategoryRenderer = CategoryRenderer;
-    if (!PerformanceCategoryRenderer) {
-      PerformanceCategoryRenderer =
+
+    // lazy loaded because they depend on CategoryRenderer to be available globally
+    global.PerformanceCategoryRenderer =
         require('../../../../report/html/renderer/performance-category-renderer.js');
-    }
-    global.PerformanceCategoryRenderer = PerformanceCategoryRenderer;
-    if (!PwaCategoryRenderer) {
-      PwaCategoryRenderer =
+    global.PwaCategoryRenderer =
         require('../../../../report/html/renderer/pwa-category-renderer.js');
-    }
-    global.PwaCategoryRenderer = PwaCategoryRenderer;
 
     // Stub out matchMedia for Node.
     global.matchMedia = function() {
@@ -161,4 +154,25 @@ describe('ReportRenderer', () => {
     renderer.setTemplateContext(otherDocument);
     assert.equal(renderer._templateContext, otherDocument);
   });
+
+  it('renders `not_applicable` audits as `not-applicable`', () => {
+    const clonedSampleResult = JSON.parse(JSON.stringify(sampleResultsOrig));
+
+    let notApplicableCount = 0;
+    Object.values(clonedSampleResult.audits).forEach(audit => {
+      if (audit.scoreDisplayMode === 'not-applicable') {
+        notApplicableCount++;
+        audit.scoreDisplayMode = 'not_applicable';
+      }
+    });
+
+    assert.ok(notApplicableCount > 20); // Make sure something's being tested.
+
+    const container = renderer._dom._document.body;
+    const reportElement = renderer.renderReport(sampleResults, container);
+    const notApplicableElementCount = reportElement
+      .querySelectorAll('.lh-audit--not-applicable').length;
+
+    assert.strictEqual(notApplicableCount, notApplicableElementCount);
+  });
 });
diff --git a/lighthouse-core/test/report/html/renderer/report-ui-features-test.js b/lighthouse-core/test/report/html/renderer/report-ui-features-test.js
index cea3db85e..1b3566fca 100644
--- a/lighthouse-core/test/report/html/renderer/report-ui-features-test.js
+++ b/lighthouse-core/test/report/html/renderer/report-ui-features-test.js
@@ -16,9 +16,6 @@ const DOM = require('../../../../report/html/renderer/dom.js');
 const DetailsRenderer = require('../../../../report/html/renderer/details-renderer.js');
 const ReportUIFeatures = require('../../../../report/html/renderer/report-ui-features.js');
 const CategoryRenderer = require('../../../../report/html/renderer/category-renderer.js');
-// lazy loaded because they depend on CategoryRenderer to be available globally
-let PerformanceCategoryRenderer = null;
-let PwaCategoryRenderer = null;
 const CriticalRequestChainRenderer = require(
     '../../../../report/html/renderer/crc-details-renderer.js');
 const ReportRenderer = require('../../../../report/html/renderer/report-renderer.js');
@@ -41,16 +38,12 @@ describe('ReportUIFeatures', () => {
     global.CriticalRequestChainRenderer = CriticalRequestChainRenderer;
     global.DetailsRenderer = DetailsRenderer;
     global.CategoryRenderer = CategoryRenderer;
-    if (!PerformanceCategoryRenderer) {
-      PerformanceCategoryRenderer =
+
+    // lazy loaded because they depend on CategoryRenderer to be available globally
+    global.PerformanceCategoryRenderer =
         require('../../../../report/html/renderer/performance-category-renderer.js');
-    }
-    global.PerformanceCategoryRenderer = PerformanceCategoryRenderer;
-    if (!PwaCategoryRenderer) {
-      PwaCategoryRenderer =
+    global.PwaCategoryRenderer =
         require('../../../../report/html/renderer/pwa-category-renderer.js');
-    }
-    global.PwaCategoryRenderer = PwaCategoryRenderer;
 
     // Stub out matchMedia for Node.
     global.matchMedia = function() {
diff --git a/lighthouse-core/test/report/html/renderer/util-test.js b/lighthouse-core/test/report/html/renderer/util-test.js
index e870d48fd..bb33a218d 100644
--- a/lighthouse-core/test/report/html/renderer/util-test.js
+++ b/lighthouse-core/test/report/html/renderer/util-test.js
@@ -7,6 +7,7 @@
 
 const assert = require('assert');
 const Util = require('../../../../report/html/renderer/util.js');
+const sampleResult = require('../../../results/sample_v2.json');
 
 const NBSP = '\xa0';
 
@@ -168,4 +169,24 @@ describe('util helpers', () => {
     Util.formatDisplayValue(displayValue);
     assert.deepStrictEqual(displayValue, cloned, 'displayValue was mutated');
   });
+
+  describe('#prepareReportResult', () => {
+    it('corrects underscored `not-applicable` scoreDisplayMode', () => {
+      const clonedSampleResult = JSON.parse(JSON.stringify(sampleResult));
+
+      let notApplicableCount = 0;
+      Object.values(clonedSampleResult.audits).forEach(audit => {
+        if (audit.scoreDisplayMode === 'not-applicable') {
+          notApplicableCount++;
+          audit.scoreDisplayMode = 'not_applicable';
+        }
+      });
+
+      assert.ok(notApplicableCount > 20); // Make sure something's being tested.
+
+      // Original audit results should be restored.
+      const preparedResult = Util.prepareReportResult(clonedSampleResult);
+      assert.deepStrictEqual(preparedResult.audits, sampleResult.audits);
+    });
+  });
 });
diff --git a/lighthouse-core/test/results/sample_v2.json b/lighthouse-core/test/results/sample_v2.json
index d6bbe1740..053f381a5 100644
--- a/lighthouse-core/test/results/sample_v2.json
+++ b/lighthouse-core/test/results/sample_v2.json
@@ -5,7 +5,7 @@
     "hostUserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3358.0 Safari/537.36",
     "benchmarkIndex": 1000
   },
-  "lighthouseVersion": "4.0.0-alpha.0",
+  "lighthouseVersion": "4.0.0-alpha.1",
   "fetchTime": "2018-03-13T00:55:45.840Z",
   "requestedUrl": "http://localhost:10200/dobetterweb/dbw_tester.html",
   "finalUrl": "http://localhost:10200/dobetterweb/dbw_tester.html",