Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions tools/performance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<div id="my-jetpack-container">` 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:<port>`) 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)
Expand Down Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:<port>)
// 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' );
Comment on lines +87 to +88

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Just a reminder rather than a change request: since this flip is install-wide, please make sure the CodeVitals annotation lands on the existing wp-admin-dashboard-* / forms-responses-* keys at the landing commit — the +9 resources / +107 KB step will read as a regression later without it. Easy to drop since it's a non-code action.

Also wanted to call out the nice detail here: using __return_zero (not __return_false) for the pre_option_ filter is exactly right — pre_option only short-circuits get_option when the value is !== false, so __return_false would quietly fall through to the stored option. The inline comment explaining that is much appreciated. 🙏

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Noted, and it won't get dropped: annotating the existing wp-admin-dashboard-* / forms-responses-* keys at the landing commit is on the landing checklist, and the PR description calls it out in the rollout notes for the same reason.

Thanks for the kind words on __return_zero! The pre_option short-circuit was subtle enough to bite silently, so the comment felt worth the lines.


// Set up fake connection on init (after Jetpack loads).
add_action( 'plugins_loaded', array( $this, 'setup_fake_connection' ), 1 );

Expand Down
99 changes: 96 additions & 3 deletions tools/performance/scripts/post-to-codevitals.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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' );
Expand All @@ -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;
}
Expand Down Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading