diff --git a/tools/performance/README.md b/tools/performance/README.md index 5e251c7ca1a7..cb312082002d 100644 --- a/tools/performance/README.md +++ b/tools/performance/README.md @@ -56,9 +56,44 @@ Each scenario posts its metrics in a single CodeVitals call per run (one per `me - **Decoded bytes, not transfer size.** The measured load is a warm-cache `page.reload()`, where cached resources report `transferSize: 0`; and the Docker WordPress serves uncompressed, so `transferSize` would neither survive caching nor match production's gzipped bytes. `decodedBodySize` is cache- and compression-independent, so it stays stable however assets are served. It maps to the decoded (uncompressed) byte count, not the gzipped wire size — fine for a trend. - **Runtime payload, not build output.** The regression this watches is the wp-build `boot` shell statically pulling core `@wordpress/editor` into pages that never open an editor. Those are externalized `@wordpress/*` core modules, resolved through the wp-build import map as separate static files, not the plugin's own bundle, so a check against the built plugin's own file sizes wouldn't move when they are lazy-loaded. Summing the resources the page actually downloads does, so the line falls when the fix lands and flags the next silent jump. -- **On the Forms responses page specifically.** It's a shipped wp-build dashboard that loads the boot shell's editor payload; the wp-admin Dashboard does not, so the bundle-size metric is posted only for `formsResponses`. +- **On the Forms responses page specifically.** It's a shipped wp-build dashboard that loads the boot shell's editor payload; the wp-admin Dashboard does not, so the bundle-size metric is posted for `formsResponses` (and, for the heavy-bundle reason below, `myJetpack`), not the Dashboard. - **Detects a jump, doesn't attribute it.** The value sums every resource on the page, not the editor payload alone (that payload is roughly 1.3 MB of the ~8.2 MB total, about 16%). The other ~84% is ordinary page weight, so on this actively-developed dashboard most trend moves will be routine Forms feature work rather than the editor payload the metric is meant to catch. A move flags that page weight changed; confirming the cause means reading the per-resource breakdown in the saved `results.json`, not the dashboard line. +### `myJetpack` — My Jetpack admin page (simulated connection) + +`admin.php?page=my-jetpack`, measured on the same simulated-connection instance as the Dashboard and Forms scenarios. My Jetpack is the heaviest Jetpack admin bundle (its own ~1.3 MB JS + CSS on top of core script handles), so it is the page where a bundle regression is most damaging — hence the `decodedBytesKB` metric is posted here too. + +The page mounts a React app: PHP emits an empty `
` and `createRoot` renders `MyJetpackScreen` into it. The scenario waits for `#my-jetpack-container .jp-admin-page` (a non-hashed class from `@automattic/jetpack-components` `AdminPage`, present only after React renders) and for the container to hydrate before measuring, so LCP and the resource payload reflect the rendered page, not the empty shell. + +| CodeVitals key | Field | Type | Description | +| ------------------------------------------------------ | ---------------- | ---------------- | --------------------------------------------------------- | +| `my-jetpack-connection-sim-largestContentfulPaint` | `lcp` | `lcp` | My Jetpack LCP | +| `my-jetpack-connection-sim-timeToFirstByte` | `ttfb` | `ttfb` | My Jetpack TTFB | +| `my-jetpack-connection-sim-firstContentfulPaint` | `fcp` | `fcp` | My Jetpack FCP | +| `my-jetpack-connection-sim-decodedBytesKB` | `decodedBytesKB` | `decodedBytesKB` | Bundle size: summed per-resource `decodedBodySize`, in KB | + +These four post straight to production keys under the same owner waiver as the Dashboard and Forms keys (see Safeguards → Staging keys). + +#### Requires offline mode OFF (and the `wp-theme` polyfill in the mirror build) + +Two conditions must hold for My Jetpack to render in the fixture: + +1. **Offline mode off.** The fixture's site URL (`http://localhost:`) has no dot, so `Status::is_local_site()` treats it as a local site and Jetpack enters offline mode, which makes `Initializer::should_initialize()` return false — My Jetpack never registers (no menu, no assets; the page is the generic "invalid page" admin shell). The `simulate-wpcom-connection` mu-plugin flips this with `add_filter( 'jetpack_offline_mode', '__return_false' )`. This is **install-wide** — see the attribution note below. +2. **`wp-theme` registered.** On trunk (Jetpack 16.1+), `my_jetpack_main_app` gained a `wp-theme` script dependency via the `@wordpress/*` bump (DataViews 17.x → `@wordpress/ui` ThemeProvider → `@wordpress/theme`). WordPress < 7.0 without the Gutenberg plugin does not register `wp-theme`, so WP silently drops the app script and the container stays empty (no console error). [#50291](https://github.com/Automattic/jetpack/pull/50291) fixed this in `My_Jetpack\Initializer` by registering the `WP_Build_Polyfills` shim (as Forms/Social/VideoPress already do). It merged on 2026-07-08 and is present in the `jetpack-production` mirror the fixture clones (verified against mirror commit `9ef44a8`, 2026-07-10: a clean checkout renders My Jetpack and passes every capture guard). Treat it as a baseline prerequisite: a mirror checkout that predates #50291 renders the page empty and fails the `waitForSelector`. + +### Offline-mode flip — attribution note + +This tooling flips `jetpack_offline_mode` off install-wide (required for My Jetpack, condition 1 above). Because one WordPress install serves every scenario, this shifts what the **existing** `wp-admin-dashboard-connection-sim-*` and `forms-responses-connection-sim-*` trends measure at the commit it lands: Jetpack runs more code paths when it is not offline. Locally measured before/after on the Dashboard scenario (the one existing scenario that measures cleanly here — see the Forms note below) was small: LCP 140→140 ms, TTFB 57→60 ms, FCP 140→140 ms, decodedBytesKB 4098→4205, resources 89→98. The timing metrics move within noise; the real signal is +9 resources / +107 KB decoded (the extra non-offline code paths). Expect a one-time baseline level shift of that order at the landing commit — every later point measures the non-offline fixture, so the trend settles at the new level rather than returning to the old one. It is a measurement-boundary change, not an ongoing regression. + +The `forms-responses-*` trends could not be measured before/after locally: in the local fixture the Forms responses page's `GET /wp/v2/settings` REST request hangs server-side (>60 s, `networkidle` never settles), so every iteration times out (re-verified 2026-07-10 on mirror commit `9ef44a8`). This is a pre-existing local-fixture issue, independent of the offline flip (it hangs with offline on or off) and unrelated to this change — the Forms scenario shipped in a prior PR. Flagged here so a Forms-trend gap around this commit is not mistaken for a regression. + +### Known fixture behavior on the My Jetpack page + +Accepted as-is (mock realism is tracked in BOOST-456, not fixed here): + +- The page's `wpcom/v2/jetpack-partners` call falls through to the mu-plugin's generic `{"success":true}` fallback and logs a `[WPCom Simulator] Unhandled endpoint (using fallback response): …/jetpack-partners` line each load. This is expected fixture noise, not an error. +- Calls scoped under `/sites/{id}/...` (stats, protect scan, videopress) are shadowed by the mock's `/sites/123456789` site-info branch (it precedes the `/stats/*` branches in the first-match chain) and receive site-info-shaped 200s — semantically wrong, so those cards render empty. Deterministic; fine for trend tracking. + ## How It Works 1. **Plugin Source**: Uses pre-built plugin from [jetpack-production](https://github.com/Automattic/jetpack-production) mirror (auto-cloned for local dev) @@ -106,7 +141,7 @@ Add a row when a new metric type starts being posted, and set the `type` on the Post a new metric to a `-staging` CodeVitals key first (e.g. `…-timeToFirstByte-staging`) for 2-3 builds. Inspect the values in the CodeVitals UI, then rename to the production key. This gives a safety window before a new metric reaches production. -**Waiving the staging window (owner decision).** A scenario may post straight to production keys when the build owner accepts the risk, as the `formsResponses` metrics do. The waiver is not automatic — it requires all of: the `SANITY_RANGES` row + the all-or-nothing gate as the substitute guardrail, manual sign-off before the first live post, and the PR that introduces the keys listing them and naming the waiver so the impact is visible in review. A dry run's `stdDev: 0` shows repeatability, not correctness, so it is not the safeguard. The per-scenario comment in `scenarios.js` records where a waiver is in effect. +**Waiving the staging window (owner decision).** A scenario may post straight to production keys when the build owner accepts the risk, as the `formsResponses` and `myJetpack` metrics do. The waiver is not automatic — it requires all of: the `SANITY_RANGES` row + the all-or-nothing gate as the substitute guardrail, manual sign-off before the first live post, and the PR that introduces the keys listing them and naming the waiver so the impact is visible in review. A dry run's `stdDev: 0` shows repeatability, not correctness, so it is not the safeguard. The per-scenario comment in `scenarios.js` records where a waiver is in effect. ### Capture guards for targeted-page scenarios diff --git a/tools/performance/docker/mu-plugins/simulate-wpcom-connection.php b/tools/performance/docker/mu-plugins/simulate-wpcom-connection.php index e0fc196b223c..3e58c6b03a8b 100644 --- a/tools/performance/docker/mu-plugins/simulate-wpcom-connection.php +++ b/tools/performance/docker/mu-plugins/simulate-wpcom-connection.php @@ -70,6 +70,23 @@ class Jetpack_WPCom_Connection_Simulator { public function __construct() { $this->latency_ms = getenv( 'WPCOM_SIMULATED_LATENCY_MS' ) ? (int) getenv( 'WPCOM_SIMULATED_LATENCY_MS' ) : 200; + // Force Jetpack offline mode OFF. The fixture's site URL (http://localhost:) + // contains no dot, so Status::is_local_site() treats it as a local site and Jetpack + // enters offline mode. Offline mode blocks My Jetpack from initializing at all + // (Initializer::should_initialize()), yet this fixture explicitly simulates a + // production, connected site. This is install-wide: flipping it shifts what EVERY + // scenario measures (Jetpack runs more code paths when not offline) — see the + // offline-mode attribution note in README.md. + // + // Two filters are needed because Status::is_offline_mode() falls back to the stored + // option when the filtered value is false: `$offline = (bool) apply_filters( ... ); + // if ( ! $offline ) { $offline = (bool) get_option( 'jetpack_offline_mode' ); }`. The + // first filter overrides the is_local_site() result; pre_option_* forces the option + // read to 0 so a dirty/reused fixture DB with jetpack_offline_mode=1 can't silently + // turn offline mode back on and break every scenario's boot. + add_filter( 'jetpack_offline_mode', '__return_false' ); + add_filter( 'pre_option_jetpack_offline_mode', '__return_zero' ); + // Set up fake connection on init (after Jetpack loads). add_action( 'plugins_loaded', array( $this, 'setup_fake_connection' ), 1 ); diff --git a/tools/performance/scripts/post-to-codevitals.test.js b/tools/performance/scripts/post-to-codevitals.test.js index a0f70c885206..ef0b90e5bab5 100644 --- a/tools/performance/scripts/post-to-codevitals.test.js +++ b/tools/performance/scripts/post-to-codevitals.test.js @@ -51,6 +51,10 @@ const FORMS_LCP_KEY = 'forms-responses-connection-sim-largestContentfulPaint'; const FORMS_TTFB_KEY = 'forms-responses-connection-sim-timeToFirstByte'; const FORMS_FCP_KEY = 'forms-responses-connection-sim-firstContentfulPaint'; const FORMS_DECODED_KEY = 'forms-responses-connection-sim-decodedBytesKB'; +const MJ_LCP_KEY = 'my-jetpack-connection-sim-largestContentfulPaint'; +const MJ_TTFB_KEY = 'my-jetpack-connection-sim-timeToFirstByte'; +const MJ_FCP_KEY = 'my-jetpack-connection-sim-firstContentfulPaint'; +const MJ_DECODED_KEY = 'my-jetpack-connection-sim-decodedBytesKB'; /** * Build the nested per-field summary the multi-metric jetpackConnected scenario reads. @@ -81,16 +85,39 @@ function formsSummary( { lcp = 300, ttfb = 200, fcp = 500, decodedBytesKB = 8229 }; } +/** + * Build the nested per-field summary the myJetpack scenario reads: the same shape as + * formsSummary (three timing fields + the bundle-size field). LCP (~640) and decodedBytesKB + * (~5860) track the observed local medians; ttfb/fcp are plausible in-range fillers. All four + * sit inside SANITY_RANGES so they post cleanly unless a test overrides one. + */ +function myJetpackSummary( { lcp = 640, ttfb = 220, fcp = 560, decodedBytesKB = 5860 } = {} ) { + return { + median: lcp, + lcp: { median: lcp }, + ttfb: { median: ttfb }, + fcp: { median: fcp }, + decodedBytesKB: { median: decodedBytesKB }, + }; +} + /** * Write a results fixture and return its path. `median` is the LCP median (kept as the * first positional arg so existing single-arg call sites read the same); TTFB and FCP * default to in-range values so the two new metrics post cleanly unless overridden. Pass - * `forms` (an object of field overrides) to also include a `formsResponses` measurement; omit - * it and only `jetpackConnected` is written, exactly as before. + * `forms` and/or `myJetpack` (objects of field overrides) to also include those measurements; + * omit both and only `jetpackConnected` is written, exactly as before. */ function writeResults( median, - { ttfb = 150, fcp = 400, hash = 'testhash', branch = 'trunk', forms = null } = {} + { + ttfb = 150, + fcp = 400, + hash = 'testhash', + branch = 'trunk', + forms = null, + myJetpack = null, + } = {} ) { const dir = fs.mkdtempSync( path.join( os.tmpdir(), 'cv-results-' ) ); const file = path.join( dir, 'results.json' ); @@ -100,6 +127,9 @@ function writeResults( if ( forms ) { measurements.formsResponses = { summary: formsSummary( forms ) }; } + if ( myJetpack ) { + measurements.myJetpack = { summary: myJetpackSummary( myJetpack ) }; + } fs.writeFileSync( file, JSON.stringify( { git: { hash, branch }, measurements } ) ); return file; } @@ -486,6 +516,50 @@ test( 'the formsResponses scenario posts LCP, TTFB, FCP and decodedBytes to prod ); } ); +test( 'the myJetpack scenario posts LCP, TTFB, FCP and decodedBytes to production keys', () => { + // Pins the FORMS-717 config: the My Jetpack admin page (the heaviest Jetpack admin bundle) + // carries the bundle-size metric (summary.decodedBytesKB.median) alongside the timing metrics, + // each on its own production key. A dropped/renamed key, or a decoded metric with no type + // (which would post unchecked), fails here rather than silently in the append-only store. + const scenario = SCENARIOS.find( s => s.key === 'myJetpack' ); + assert.ok( scenario, 'myJetpack scenario must exist' ); + assert.ok( Array.isArray( scenario.metrics ), 'myJetpack must use the metrics array' ); + assert.deepEqual( + scenario.metrics.map( m => ( { + field: m.field, + codevitalsKey: m.codevitalsKey, + type: m.type, + } ) ), + [ + { field: 'lcp', codevitalsKey: MJ_LCP_KEY, type: 'lcp' }, + { field: 'ttfb', codevitalsKey: MJ_TTFB_KEY, type: 'ttfb' }, + { field: 'fcp', codevitalsKey: MJ_FCP_KEY, type: 'fcp' }, + { field: 'decodedBytesKB', codevitalsKey: MJ_DECODED_KEY, type: 'decodedBytesKB' }, + ] + ); + // The page-navigation contract measure-lcp.js reads: a target path + a hydration selector. + // The selector is the AdminPage frame that appears only after React renders MyJetpackScreen + // into the (initially empty) container, so a run measures the rendered app, not the shell. + assert.equal( scenario.path, '/wp-admin/admin.php?page=my-jetpack' ); + assert.equal( scenario.waitForSelector, '#my-jetpack-container .jp-admin-page' ); + // A weak guard on its own: My Jetpack is a single-slug SPA, so every view keeps + // `page=my-jetpack` — even the not-connected redirect to `&step=onboarding`. What actually + // stops a wrong-view post is the `.jp-admin-page` selector above (OnboardingScreen renders + // without AdminPage, so it never matches). expectUrlIncludes only catches a redirect that + // leaves My Jetpack entirely. + assert.equal( scenario.expectUrlIncludes, 'page=my-jetpack' ); + // A resource-count floor so a partial capture can't post an undercounted decodedBytesKB. + // Pin the exact value (siblings pin every field by equality) so a later edit toward the + // ~90-resource load can't erode the margin silently, and exercise the real guard at the + // boundary: one below the floor must throw, the floor itself must not. + assert.equal( scenario.minResourceCount, 64 ); + assert.throws( + () => assertCaptureComplete( { totalRequests: 63 }, scenario ), + /Incomplete capture: 63 resources < expected minimum 64/ + ); + assert.doesNotThrow( () => assertCaptureComplete( { totalRequests: 64 }, scenario ) ); +} ); + // --- redactToken (keeps the token out of logs and errors) --- test( 'redactToken strips the exact token and any token query param', () => { @@ -529,6 +603,25 @@ test( 'dry-run with both scenarios present posts all 7 keys, including the Forms assert.equal( Object.keys( result.payload.metrics ).length, 7 ); } ); +test( 'dry-run with all three scenarios present posts all 11 keys, including the My Jetpack decoded-bytes key', async () => { + // The full automated run measures all three scenarios, so the payload carries jetpackConnected's + // 3 timing keys, formsResponses' 4, AND myJetpack's 4 (timing + decodedBytesKB). The config test + // pins the myJetpack keys statically; this proves they reach the payload with the right values + // under the exact production key names, so a wiring regression in the scenario-agnostic loop + // (a dropped/renamed myJetpack metric) fails here rather than silently in the append-only store. + const file = writeResults( 120, { + forms: { decodedBytesKB: 8229 }, + myJetpack: { lcp: 640, ttfb: 220, fcp: 560, decodedBytesKB: 5860 }, + } ); + const result = await silenced( () => postToCodeVitals( file, { dryRun: true } ) ); + assert.equal( result.validationFailed, false ); + assert.equal( result.payload.metrics[ MJ_LCP_KEY ], 640 ); + assert.equal( result.payload.metrics[ MJ_TTFB_KEY ], 220 ); + assert.equal( result.payload.metrics[ MJ_FCP_KEY ], 560 ); + assert.equal( result.payload.metrics[ MJ_DECODED_KEY ], 5860 ); + assert.equal( Object.keys( result.payload.metrics ).length, 11 ); +} ); + test( 'a live run with an out-of-range Forms decodedBytesKB posts nothing and never calls fetch', async () => { // The append-only guarantee end to end: one out-of-range decoded value (52000 > max 51200) // fails its sanity check, the per-run atomic gate commits to posting nothing, and fetch is diff --git a/tools/performance/scripts/scenarios.js b/tools/performance/scripts/scenarios.js index c77706b4cf9f..9ef612537f1c 100644 --- a/tools/performance/scripts/scenarios.js +++ b/tools/performance/scripts/scenarios.js @@ -117,6 +117,71 @@ export const SCENARIOS = [ postToCodeVitals: true, isBaseline: false, }, + { + key: 'myJetpack', + name: 'My Jetpack (connection sim)', + cliName: 'my-jetpack', + // Same WordPress instance as the Dashboard and Forms scenarios — just a different page — + // so no new Docker service is needed; only `path`/`waitForSelector` below differ. + dockerService: 'wordpress-jetpack-connected', + wpPath: '/var/www/html/jetpack-connected', + envVar: 'WP_JETPACK_CONNECTED_URL', + defaultUrl: 'http://localhost:8083', + header: 'My Jetpack (simulated WP.com connection)', + // The My Jetpack admin page - the heaviest Jetpack admin bundle. PHP emits an empty + // `
` and React (createRoot) renders MyJetpackScreen into + // it, so measure-lcp.js waits for the AdminPage frame (`.jp-admin-page`, a non-hashed + // class from @automattic/jetpack-components) to appear so a run measures the rendered app, + // not the empty shell. Capture completeness then rests on the networkidle wait plus the + // stable resource count, not the frame selector (`.jp-admin-page` renders with its children + // in one commit, so its presence is not a load-finished proxy) and not networkidle alone + // (the async product cards can settle after a quiet gap). The minResourceCount floor below + // is the backstop against gross truncation. + // + // Requires offline mode OFF (Status::is_offline_mode() gates + // Initializer::should_initialize(); localhost has no dot so the fixture is "local" = + // offline by default): the simulate-wpcom-connection mu-plugin flips it. See the README + // offline-mode attribution note. + path: '/wp-admin/admin.php?page=my-jetpack', + waitForSelector: '#my-jetpack-container .jp-admin-page', + expectUrlIncludes: 'page=my-jetpack', + // A healthy load of this page fetches ~92 resources (stable across iterations locally); + // measure-lcp.js fails the run if it captures fewer than this floor, so a truncated/partial + // capture can't post an in-range but undercounted decodedBytesKB. Set to ~70% of the observed + // count (count-based, not asset-based) so it only catches gross capture truncation. + minResourceCount: 64, + // These four post straight to PRODUCTION keys — the `-staging` window in the README + // Safeguards is deliberately waived here (owner decision, Liam 2026-07-08), same rationale + // and substitute guardrails (SANITY_RANGES + all-or-nothing gate + manual sign-off) as the + // wp-admin-dashboard and forms-responses keys. + metrics: [ + { + field: 'lcp', + codevitalsKey: 'my-jetpack-connection-sim-largestContentfulPaint', + type: 'lcp', + }, + { + field: 'ttfb', + codevitalsKey: 'my-jetpack-connection-sim-timeToFirstByte', + type: 'ttfb', + }, + { + field: 'fcp', + codevitalsKey: 'my-jetpack-connection-sim-firstContentfulPaint', + type: 'fcp', + }, + { + // The bundle-size metric: summed per-resource decodedBodySize in KB (see + // measure-lcp.js). My Jetpack is the heaviest Jetpack admin bundle, so this is + // the surface a bundle regression is most damaging on. + field: 'decodedBytesKB', + codevitalsKey: 'my-jetpack-connection-sim-decodedBytesKB', + type: 'decodedBytesKB', + }, + ], + postToCodeVitals: true, + isBaseline: false, + }, ]; /** @@ -135,12 +200,12 @@ export const SANITY_RANGES = { fcp: { min: 50, max: 30000 }, tbt: { min: 0, max: 10000 }, // Can legitimately be 0; >10s is catastrophic. cls: { min: 0, max: 5 }, // >5 would mean the page is unusable. - // Summed per-resource decodedBodySize, in KB. The Forms responses wp-build dashboard - // measures ~8200 KB (deterministic across iterations). These are guardrails against a - // broken measurement, NOT a trend clip: min 1000 catches a page that failed to load its - // wp-build shell (a real dashboard is always well over 1MB decoded); max 51200 (50MB) - // catches a bytes-vs-KB scale error while staying clear of any legitimate regression, which - // the trend should record rather than reject. + // Summed per-resource decodedBodySize, in KB. This row now guards two scenarios: the Forms + // responses wp-build dashboard (~8200 KB) and My Jetpack (~5860 KB), so do not tighten it to + // either page's profile. These are guardrails against a broken measurement, NOT a trend clip: + // min 1000 catches a page that failed to load its wp-build shell (a real dashboard is always + // well over 1MB decoded); max 51200 (50MB) catches a bytes-vs-KB scale error while staying + // clear of any legitimate regression, which the trend should record rather than reject. decodedBytesKB: { min: 1000, max: 51200 }, };