Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install k6-perf-test-website@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin k6-perf-test-website v1.0.0 follows the Agent Plugins spec.
gh skills-hub install k6-perf-test-website Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/k6-perf-test-website/ Extract the ZIP to .github/skills/ in your repo. The folder name must match k6-perf-test-website for Copilot to auto-discover it.
Skill Files (28)
SKILL.md 13.5 KB
---
name: k6-perf-test-website
description: >
Use when the user wants to performance-test, load-test, or stress-test
a public website end-to-end with k6. Produces a hybrid (protocol +
browser) test suite, SLO-backed thresholds, a load-generator monitor
sidecar, and a Grafana-side investigation playbook for backends the
user owns. Triggers on "perf test my site", "performance test my
site", "load test this URL",
"stress test my web app", "I want to load test [URL]", "set up k6
against my website", "write a k6 suite for [site]", "see if my site
handles N concurrent users", or "how does my site perform under
traffic". Use this skill whenever the user mentions k6, load testing,
stress testing, performance testing, or wants to validate a website
under traffic — even if they don't explicitly use the word "test" or
ask for the specific outputs this skill produces. This skill is for a
full multi-test suite across several workflows; for a single browser test —
functional OR a browser load test measuring Web Vitals for one journey —
use k6-browser-test.
---
# `k6-perf-test-website`
An end-to-end, opinionated workflow for performance-testing any
public website with k6. The skill produces:
- A scaffolded project with one folder per user-described workflow.
- Functional protocol + browser tests (must pass before load testing).
- Hybrid load tests (protocol scenario + 1 browser VU) per test type
(smoke / average / stress / spike / soak / breakpoint).
- SLO-backed thresholds with per-endpoint tagging and Web Vitals.
- A cross-platform load-generator monitor sidecar.
- Optional Grafana-side investigation when the user owns the backend.
- A structured Markdown report at the end.
> **Just want one functional browser test from a plain-language journey?**
> This skill builds a full, multi-test performance *suite*. For a single
> `k6/browser` functional (or standalone browser load) test — with selectors
> discovered by exploring the live site — use the **k6-browser-test** skill
> instead.
This skill enforces a few opinions you should not silently override:
- **Always elicit workflows first.** Don't guess.
- **Functional tests must be green before load tests run.**
- **Always monitor the load generator** — server-looks-slow is often
laptop-looks-slow.
- **Local for validation, cloud for scale** — but ask the user where
to run each test type; don't hardcode.
- **No shared `tests/lib/`.** Iteration-body duplication is preferred;
each script reads cleanly on its own during incident review.
## Prerequisites
- **k6 ≥ v2.0.0** (`k6 version`) — required for stable `k6/browser`,
`expect()`, async/await iteration functions, and per-request `tags`.
- **Node.js ≥ 20** + npm.
- **Playwright** with the Chromium download
(`npx playwright install chromium`).
- **`har-to-k6`** (`npm i -D har-to-k6`).
- Network access from the load-generator host to the target site.
Tools the skill prefers when installed:
- `mcp-k6` — script creation, Playwright→k6/browser migration, API
lookup. Prefer over hand-writing k6 boilerplate.
- `mcp-grafana` — in-session Prometheus/Loki/Tempo/Pyroscope queries
during §9 backend investigation.
- `gcx` — Grafana Cloud CLI for shell-friendly queries, datasource
discovery, and Grafana Cloud k6 cloud-run dispatch.
- `k6` binary — local validation runs and breakpoint hunting.
- `k6 x docs` (xk6-docs) — look up k6 API surface when writing or
editing scripts without `mcp-k6` available.
If these tools are not configured the skill falls back to plain CLI
tools (`k6`, `npx`, `curl`) and hand-written scripts. The skill does
not own toolchain setup; defer to the user's existing setup process.
Explicit non-goals:
- Protocol-only suites (out of scope for this skill).
- API-only / non-browser apps.
- Mobile-native testing.
- Capacity planning beyond finding and tagging a breakpoint.
## Workflow overview
Tick these off in order. Each step has a section below.
1. Elicit workflows from the user. [§1](#1-elicit-workflows)
2. Scaffold the project from `assets/`. [§2](#2-scaffold-the-project)
3. Record each workflow with Playwright. [§3](#3-record-each-workflow)
4. Build functional protocol + browser tests; run `tests/run-all.sh`
until green. [§4](#4-build-functional-tests)
5. Design SLO-backed thresholds and per-endpoint tags.
[§5](#5-design-slos-and-thresholds)
6. Build hybrid load tests, one file per test type.
[§6](#6-build-hybrid-load-tests)
7. Run validation locally with the LG sidecar.
[§7](#7-run-locally-with-lg-sidecar)
8. Push to Grafana Cloud k6 for the test types the user chose for
cloud. [§8](#8-push-to-grafana-cloud-k6)
9. Investigate the backend with Grafana (if owned).
[§9](#9-investigate-the-backend)
10. Report back to the user. [§10](#10-report-back)
## 1. Elicit workflows
**The single most important step.** Without explicit workflows, every
later step is guesswork.
Ask the user the questions in `references/workflow-elicitation.md`
and record answers in a `runbook.md` alongside the scaffolded project.
You must capture: 2-4 named workflows, credentials, read vs write,
destructive actions to avoid during soak, worry list, existing SLOs,
backend ownership and Grafana access, and **per test type** whether
each runs locally or in Grafana Cloud k6.
If the user can't name at least one workflow, **stop and clarify**;
do not proceed.
## 2. Scaffold the project
Copy the `assets/` tree from this skill into the user's chosen
directory. The skill's `assets/` directory is at `<SKILL_DIR>/assets/`,
where `<SKILL_DIR>` is the absolute path to this skill's directory —
your harness exposes this (e.g. opencode prefixes skill metadata with
a `Base directory for this skill:` line). If you can't determine
`<SKILL_DIR>` from context, ask the user.
```bash
cp -R "<SKILL_DIR>/assets/." "<target-dir>/"
```
If `cp -R` is blocked by sandbox permissions, copy files individually
via your agent's file-write tool.
The scaffolded layout:
```
<target-dir>/
├── package.json
├── .gitignore
├── README.md
├── runbook.md # you create from §1 answers
├── recordings/
│ ├── README.md
│ └── scripts/
│ └── recorder.template.js # copy per workflow → wN-<short-name>.js, …
├── tests/
│ ├── run-all.sh
│ └── workflow.template/ # copy per workflow → wN-<short-name>/, …
│ ├── from-har.js
│ ├── protocol.js
│ ├── browser.js
│ ├── smoke.js
│ ├── average.js
│ ├── stress.js
│ ├── spike.js
│ ├── soak.js
│ └── breakpoint.js
└── tools/
├── lg-monitor.sh
└── run-with-monitor.sh
```
For each workflow: copy `recorder.template.js` → `recordings/scripts/wN-<short-name>.js`,
copy `tests/workflow.template/` → `tests/wN-<short-name>/`, and
replace `<WORKFLOW_PLACEHOLDER>` markers with the workflow's short name.
Then install:
```bash
cd <target-dir> && npm install && npx playwright install chromium
```
## 3. Record each workflow
Per workflow:
1. Fill in `recordings/scripts/wN-<short-name>.js`: user-action sequence,
`recordHar.urlFilter` regex (allow-list the target host; block
third-party RUM/ads — see `references/recording-with-playwright.md`),
and a real Chrome `userAgent` (the default `HeadlessChrome` UA
triggers bot-blocking on many sites).
2. Run: `node recordings/scripts/wN-<short-name>.js` → writes `recordings/har/wN-<short-name>.har`
3. Convert: `npx har-to-k6 recordings/har/wN-<short-name>.har -o tests/wN-<short-name>/from-har.js`
4. Commit both HAR and `from-har.js` (audit trail for bundle-path changes).
If the recorder fails or produces an unusable HAR (bot-blocking,
missing hydration, third-party noise), see the Recording section of
`references/gotchas.md` and `references/recording-with-playwright.md`.
Prefer `mcp-k6` recording and migration tools if available.
## 4. Build functional tests
Per workflow:
1. Hand-clean `from-har.js` into `protocol.js` — drop per-request
UA headers, rename groups, parameterise `BASE_URL`, replace session
tokens, drop `sleep(1)`, add `expect()` on every load-bearing
response. Full procedure in `references/functional-tests.md`.
2. Hand-write `browser.js` from the Playwright recorder using the
5-step procedure in `references/functional-tests.md`.
3. Run `./tests/run-all.sh`. **Do not proceed to §5 until it exits 0.**
Prefer `mcp-k6` migration tools for Playwright→k6/browser conversion.
## 5. Design SLOs and thresholds
Adjust the opinionated defaults in `assets/tests/workflow.template/`
to the user's stated SLOs from §1. Four layers:
1. **Global SLOs** — overall error rate + aggregate latency.
2. **Per-endpoint thresholds** — tag every protocol request, threshold per tag.
3. **Per-iteration thresholds** — workflow time + iteration completion rate.
4. **Web Vitals** — LCP/INP/CLS only (no FCP).
Default globals:
```js
http_req_failed: ['rate<0.01'],
http_req_duration: ['p(95)<500'],
checks: ['rate>0.99'],
```
Per-endpoint tagging:
```js
http.get(`${BASE_URL}/api/things`, { tags: { name: 'GetThings' } });
'http_req_duration{name:GetThings}': ['p(95)<400', 'p(99)<800'],
```
Web Vitals:
```js
browser_web_vital_lcp: ['p(95)<2500'],
browser_web_vital_inp: ['p(95)<200'],
browser_web_vital_cls: ['p(95)<0.1'],
```
See `references/slo-design.md` for per-iteration tuning, the
`performance.mark` custom-Trend pattern, `iteration_completed` Rate,
breakpoint abort-on-fail thresholds, and loosening rules.
## 6. Build hybrid load tests
Per workflow, one file per test type. Each file has a protocol scenario
(drives load) plus a single browser VU (measures Web Vitals under load).
Breakpoint is protocol-only — a browser VU adds noise to the signal.
| Type | Executor | Defaults |
|------------|----------------------|------------------------------------------|
| smoke | constant-vus | 3 VUs × 1m |
| average | ramping-vus | 0→20→0 over 14m |
| stress | ramping-vus | 0→50→0 over 20m |
| spike | ramping-vus | 0→100→0 over 2m |
| soak | ramping-vus | 0→10→0 over 70m |
| breakpoint | ramping-arrival-rate | 5/s→500/s over 20m, abortOnFail |
Tune per workflow once you've seen smoke results. See
`references/test-types.md` for rationale and `references/hybrid-load-design.md`
for why one file per type and why duplication between files is acceptable.
## 7. Run locally with LG sidecar
```bash
./tools/run-with-monitor.sh tests/wN-<short-name>/smoke.js
```
Starts `lg-monitor.sh` in the background, runs k6, then prints a
summary verdict: **OK** (≥30% idle), **NOTE** (10–30%), or **WARNING**
(<10%). If WARNING, the laptop is the bottleneck — reduce VUs, switch
to cloud, or split across multiple LGs. See `references/lg-monitoring.md`.
## 8. Push to Grafana Cloud k6
For each test type assigned to cloud in the §1 runbook:
1. Confirm `k6 cloud login` works (the skill does not own auth setup).
2. Run smoke locally first to validate the script.
3. `k6 cloud run tests/wN-<short-name>/<type>.js`
4. Capture the run URL for the §10 report.
**Cost reminder:** browser VU-hours are billed 10× protocol VU-hours.
Soak and breakpoint are the most expensive. Check limits before long runs.
See `references/local-vs-cloud.md`.
## 9. Investigate the backend
Only if the user owns the backend and has Grafana access.
1. Discover datasources via `mcp-grafana` or `gcx datasources list`.
2. Ask the user for service label keys — do not guess.
3. Correlate the k6 run window with RED metrics, error logs, traces,
and profiles (Pyroscope — use explicit `from`/`to` for the run window).
4. Hand back specific evidence: timestamps, query strings, panel links.
See `references/grafana-investigation.md` for the full flow including
how to verify absence before reporting it.
## 10. Report back
Fill in the report template from `references/reporting.md`:
- **Summary** — workflows, test types, dates
- **SLOs** — pass/fail per threshold
- **Findings** — one paragraph per finding, ordered by severity, with specific evidence
- **Evidence** — k6 output paths, LG monitor CSVs, cloud run URLs, Grafana links
- **Suggested next steps**
Always be specific. "Latency is high" is not a finding. "GetPizza
p(95) hit 1.4s at iteration ~200; correlated with sustained 100% CPU
on the recommender service per Grafana panel link" is.
---
## Reference index
- [`references/workflow-elicitation.md`](references/workflow-elicitation.md) — verbatim question script for §1.
- [`references/recording-with-playwright.md`](references/recording-with-playwright.md) — HAR capture, third-party filter regex, hydration signals.
- [`references/functional-tests.md`](references/functional-tests.md) — 5-step Playwright→k6/browser conversion procedure.
- [`references/hybrid-load-design.md`](references/hybrid-load-design.md) — protocol + 1 browser VU rationale, duplication argument.
- [`references/slo-design.md`](references/slo-design.md) — full threshold rationale, async vs sync metric capture.
- [`references/test-types.md`](references/test-types.md) — definitions and defaults for all six test types.
- [`references/lg-monitoring.md`](references/lg-monitoring.md) — why the sidecar exists, how to read its output.
- [`references/local-vs-cloud.md`](references/local-vs-cloud.md) — framing, cost model, per-test-type tradeoffs.
- [`references/grafana-investigation.md`](references/grafana-investigation.md) — generic backend investigation flow.
- [`references/gotchas.md`](references/gotchas.md) — generic pitfalls.
- [`references/reporting.md`](references/reporting.md) — final report template.
README.md 3.1 KB
# Performance tests
Scaffolded by the `k6-perf-test-website` skill. End-to-end k6 perf
test suite using a hybrid protocol + browser approach.
## Layout
```
.
├── package.json # Playwright + har-to-k6
├── runbook.md # workflows, credentials, run plan
├── recordings/
│ ├── scripts/ # Playwright recorder per workflow (wN-<short-name>.js)
│ └── har/ # HAR captures, committed
├── tests/
│ ├── run-all.sh # functional-test driver (must exit 0)
│ ├── workflow.template/ # copy this per workflow
│ └── wN-<short-name>/ # one folder per workflow
│ ├── from-har.js # har-to-k6 output, committed for audit
│ ├── protocol.js # functional protocol test
│ ├── browser.js # functional browser test
│ ├── smoke.js # hybrid smoke
│ ├── average.js # hybrid avg load
│ ├── stress.js # hybrid stress
│ ├── spike.js # hybrid spike
│ ├── soak.js # hybrid soak
│ └── breakpoint.js # protocol-only ramping breakpoint
└── tools/
├── lg-monitor.sh # cross-platform LG sidecar
└── run-with-monitor.sh # k6 wrapper + summary
```
## Quick start
```bash
# 1. Install
npm install
npx playwright install chromium
# 2. Record each workflow (one-time per workflow)
node recordings/scripts/wN-<short-name>.js
npx har-to-k6 recordings/har/wN-<short-name>.har -o tests/wN-<short-name>/from-har.js
# ... then hand-clean from-har.js into protocol.js and browser.js
# (see skill reference: functional-tests.md)
# 3. Verify functional tests pass
./tests/run-all.sh
# 4. Run a load test with the LG monitor sidecar
./tools/run-with-monitor.sh tests/wN-<short-name>/smoke.js
./tools/run-with-monitor.sh tests/wN-<short-name>/average.js
./tools/run-with-monitor.sh tests/wN-<short-name>/stress.js
# ... etc per the run plan in runbook.md
# 5. (If cloud) push to Grafana Cloud k6
k6 cloud run tests/wN-<short-name>/stress.js
```
## Run plan
See `runbook.md` for:
- Per-workflow definitions and credentials.
- SLOs.
- Which test types run locally vs in Grafana Cloud k6.
- Constraints (IP allow-lists, rate limiters, etc.).
## Where output goes
- Functional test logs: `${TMPDIR}/k6-run-all/`
- Load test logs + LG monitor CSVs: `/tmp/perf-lg-monitor/`
- k6 cloud runs: Grafana Cloud k6 web UI (links in run-all.sh
output).
## Adding a workflow
```bash
# Copy template
cp -R tests/workflow.template tests/wN-<short-name>
cp recordings/scripts/recorder.template.js recordings/scripts/wN-<short-name>.js
# Replace <WORKFLOW_PLACEHOLDER> markers in each copied file
grep -rl '<WORKFLOW_PLACEHOLDER>' tests/wN-<short-name> recordings/scripts/wN-<short-name>.js \
| xargs sed -i.bak "s/<WORKFLOW_PLACEHOLDER>/wN-<short-name>/g" \
&& find tests/wN-<short-name> recordings/scripts -name '*.bak' -delete
# Fill in the per-workflow body
$EDITOR recordings/scripts/wN-<short-name>.js
node recordings/scripts/wN-<short-name>.js
npx har-to-k6 recordings/har/wN-<short-name>.har -o tests/wN-<short-name>/from-har.js
# hand-clean from-har.js → protocol.js + browser.js
./tests/run-all.sh
```
package.json 0.4 KB
{
"name": "perf-tests",
"private": true,
"description": "k6 performance tests scaffolded by the k6-perf-test-website skill",
"scripts": {
"//": "Add `record:wN-<short-name>` entries per workflow as you scaffold them, e.g.",
"//record:wN-<short-name>": "node recordings/scripts/wN-<short-name>.js"
},
"devDependencies": {
"har-to-k6": "0.14.17",
"playwright": "1.64.1"
}
}
README.md 2.4 KB
# Recordings: Playwright source-of-truth → HAR → k6 scripts
Source of truth for `tests/`. Each workflow has one Playwright
recorder in `scripts/` and one HAR in `har/`.
## Pipeline
```
recordings/scripts/wN-<short-name>.js (Playwright -- source of truth)
├── node recordings/scripts/wN-<short-name>.js ⟶ recordings/har/wN-<short-name>.har
│ └── npx har-to-k6 wN-<short-name>.har ⟶ tests/wN-<short-name>/from-har.js (raw)
│ └── hand cleanup ⟶ tests/wN-<short-name>/protocol.js (final)
└── 5-step manual conversion ⟶ tests/wN-<short-name>/browser.js (final)
```
See the `k6-perf-test-website` skill references:
- `recording-with-playwright.md` for the recorder pattern
- `functional-tests.md` for the 5-step Playwright → k6/browser
conversion
## Re-record when
- The app's bundled hash-named assets change (the protocol test
will fail with a 404 — re-record to refresh the asset paths).
- The API or workflow changes the recorded request sequence.
- You want a fresh HAR for analysis (before/after a backend
change).
```bash
# 1. Re-run the recorder
node recordings/scripts/wN-<short-name>.js
# 2. Regenerate raw k6
npx har-to-k6 recordings/har/wN-<short-name>.har -o tests/wN-<short-name>/from-har.js
# 3. By hand: bring new asset paths / request sequences into
# tests/wN-<short-name>/protocol.js and tests/wN-<short-name>/browser.js.
# 4. Verify
./tests/run-all.sh
```
## Why HARs are committed
- Reproducibility — anyone reading the repo can see what was
captured.
- Diff-ability — when the app is rebuilt, `git diff` shows what
changed at the protocol layer.
- Small enough — typical HAR is 300 KB - 2 MB.
## Recorder template notes
- All recorders use `recordHar.urlFilter` to keep third-party
collectors (RUM, error reporters, analytics, ads, social, …)
out of the HAR. **Critical** — see skill gotchas.
- All recorders have a belt-and-braces `context.route` filter
that aborts third-party requests at the network layer too.
- All recorders are headless by default
(`chromium.launch({ headless: true })`).
- All recorders use a **real Chrome** UA, not the
`HeadlessChrome` default. The default UA triggers bot-blocking
on many production sites.
- All recorders are idempotent — re-running overwrites the HAR.
- `BASE_URL` can be overridden via env. The `urlFilter` regex
must accept any host you use (default: target host + localhost).
recorder.template.js 4.9 KB
// Playwright recorder template -- one per workflow.
//
// Copy this file to recordings/scripts/wN-<short-name>.js, then:
// 1. Replace <WORKFLOW_PLACEHOLDER> with the workflow name (e.g. w1-checkout).
// 2. Update BASE_URL and the `isAllowedHost` allow-list to match the target.
// 3. Update the `urlFilter` regex to match the same hosts.
// 4. Replace the "USER ACTION SEQUENCE" block with the actual workflow steps.
// 5. Run: `node recordings/scripts/wN-<short-name>.js`
//
// Produces:
// recordings/har/<WORKFLOW_PLACEHOLDER>.har
//
// See the k6-perf-test-website skill's recording-with-playwright.md for design
// notes (third-party filter rationale, hydration sentinels, UA selection).
const path = require('path');
const { chromium } = require('playwright');
// --- Configuration --------------------------------------------------------------
const BASE_URL = process.env.BASE_URL || 'https://target-host.example';
const HAR_PATH = path.resolve(__dirname, '..', 'har', '<WORKFLOW_PLACEHOLDER>.har');
// Real Chrome UA. The default headless UA contains "HeadlessChrome" which
// triggers bot-blocking on many production sites. Set this to a recent Chrome
// version's UA string.
const USER_AGENT =
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36';
// Hosts we want to keep in the HAR. Everything else is aborted at the network
// layer AND filtered out of the HAR. This excludes third-party RUM, error
// reporters, analytics, ads, etc.
function isAllowedHost(url) {
try {
const u = new URL(url);
return u.hostname === 'target-host.example' || u.hostname === 'localhost';
} catch {
return false;
}
}
// HAR write-time filter -- entries whose URL does not match this regex are
// silently dropped. Must allow-list the same hosts as isAllowedHost.
const HAR_URL_FILTER = /^https?:\/\/(target-host\.example|localhost)(:\d+)?\//;
// --- Recorder body --------------------------------------------------------------
(async () => {
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({
userAgent: USER_AGENT,
recordHar: {
path: HAR_PATH,
mode: 'full',
content: 'embed',
urlFilter: HAR_URL_FILTER,
},
});
// Belt-and-braces: also abort third-party requests at the network layer so
// they don't send traffic to third parties during recording (politeness +
// avoid status:-1 entries in the HAR).
await context.route('**', (route) => {
if (isAllowedHost(route.request().url())) return route.continue();
return route.abort();
});
const page = await context.newPage();
// ============================================================================
// USER ACTION SEQUENCE -- replace this whole block with the actual workflow.
// ============================================================================
//
// Pattern:
// 1. page.goto(BASE_URL) + waitFor a post-hydration sentinel (an interactive
// element that only exists after the SPA has booted).
// 2. page.click / page.fill / etc. for each user action.
// 3. Promise.all([page.waitForResponse(...), page.click(...)]) when an action
// triggers a critical API call -- ensures the HAR captures the response.
// 4. waitFor the result locator after each significant action.
// 5. waitForTimeout(500) at the end so trailing in-flight requests land in
// the HAR before context.close().
// Step 1: open homepage. Wait for a post-hydration sentinel (an element that
// only exists after JS has hydrated -- typically an interactive button/link
// rendered by the framework, not the SSR).
await page.goto(BASE_URL, { waitUntil: 'load' });
// EXAMPLE -- replace with the actual sentinel for the workflow:
// const primaryAction = page.locator('button[name="primary-action"]');
// await primaryAction.waitFor({ state: 'visible' });
// Step 2..N: the user actions.
//
// EXAMPLE:
// await Promise.all([
// page.waitForResponse(
// (r) => r.url().includes('/api/action') && r.request().method() === 'POST',
// ),
// primaryAction.click(),
// ]);
// await page.locator('#result').waitFor({ state: 'visible' });
// Final settle so any trailing in-flight requests (CSS background-image
// fetches kicked off by the result render, etc.) land in the HAR.
await page.waitForTimeout(500);
// ============================================================================
// END USER ACTION SEQUENCE
// ============================================================================
await context.close();
await browser.close();
// Playwright writes HAR on context.close(); print confirmation.
// eslint-disable-next-line no-console
console.log(`HAR written: ${HAR_PATH}`);
})().catch((err) => {
// eslint-disable-next-line no-console
console.error(err);
process.exit(1);
});
run-all.sh 2.8 KB
#!/usr/bin/env bash
# Runs all functional k6 scripts (protocol + browser per workflow) and reports
# a summary. Exit code 0 if every script passed; non-zero (= number of failures)
# otherwise.
#
# Usage:
# ./tests/run-all.sh
# BASE_URL=http://localhost:3333 ./tests/run-all.sh
#
# Per-test logs at: ${TMPDIR:-/tmp}/k6-run-all/<workflow>-<kind>.log
#
# Auto-discovers workflows by listing tests/w*-*/ folders and matching the
# protocol.js + browser.js convention. Skips any folder that doesn't have both.
set -u
LOGDIR="${TMPDIR:-/tmp}/k6-run-all"
mkdir -p "$LOGDIR"
# Portable elapsed-time helper. macOS `date` has no %N (nanoseconds) and still
# exits 0, so the old `date +%s%N` never hit its fallback and produced bogus
# sub-second math there (every run printed 0.0s). Prefer python3 (already a
# dependency of run-with-monitor.sh) for fractional seconds; fall back to
# whole-second `date +%s` when python3 is absent.
if command -v python3 >/dev/null 2>&1; then
now_s() { python3 -c 'import time; print(time.time())'; }
else
now_s() { date +%s; }
fi
# Find all workflow folders matching tests/wN-<short-name>/
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WORKFLOWS=()
for d in "$SCRIPT_DIR"/w*-*/; do
[ -d "$d" ] || continue
[ -f "$d/protocol.js" ] || continue
[ -f "$d/browser.js" ] || continue
WORKFLOWS+=("$(basename "$d")")
done
if [ "${#WORKFLOWS[@]}" -eq 0 ]; then
echo "No workflow folders found in $SCRIPT_DIR (expected tests/wN-<short-name>/protocol.js + browser.js)." >&2
exit 0
fi
# Build the test list: protocol then browser per workflow.
declare -a RESULTS
FAIL_COUNT=0
for wf in "${WORKFLOWS[@]}"; do
for kind in protocol browser; do
label="tests/$wf/$kind.js"
script="$SCRIPT_DIR/$wf/$kind.js" # absolute: works regardless of CWD
log="$LOGDIR/$wf-$kind.log"
printf '%-20s %-50s ' "$wf $kind" "$label"
start_s=$(now_s)
if [ "$kind" = "browser" ]; then
K6_BROWSER_HEADLESS=true k6 run "$script" >"$log" 2>&1
rc=$?
else
k6 run "$script" >"$log" 2>&1
rc=$?
fi
end_s=$(now_s)
dur_s=$(awk "BEGIN { printf \"%.1f\", $end_s - $start_s }")
if [ $rc -eq 0 ]; then
printf 'OK (%ss)\n' "$dur_s"
RESULTS+=("OK|$wf $kind|${dur_s}s")
else
printf 'FAIL (%ss) log: %s\n' "$dur_s" "$log"
RESULTS+=("FAIL|$wf $kind|${dur_s}s|$log")
FAIL_COUNT=$((FAIL_COUNT + 1))
fi
done
done
echo
echo "--- summary ---"
for r in "${RESULTS[@]}"; do
IFS='|' read -r status label dur extra <<<"$r"
if [ "$status" = "OK" ]; then
printf ' OK %-30s %s\n' "$label" "$dur"
else
printf ' FAIL %-30s %s (see %s)\n' "$label" "$dur" "$extra"
fi
done
echo
TOTAL=$(( ${#WORKFLOWS[@]} * 2 ))
if [ $FAIL_COUNT -eq 0 ]; then
echo "All $TOTAL functional tests passed."
else
echo "$FAIL_COUNT of $TOTAL failed."
fi
exit $FAIL_COUNT
average.js 4.0 KB
// Hybrid k6 AVERAGE-LOAD test for workflow <WORKFLOW_PLACEHOLDER>.
//
// AVERAGE: expected production load. Tune target VUs to match the customer's
// typical concurrent user count from runbook.md.
//
// Scenarios:
// - protocol : ramping-vus 0 → 20 → 0 over 14m
// - browser : 1 constant VU × 14m (Web Vitals canary)
//
// Iteration body is identical to smoke.js -- duplication is intentional per the
// k6-perf-test-website skill's hybrid-load-design.md. Update both files in lock-step
// when the workflow body changes.
//
// Run:
// ./tools/run-with-monitor.sh tests/<WORKFLOW_PLACEHOLDER>/average.js
// k6 cloud run tests/<WORKFLOW_PLACEHOLDER>/average.js
import http from 'k6/http';
import { check, group, sleep } from 'k6';
import { browser } from 'k6/browser';
import { Rate, Trend } from 'k6/metrics';
// asyncCheck (not bare check from k6) is required for async browser locators — see references/gotchas.md
import { check as asyncCheck } from 'https://jslib.k6.io/k6-utils/1.5.0/index.js';
const timeToResult = new Trend('time_to_result', true);
const iterationCompleted = new Rate('iteration_completed');
const BASE_URL = __ENV.BASE_URL || 'https://target-host.example';
const USER_AGENT =
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36';
const BACKEND_THRESHOLDS = {
http_req_failed: ['rate<0.01'],
http_req_duration: ['p(95)<500'],
checks: ['rate>0.99'],
// 'http_req_duration{name:GetConfig}': ['p(95)<300'],
// 'http_req_duration{name:GetAction}': ['p(95)<1000', 'p(99)<1500'],
};
const BROWSER_THRESHOLDS = {
browser_web_vital_lcp: ['p(95)<2500'],
browser_web_vital_inp: ['p(95)<200'],
browser_web_vital_cls: ['p(95)<0.1'],
'iteration_duration{scenario:browser}': ['p(95)<10000'],
time_to_result: ['p(95)<3000'],
'iteration_completed{scenario:browser}': ['rate>0.99'],
};
export const options = {
userAgent: USER_AGENT,
scenarios: {
protocol: {
executor: 'ramping-vus',
exec: 'protocolIteration',
startVUs: 0,
stages: [
{ duration: '2m', target: 20 }, // ramp up
{ duration: '10m', target: 20 }, // hold at expected load
{ duration: '2m', target: 0 }, // ramp down
],
},
browser: {
executor: 'constant-vus',
exec: 'browserIteration',
vus: 1,
duration: '14m',
options: { browser: { type: 'chromium' } },
},
},
thresholds: { ...BACKEND_THRESHOLDS, ...BROWSER_THRESHOLDS },
};
// --- Protocol iteration ---------------------------------------------------------
// Body identical to smoke.js -- duplicate so each file reads cleanly on its own
// during incident review. See hybrid-load-design.md for the rationale.
export function protocolIteration() {
group('<WORKFLOW_PLACEHOLDER>', function () {
let res = http.get(`${BASE_URL}/`, {
headers: {
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
},
});
check(res, { 'homepage 200': (r) => r.status === 200 });
// ... fill in the rest of the protocol body from protocol.js ...
// Use check() instead of expect(), and add tags: { name: 'EndpointName' } per
// request. See smoke.js for the full template.
sleep(Math.random() * 3 + 1);
// The user action (tagged)
});
}
// --- Browser iteration ----------------------------------------------------------
// Body identical to smoke.js.
export async function browserIteration() {
const page = await browser.newPage();
let success = true;
try {
await page.goto(BASE_URL, { waitUntil: 'load' });
// ... fill in the browser iteration from browser.js, with performance.mark /
// measure to record the time_to_result Trend. See smoke.js for the full
// template.
} catch (e) {
success = false;
console.error(`<WORKFLOW_PLACEHOLDER> browser iteration failed: ${(e && e.message) || e}`);
throw e;
} finally {
iterationCompleted.add(success);
await page.close();
}
}
breakpoint.js 3.9 KB
// k6 BREAKPOINT test for workflow <WORKFLOW_PLACEHOLDER>.
//
// BREAKPOINT: ramping arrival rate, find the ceiling. PROTOCOL-ONLY -- a single
// browser VU mid-test adds noise to the signal we're hunting. Document the
// abort point (final iteration rate or arrival rate) as the breakpoint.
//
// `ramping-arrival-rate` (not VUs) because the cliff is in requests-per-second,
// not concurrent users. VU-based ramps are bounded by iteration duration; if
// iterations slow down, VUs back off and you never reach the cliff. Arrival
// rate injects requests on a fixed schedule.
//
// `abortOnFail` thresholds stop the run when SLOs break. `delayAbortEval` 30s
// avoids tripping on instantaneous fluctuations.
//
// COST WARNING (Grafana Cloud k6): breakpoint runs can use 30-100+ VUh.
// Confirm with the customer per runbook.md before pushing.
//
// Iteration body mirrors smoke.js's protocolIteration (no browser body here)
// with ONE deliberate difference: NO think-time sleep(). Breakpoint hunts raw
// requests-per-second, and with `ramping-arrival-rate` every started iteration
// holds a VU until it finishes. A 1-4s think-time sleep makes each iteration
// last ~2.5s, so each VU can only serve ~0.4 iters/s. k6 then hits the maxVUs
// cap, logs "Insufficient VUs", and drops iterations -- the arrival rate
// plateaus from VU exhaustion long before the backend's real ceiling, which is
// easy to misread as "the server broke". Keep think-time out of breakpoint;
// it belongs in average/stress/soak where it models real user pacing.
//
// Run:
// ./tools/run-with-monitor.sh tests/<WORKFLOW_PLACEHOLDER>/breakpoint.js
// k6 cloud run tests/<WORKFLOW_PLACEHOLDER>/breakpoint.js # confirm budget
import http from 'k6/http';
import { check, group } from 'k6';
const BASE_URL = __ENV.BASE_URL || 'https://target-host.example';
const USER_AGENT =
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36';
export const options = {
userAgent: USER_AGENT,
scenarios: {
protocol: {
executor: 'ramping-arrival-rate',
exec: 'protocolIteration',
startRate: 5,
timeUnit: '1s',
preAllocatedVUs: 50,
// maxVUs must exceed target_rate × expected_iteration_seconds, or k6 runs
// out of VUs and the arrival rate plateaus before the real ceiling. With
// no think-time and a ~0.2s iteration, 500/s needs ~100 VUs, so 500 is
// ample headroom. If your iteration is slower, raise this accordingly.
maxVUs: 500,
stages: [
{ duration: '20m', target: 500 }, // ramp arrival rate 5/s → 500/s
],
},
// NO browser scenario -- breakpoint hunts protocol throughput. Adding a
// browser VU adds noise without contributing signal.
},
thresholds: {
// abortOnFail: stop the run when SLOs break -- that's the breakpoint.
http_req_failed: [
{ threshold: 'rate<0.05', abortOnFail: true, delayAbortEval: '30s' },
],
http_req_duration: [
{ threshold: 'p(95)<2000', abortOnFail: true, delayAbortEval: '30s' },
],
checks: ['rate>0.95'],
},
};
// --- Protocol iteration ---------------------------------------------------------
// Mirrors smoke.js's protocolIteration MINUS the think-time sleep() (see the
// header note for why). See smoke.js for the full template and
// hybrid-load-design.md for why duplication is preferred over a shared helper.
export function protocolIteration() {
group('<WORKFLOW_PLACEHOLDER>', function () {
let res = http.get(`${BASE_URL}/`, {
headers: {
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
},
});
check(res, { 'homepage 200': (r) => r.status === 200 });
// ... fill in from protocol.js with check() + tags. See smoke.js template.
// Do NOT add a think-time sleep() here -- it caps achievable arrival rate
// via VU exhaustion. The user action (tagged) goes here, back-to-back.
});
}
browser.js 3.3 KB
// k6-browser functional test for workflow <WORKFLOW_PLACEHOLDER>.
//
// Hand-converted from recordings/scripts/<WORKFLOW_PLACEHOLDER>.js per the
// k6-perf-test-website skill's 5-step procedure in functional-tests.md. The
// page-interaction body is structurally identical to the Playwright recorder;
// only the framework scaffolding differs.
//
// Run:
// k6 run tests/<WORKFLOW_PLACEHOLDER>/browser.js
// K6_BROWSER_HEADLESS=true k6 run tests/<WORKFLOW_PLACEHOLDER>/browser.js
import { browser } from 'k6/browser';
import { expect } from 'https://jslib.k6.io/k6-testing/0.5.0/index.js';
const BASE_URL = __ENV.BASE_URL || 'https://target-host.example';
export const options = {
scenarios: {
'<WORKFLOW_PLACEHOLDER>': {
executor: 'shared-iterations',
vus: 1,
iterations: 1,
options: { browser: { type: 'chromium' } },
},
},
};
export default async function () {
// browser.newPage() is the default; iterations don't share cookies. If you
// need a fresh browser context per iteration (e.g. to ensure logged-out
// start state), see references/functional-tests.md for newContext().
const page = await browser.newPage();
try {
// Step 1: open homepage. Wait for a post-hydration sentinel (an interactive
// element that only exists after JS has hydrated). See the k6-perf-test-website
// skill's recording-with-playwright.md.
await page.goto(BASE_URL, { waitUntil: 'load' });
// EXAMPLE -- the structural pattern is:
// 1. Locate + wait for the post-hydration sentinel.
// 2. Use `expect(...).toBeVisible()` to fail loudly if the sentinel
// doesn't appear.
// 3. For timed actions, use `performance.mark()` / `performance.measure()`
// inside `page.evaluate()` and a custom Trend. Do NOT use `group()`
// around `await` -- in k6/browser's async runtime, `group()` does not
// wrap awaited code correctly and `group_duration` will not capture
// what you expect. See references/slo-design.md (the "async vs sync"
// section).
// 4. Use Promise.all([waitForResponse, click]) so the response is captured
// before the next assertion.
// 5. Assert the result element appears with expect(...).toBeVisible().
//
// Replace the body below with the actual workflow:
// const primaryAction = page.locator('button[name="primary-action"]');
// await primaryAction.waitFor({ state: 'visible' });
// await expect(primaryAction).toBeVisible();
//
// // Mark the start of the timed action (NOT inside a group()).
// await page.evaluate(() => performance.mark('action-start'));
//
// await Promise.all([
// page.waitForResponse(
// (r) => r.url().includes('/api/action') && r.request().method() === 'POST',
// ),
// primaryAction.click(),
// ]);
//
// const result = page.locator('#result');
// await result.waitFor({ state: 'visible' });
// await expect(result).toBeVisible();
//
// // Read the duration back into a custom Trend in smoke.js / average.js etc.
// // (In the bare functional browser.js you can skip this; the Trend lives in
// // the load-test scripts where measurement matters.)
} finally {
// Always close the page in finally -- resource leak otherwise.
await page.close();
}
}
from-har.js 1.5 KB
// from-har.js -- raw har-to-k6 output, committed for audit.
//
// This file is REGENERATED by:
// npx har-to-k6 recordings/har/<WORKFLOW_PLACEHOLDER>.har -o tests/<WORKFLOW_PLACEHOLDER>/from-har.js
//
// You should NOT edit this file by hand. Instead, hand-clean it into
// `protocol.js` per the k6-perf-test-website skill's functional-tests.md
// procedure:
//
// 1. Move per-request User-Agent / sec-ch-ua-* to options.userAgent
// 2. Rename the opaque group
// 3. Parameterise BASE_URL via __ENV
// 4. Replace recorded credentials with test credentials / __ENV
// 5. Drop the auto-inserted sleep(1)
// 6. Add expect() on every load-bearing response
//
// Then commit BOTH the regenerated from-har.js AND the cleaned protocol.js so
// the audit trail is preserved.
//
// THIS FILE IS A PLACEHOLDER. Replace it by regenerating from your HAR.
import http from 'k6/http';
import { sleep, group } from 'k6';
export const options = {
iterations: 1,
};
export default function () {
group('page_0', function () {
// The body of this function will be filled in by `npx har-to-k6`. It will
// contain one http.* call per request in the HAR, plus auto-inserted
// headers and a trailing sleep(1).
//
// Run the recorder + har-to-k6 to populate this:
//
// node recordings/scripts/<WORKFLOW_PLACEHOLDER>.js
// npx har-to-k6 recordings/har/<WORKFLOW_PLACEHOLDER>.har \
// -o tests/<WORKFLOW_PLACEHOLDER>/from-har.js
sleep(1);
});
}
protocol.js 3.9 KB
// k6 protocol-level functional test for workflow <WORKFLOW_PLACEHOLDER>.
//
// Hand-cleaned from from-har.js per the k6-perf-test-website skill's
// functional-tests.md procedure.
//
// Run:
// k6 run tests/<WORKFLOW_PLACEHOLDER>/protocol.js
// BASE_URL=http://localhost:3333 k6 run tests/<WORKFLOW_PLACEHOLDER>/protocol.js
import http from 'k6/http';
import { group } from 'k6';
import { expect } from 'https://jslib.k6.io/k6-testing/0.5.0/index.js';
// --- Configuration --------------------------------------------------------------
const BASE_URL = __ENV.BASE_URL || 'https://target-host.example';
// Real Chrome UA -- headless UAs trigger bot-blocking on production sites.
const USER_AGENT =
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36';
// Auth -- if your workflow needs a token, set TEST_TOKEN env or hard-code a
// well-known test value here. Do not commit production credentials.
// const AUTH_TOKEN = __ENV.TEST_TOKEN || 'replace-with-test-token';
export const options = {
vus: 1,
iterations: 1,
userAgent: USER_AGENT,
};
// --- Iteration body -------------------------------------------------------------
export default function () {
group('<WORKFLOW_PLACEHOLDER>', function () {
// ============================================================================
// PROTOCOL ITERATION -- replace this block with the cleaned-up sequence from
// from-har.js. Pattern:
//
// 1. Homepage shell (HTML) -- expect 200.
// 2. Static assets (CSS/JS) -- expect 200 on each. A 404 on a hash-named
// bundle is the expected failure mode when the app is rebuilt; the
// test must fail loudly so the recorder is re-run.
// 3. onMount API fan-out -- expect 200 + body-shape assertions on the
// load-bearing responses.
// 4. The user action(s) -- expect 200 + body-shape assertions on the
// response that carries the workflow's payload.
// 5. Trailing fetches (CSS background-image, etc.).
//
// Every http.* call gets at least an expect() on res.status.
// The response that carries the workflow's payload gets additional
// body-shape assertions.
// ============================================================================
// EXAMPLE -- replace with the actual workflow:
// 1. Homepage shell
let res = http.get(`${BASE_URL}/`, {
headers: {
Accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
'Upgrade-Insecure-Requests': '1',
},
});
expect(res.status).toBe(200);
// 2. Static assets -- list every asset captured in the HAR, with status
// assertion on each so a hash-rename failure is obvious.
// const assets = [
// ['css', '/_app/immutable/assets/0.<hash>.css'],
// ['js', '/_app/immutable/entry/start.<hash>.js'],
// // ...
// ];
// for (const [kind, path] of assets) {
// const r = http.get(`${BASE_URL}${path}`, {
// headers: {
// Accept: kind === 'css' ? 'text/css,*/*;q=0.1' : '*/*',
// Referer: `${BASE_URL}/`,
// },
// });
// expect(r.status, `asset ${path}`).toBe(200);
// }
// 3. onMount API fan-out
// res = http.get(`${BASE_URL}/api/config`, { headers: { Referer: `${BASE_URL}/` } });
// expect(res.status).toBe(200);
// 4. The user action
// const payload = JSON.stringify({ /* request body */ });
// res = http.post(`${BASE_URL}/api/action`, payload, {
// headers: {
// Accept: '*/*',
// 'Content-Type': 'application/json',
// Origin: BASE_URL,
// Referer: `${BASE_URL}/`,
// },
// });
// expect(res.status).toBe(200);
// const result = res.json('result');
// expect(result).not.toBeNull();
// 5. Trailing fetches (if any in the HAR)
});
}
smoke.js 8.1 KB
// Hybrid k6 SMOKE test for workflow <WORKFLOW_PLACEHOLDER>.
//
// SMOKE: low VUs, short duration, sanity check. Always run before any other
// test type. If smoke fails, fix the script before scaling.
//
// Scenarios:
// - protocol : 3 constant VUs × 1m, drives the bulk of the load
// - browser : 1 constant VU × 1m, measures Web Vitals under load
//
// Run:
// k6 run tests/<WORKFLOW_PLACEHOLDER>/smoke.js
// ./tools/run-with-monitor.sh tests/<WORKFLOW_PLACEHOLDER>/smoke.js
// BASE_URL=http://localhost:3333 k6 run tests/<WORKFLOW_PLACEHOLDER>/smoke.js
// k6 cloud run tests/<WORKFLOW_PLACEHOLDER>/smoke.js
import http from 'k6/http';
import { check, group, sleep } from 'k6';
import { browser } from 'k6/browser';
import { Rate, Trend } from 'k6/metrics';
// asyncCheck (not bare check from k6) is required for async browser locators — see references/gotchas.md
import { check as asyncCheck } from 'https://jslib.k6.io/k6-utils/1.5.0/index.js';
// --- Custom metrics -------------------------------------------------------------
// Time from "user clicks the action button" to "result is visible". Web Vitals
// measure initial render; this Trend captures the slow action specifically.
// Implemented via performance.mark/measure (group() does NOT work in async code).
const timeToResult = new Trend('time_to_result', true);
// Browser iterations can throw on locator timeouts. A thrown iteration is
// "interrupted" in k6's summary, not "failed". This Rate makes failures visible.
const iterationCompleted = new Rate('iteration_completed');
// --- Configuration --------------------------------------------------------------
const BASE_URL = __ENV.BASE_URL || 'https://target-host.example';
const USER_AGENT =
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36';
// --- Thresholds -----------------------------------------------------------------
const BACKEND_THRESHOLDS = {
// < 1% failures. NOTE: k6 counts any 4xx/5xx as a "failed" request by default.
// If your workflow intentionally produces a non-2xx (e.g. anonymous user
// returns 401, "not found" returns 404), this threshold will blow because
// those expected failures count against it. See references/gotchas.md
// ("Workflows with expected 4xx/5xx responses") for two correct fixes:
// (A) http.setResponseCallback(http.expectedStatuses({min:200,max:299}, 401))
// at the top of the module, or (B) tag the expected-failure request and
// threshold its tag separately. Do NOT just relax this number — that
// hides real failures elsewhere.
http_req_failed: ['rate<0.01'],
http_req_duration: ['p(95)<500'], // global p95 < 500ms
checks: ['rate>0.99'],
// EXAMPLE per-endpoint thresholds (add a tag to each http.* call in the
// protocolIteration body via `tags: { name: 'GetThings' }`, then threshold):
// 'http_req_duration{name:GetConfig}': ['p(95)<300'],
// 'http_req_duration{name:GetAction}': ['p(95)<1000', 'p(99)<1500'],
};
const BROWSER_THRESHOLDS = {
// Web Vitals (Google "good" thresholds; loosen with documentation only)
browser_web_vital_lcp: ['p(95)<2500'],
browser_web_vital_inp: ['p(95)<200'],
browser_web_vital_cls: ['p(95)<0.1'],
// User-perceived workflow time
'iteration_duration{scenario:browser}': ['p(95)<10000'], // 10s end-to-end
// Custom action time (for the slow user action specifically).
// WARNING: this threshold PASSES VACUOUSLY until you wire up timeToResult.add()
// in browserIteration (it's commented out in the example body below). k6 treats
// a metric with zero samples as non-violating, so an unfilled time_to_result
// shows green while measuring nothing -- false comfort. Either wire up the
// performance.mark/measure block or delete this threshold; don't ship it empty.
time_to_result: ['p(95)<3000'], // click → result: 3s
// Browser iteration health
'iteration_completed{scenario:browser}': ['rate>0.99'], // <1% throws
};
// --- Options --------------------------------------------------------------------
export const options = {
userAgent: USER_AGENT,
scenarios: {
protocol: {
executor: 'constant-vus',
exec: 'protocolIteration',
vus: 3,
duration: '1m',
},
browser: {
executor: 'constant-vus',
exec: 'browserIteration',
vus: 1,
duration: '1m',
options: { browser: { type: 'chromium' } },
},
},
thresholds: { ...BACKEND_THRESHOLDS, ...BROWSER_THRESHOLDS },
};
// --- Protocol iteration ---------------------------------------------------------
export function protocolIteration() {
group('<WORKFLOW_PLACEHOLDER>', function () {
// ============================================================================
// PROTOCOL ITERATION BODY -- structurally identical to protocol.js but with
// check() (not expect()), per-endpoint tags, and randomised sleep between
// user actions.
//
// Pattern:
// 1. Homepage shell
// 2. Static assets
// 3. onMount API fan-out (tag each endpoint)
// 4. sleep(random think time) -- simulate user reading the page
// 5. The user action (tag it)
// 6. Trailing fetches
//
// No trailing sleep -- closed-model executors pace via VU count.
// ============================================================================
// EXAMPLE -- replace with the actual workflow body:
let res = http.get(`${BASE_URL}/`, {
headers: {
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
},
});
check(res, { 'homepage 200': (r) => r.status === 200 });
// res = http.get(`${BASE_URL}/api/config`, {
// headers: { Referer: `${BASE_URL}/` },
// tags: { name: 'GetConfig' },
// });
// check(res, { 'config 200': (r) => r.status === 200 });
// User reads the page, decides to act.
sleep(Math.random() * 3 + 1);
// The action -- tag it for per-endpoint thresholding.
// res = http.post(`${BASE_URL}/api/action`, JSON.stringify({ /* payload */ }), {
// headers: { 'Content-Type': 'application/json', Referer: `${BASE_URL}/` },
// tags: { name: 'GetAction' },
// });
// check(res, {
// 'action 200': (r) => r.status === 200,
// 'action has result': (r) => r.json('result') != null,
// });
});
}
// --- Browser iteration ----------------------------------------------------------
export async function browserIteration() {
const page = await browser.newPage();
let success = true;
try {
// Open homepage, wait for hydration sentinel.
await page.goto(BASE_URL, { waitUntil: 'load' });
// EXAMPLE -- replace with the actual workflow:
// const primaryAction = page.locator('button[name="primary-action"]');
// await primaryAction.waitFor({ state: 'visible' });
// // Think time before clicking.
// await page.waitForTimeout(1000 + Math.random() * 3000);
// // Mark the start of the slow action in the Performance Timeline.
// await page.evaluate(() => performance.mark('action-start'));
// await Promise.all([
// page.waitForResponse(
// (r) => r.url().includes('/api/action') && r.request().method() === 'POST',
// ),
// primaryAction.click(),
// ]);
// const result = page.locator('#result');
// await result.waitFor({ state: 'visible' });
// // Record the time-to-result.
// const ms = await page.evaluate(() => {
// performance.mark('action-end');
// return performance.measure('time-to-result', 'action-start', 'action-end').duration;
// });
// timeToResult.add(ms);
// // Async check (records in `checks` rate, doesn't abort).
// await asyncCheck(result, {
// 'result visible': async (lo) => (await lo.isVisible()) === true,
// });
} catch (e) {
success = false;
console.error(`<WORKFLOW_PLACEHOLDER> browser iteration failed: ${(e && e.message) || e}`);
throw e; // re-throw so k6 also marks the iteration interrupted
} finally {
iterationCompleted.add(success);
await page.close();
}
}
soak.js 3.9 KB
// Hybrid k6 SOAK test for workflow <WORKFLOW_PLACEHOLDER>.
//
// SOAK: sustained moderate load over a long window. Goal is to find memory
// leaks, connection drift, scheduled-job interference, cache eviction patterns.
//
// Scenarios:
// - protocol : ramping-vus 0 → 10 → 0 over 70m (5m ramp / 60m hold / 5m drop)
// - browser : 1 constant VU × 70m
//
// COST WARNING (Grafana Cloud k6): a 70-minute browser VU costs ~12 VUh
// (browser VUs are billed 10×). This is one of the most budget-hostile test
// types in cloud. Confirm with the customer per runbook.md before pushing.
//
// CLIENT-SIDE NOTE: long browser soaks may show k6 RSS climbing on the LG.
// This is NOT necessarily a server-side leak -- k6 accumulates every metric
// sample for the run summary. Verify against backend memory metrics before
// reporting a leak.
//
// Iteration body is identical to smoke.js.
//
// Run:
// ./tools/run-with-monitor.sh tests/<WORKFLOW_PLACEHOLDER>/soak.js
// k6 cloud run tests/<WORKFLOW_PLACEHOLDER>/soak.js # only with customer confirmation
import http from 'k6/http';
import { check, group, sleep } from 'k6';
import { browser } from 'k6/browser';
import { Rate, Trend } from 'k6/metrics';
// asyncCheck (not bare check from k6) is required for async browser locators — see references/gotchas.md
import { check as asyncCheck } from 'https://jslib.k6.io/k6-utils/1.5.0/index.js';
const timeToResult = new Trend('time_to_result', true);
const iterationCompleted = new Rate('iteration_completed');
const BASE_URL = __ENV.BASE_URL || 'https://target-host.example';
const USER_AGENT =
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36';
const BACKEND_THRESHOLDS = {
http_req_failed: ['rate<0.01'],
http_req_duration: ['p(95)<500'],
checks: ['rate>0.99'],
};
const BROWSER_THRESHOLDS = {
browser_web_vital_lcp: ['p(95)<2500'],
browser_web_vital_inp: ['p(95)<200'],
browser_web_vital_cls: ['p(95)<0.1'],
'iteration_duration{scenario:browser}': ['p(95)<10000'],
time_to_result: ['p(95)<3000'],
'iteration_completed{scenario:browser}': ['rate>0.99'],
};
export const options = {
userAgent: USER_AGENT,
scenarios: {
protocol: {
executor: 'ramping-vus',
exec: 'protocolIteration',
startVUs: 0,
stages: [
{ duration: '5m', target: 10 }, // ramp up to soak level
{ duration: '60m', target: 10 }, // hold for an hour
{ duration: '5m', target: 0 }, // ramp down
],
},
browser: {
executor: 'constant-vus',
exec: 'browserIteration',
vus: 1,
duration: '70m',
options: { browser: { type: 'chromium' } },
},
},
thresholds: { ...BACKEND_THRESHOLDS, ...BROWSER_THRESHOLDS },
};
// --- Protocol iteration ---------------------------------------------------------
export function protocolIteration() {
group('<WORKFLOW_PLACEHOLDER>', function () {
let res = http.get(`${BASE_URL}/`, {
headers: {
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
},
});
check(res, { 'homepage 200': (r) => r.status === 200 });
// ... fill in from protocol.js with check() + tags. See smoke.js template.
sleep(Math.random() * 3 + 1);
// The user action (tagged)
});
}
// --- Browser iteration ----------------------------------------------------------
export async function browserIteration() {
const page = await browser.newPage();
let success = true;
try {
await page.goto(BASE_URL, { waitUntil: 'load' });
// ... fill in from browser.js with performance.mark/measure. See smoke.js.
} catch (e) {
success = false;
console.error(`<WORKFLOW_PLACEHOLDER> browser iteration failed: ${(e && e.message) || e}`);
throw e;
} finally {
iterationCompleted.add(success);
await page.close();
}
}
spike.js 3.4 KB
// Hybrid k6 SPIKE test for workflow <WORKFLOW_PLACEHOLDER>.
//
// SPIKE: sudden VU jump. Goal is to verify the system recovers. Some degradation
// during the spike is expected; the question is whether baseline is restored
// after the drop.
//
// Scenarios:
// - protocol : ramping-vus 0 → 100 → 0 over 2m (30s ramp / 1m hold / 30s drop)
// - browser : 1 constant VU × 2m (Web Vitals during the spike)
//
// Iteration body is identical to smoke.js.
//
// Run:
// ./tools/run-with-monitor.sh tests/<WORKFLOW_PLACEHOLDER>/spike.js
// k6 cloud run tests/<WORKFLOW_PLACEHOLDER>/spike.js
import http from 'k6/http';
import { check, group, sleep } from 'k6';
import { browser } from 'k6/browser';
import { Rate, Trend } from 'k6/metrics';
// asyncCheck (not bare check from k6) is required for async browser locators — see references/gotchas.md
import { check as asyncCheck } from 'https://jslib.k6.io/k6-utils/1.5.0/index.js';
const timeToResult = new Trend('time_to_result', true);
const iterationCompleted = new Rate('iteration_completed');
const BASE_URL = __ENV.BASE_URL || 'https://target-host.example';
const USER_AGENT =
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36';
const BACKEND_THRESHOLDS = {
http_req_failed: ['rate<0.01'],
http_req_duration: ['p(95)<500'],
checks: ['rate>0.99'],
};
const BROWSER_THRESHOLDS = {
browser_web_vital_lcp: ['p(95)<2500'],
browser_web_vital_inp: ['p(95)<200'],
browser_web_vital_cls: ['p(95)<0.1'],
'iteration_duration{scenario:browser}': ['p(95)<10000'],
time_to_result: ['p(95)<3000'],
'iteration_completed{scenario:browser}': ['rate>0.99'],
};
export const options = {
userAgent: USER_AGENT,
scenarios: {
protocol: {
executor: 'ramping-vus',
exec: 'protocolIteration',
startVUs: 0,
stages: [
{ duration: '30s', target: 100 }, // spike up
{ duration: '1m', target: 100 }, // hold at peak
{ duration: '30s', target: 0 }, // drop
],
},
browser: {
executor: 'constant-vus',
exec: 'browserIteration',
vus: 1,
duration: '2m',
options: { browser: { type: 'chromium' } },
},
},
thresholds: { ...BACKEND_THRESHOLDS, ...BROWSER_THRESHOLDS },
};
// --- Protocol iteration ---------------------------------------------------------
export function protocolIteration() {
group('<WORKFLOW_PLACEHOLDER>', function () {
let res = http.get(`${BASE_URL}/`, {
headers: {
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
},
});
check(res, { 'homepage 200': (r) => r.status === 200 });
// ... fill in from protocol.js with check() + tags. See smoke.js template.
sleep(Math.random() * 3 + 1);
// The user action (tagged)
});
}
// --- Browser iteration ----------------------------------------------------------
export async function browserIteration() {
const page = await browser.newPage();
let success = true;
try {
await page.goto(BASE_URL, { waitUntil: 'load' });
// ... fill in from browser.js with performance.mark/measure. See smoke.js.
} catch (e) {
success = false;
console.error(`<WORKFLOW_PLACEHOLDER> browser iteration failed: ${(e && e.message) || e}`);
throw e;
} finally {
iterationCompleted.add(success);
await page.close();
}
}
stress.js 3.6 KB
// Hybrid k6 STRESS test for workflow <WORKFLOW_PLACEHOLDER>.
//
// STRESS: beyond expected load. Goal is to find where SLOs start to break.
// Expect some thresholds to FAIL -- that's the entire point. The specific
// thresholds that fail tell you which part of the system is the bottleneck.
//
// Scenarios:
// - protocol : ramping-vus 0 → 50 → 0 over 20m
// - browser : 1 constant VU × 20m (Web Vitals canary -- watch for regression)
//
// Iteration body is identical to smoke.js -- duplication is intentional per the
// k6-perf-test-website skill's hybrid-load-design.md.
//
// Run:
// ./tools/run-with-monitor.sh tests/<WORKFLOW_PLACEHOLDER>/stress.js
// k6 cloud run tests/<WORKFLOW_PLACEHOLDER>/stress.js
import http from 'k6/http';
import { check, group, sleep } from 'k6';
import { browser } from 'k6/browser';
import { Rate, Trend } from 'k6/metrics';
// asyncCheck (not bare check from k6) is required for async browser locators — see references/gotchas.md
import { check as asyncCheck } from 'https://jslib.k6.io/k6-utils/1.5.0/index.js';
const timeToResult = new Trend('time_to_result', true);
const iterationCompleted = new Rate('iteration_completed');
const BASE_URL = __ENV.BASE_URL || 'https://target-host.example';
const USER_AGENT =
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36';
const BACKEND_THRESHOLDS = {
http_req_failed: ['rate<0.01'],
http_req_duration: ['p(95)<500'],
checks: ['rate>0.99'],
// 'http_req_duration{name:GetAction}': ['p(95)<1000', 'p(99)<1500'],
};
const BROWSER_THRESHOLDS = {
browser_web_vital_lcp: ['p(95)<2500'],
browser_web_vital_inp: ['p(95)<200'],
browser_web_vital_cls: ['p(95)<0.1'],
'iteration_duration{scenario:browser}': ['p(95)<10000'],
time_to_result: ['p(95)<3000'],
'iteration_completed{scenario:browser}': ['rate>0.99'],
};
export const options = {
userAgent: USER_AGENT,
scenarios: {
protocol: {
executor: 'ramping-vus',
exec: 'protocolIteration',
startVUs: 0,
stages: [
{ duration: '5m', target: 50 }, // ramp up to stress level
{ duration: '10m', target: 50 }, // hold at stress level
{ duration: '5m', target: 0 }, // ramp down
],
},
browser: {
executor: 'constant-vus',
exec: 'browserIteration',
vus: 1,
duration: '20m',
options: { browser: { type: 'chromium' } },
},
},
thresholds: { ...BACKEND_THRESHOLDS, ...BROWSER_THRESHOLDS },
};
// --- Protocol iteration ---------------------------------------------------------
export function protocolIteration() {
group('<WORKFLOW_PLACEHOLDER>', function () {
let res = http.get(`${BASE_URL}/`, {
headers: {
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
},
});
check(res, { 'homepage 200': (r) => r.status === 200 });
// ... fill in from protocol.js with check() + tags. See smoke.js template.
sleep(Math.random() * 3 + 1);
// The user action (tagged)
});
}
// --- Browser iteration ----------------------------------------------------------
export async function browserIteration() {
const page = await browser.newPage();
let success = true;
try {
await page.goto(BASE_URL, { waitUntil: 'load' });
// ... fill in from browser.js with performance.mark/measure. See smoke.js.
} catch (e) {
success = false;
console.error(`<WORKFLOW_PLACEHOLDER> browser iteration failed: ${(e && e.message) || e}`);
throw e;
} finally {
iterationCompleted.add(success);
await page.close();
}
}
lg-monitor.sh 6.3 KB
#!/usr/bin/env bash
# Load-generator resource sidecar -- cross-platform (macOS + Linux).
#
# Samples k6 / Chromium / system CPU / NIC throughput every $INTERVAL seconds
# (default 5) and writes a CSV row to stdout. Terminate with SIGINT or SIGTERM.
#
# Required because a CPU-pegged load generator silently throttles its own
# request rate -- the server then looks slower than it really is. See the
# k6-perf-test-website skill's lg-monitoring.md.
#
# Usage (standalone):
# tools/lg-monitor.sh > /tmp/lg.csv &
# MON=$!; trap "kill $MON" EXIT
# k6 run tests/...
#
# Usually invoked indirectly via tools/run-with-monitor.sh.
#
# Windows: run under WSL2.
set -u
INTERVAL="${INTERVAL:-5}"
OS="$(uname -s)"
# --- OS-specific functions ------------------------------------------------------
case "$OS" in
Darwin)
detect_nic() {
route get default 2>/dev/null | awk '/interface:/{print $2; exit}'
}
sample_cpu() {
# macOS `top -l 1 -s 0`: "CPU usage: 12.34% user, 5.67% sys, 81.99% idle"
top -l 1 -s 0 -n 0 2>/dev/null \
| awk -F'[ %,]+' '/CPU usage:/{print $3 "," $5 "," $7; exit}'
}
sample_nic_bytes() {
# `netstat -ibn`: pick the link row (column 3 contains "Link") for our NIC.
# Columns: Name Mtu Network Address Ipkts Ierrs Ibytes Opkts Oerrs Obytes ...
local nic="$1"
netstat -ibn 2>/dev/null \
| awk -v nic="$nic" '$1==nic && $3 ~ /Link/{print $7","$10; exit}'
}
find_chrome_pids() {
# macOS: ps -axo pid,command. --headless flag distinguishes test chromium
# from the user's regular Chrome.
ps -axo pid=,command= 2>/dev/null \
| awk 'BEGIN{IGNORECASE=1} /--headless/ && tolower($0) ~ /chrom/ {print $1}' \
| head -50
}
;;
Linux)
detect_nic() {
# `ip route show default` → "default via X dev eth0 ..."
ip route show default 2>/dev/null | awk '/^default/{for(i=1;i<=NF;i++)if($i=="dev"){print $(i+1); exit}}'
}
sample_cpu() {
# Read /proc/stat twice (separated by 1s), compute deltas. cpu line:
# cpu user nice system idle iowait irq softirq steal guest guest_nice
local a b
a=$(awk '/^cpu /{print $2","$3","$4","$5","$6","$7","$8","$9; exit}' /proc/stat)
sleep 1
b=$(awk '/^cpu /{print $2","$3","$4","$5","$6","$7","$8","$9; exit}' /proc/stat)
awk -v a="$a" -v b="$b" 'BEGIN {
n=split(a,aa,","); split(b,bb,",");
for (i=1;i<=n;i++) d[i]=bb[i]-aa[i];
total=0; for (i=1;i<=n;i++) total += d[i];
if (total==0) { print "0.0,0.0,0.0"; exit }
user = 100 * (d[1] + d[2]) / total;
sys = 100 * (d[3] + d[6] + d[7]) / total;
idle = 100 * (d[4] + d[5]) / total;
printf "%.2f,%.2f,%.2f", user, sys, idle;
}'
}
sample_nic_bytes() {
# /proc/net/dev:
# iface: rx_bytes packets errs drop fifo frame compressed multicast tx_bytes packets errs ...
local nic="$1"
awk -F'[: ]+' -v nic="$nic" '$2==nic{print $3","$11; exit; }; $1==nic{print $2","$10; exit}' \
< /proc/net/dev
}
find_chrome_pids() {
ps -eo pid=,cmd= 2>/dev/null \
| awk 'BEGIN{IGNORECASE=1} /--headless/ && tolower($0) ~ /chrom/ {print $1}' \
| head -50
}
;;
*)
echo "lg-monitor: unsupported OS '$OS'. Supported: Darwin (macOS), Linux. Run under WSL2 on Windows." >&2
exit 2
;;
esac
# Detect primary NIC.
NIC="$(detect_nic)"
NIC="${NIC:-en0}"
# --- CSV header ------------------------------------------------------------------
echo "timestamp_iso,uptime_s,sys_cpu_user,sys_cpu_sys,sys_cpu_idle,k6_cpu,k6_mem_pct,k6_rss_kb,chrome_cpu_total,chrome_mem_pct_total,chrome_rss_kb_total,chrome_proc_count,nic,nic_rx_bytes,nic_tx_bytes,nic_rx_bytes_per_s,nic_tx_bytes_per_s"
start_s=$(date +%s)
prev_rx=""
prev_tx=""
trap 'exit 0' INT TERM
# --- Sample loop -----------------------------------------------------------------
while true; do
ts=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
uptime=$(( $(date +%s) - start_s ))
# System CPU
cpu_csv="$(sample_cpu)"
sys_user="$(echo "$cpu_csv" | cut -d, -f1)"
sys_sys="$(echo "$cpu_csv" | cut -d, -f2)"
sys_idle="$(echo "$cpu_csv" | cut -d, -f3)"
# k6 process (pgrep matches `k6 run ...` invocation).
# `|| true` is intentional: pgrep exits non-zero with no output when there's
# no match, which is the normal case during sidecar startup (we sample before
# k6 starts) and shutdown. Without the guard, callers that source this script
# under `set -e` (or `bash -e`) silently exit at the first idle sample, and
# the CSV stops growing -- leading to the false "no monitor output" symptom.
k6_pid=$(pgrep -fn "k6 run " 2>/dev/null | head -1 || true)
if [ -n "${k6_pid:-}" ]; then
k6_line=$(ps -o '%cpu=,%mem=,rss=' -p "$k6_pid" 2>/dev/null | tr -s ' ')
k6_cpu=$(echo "$k6_line" | awk '{print $1}')
k6_mem=$(echo "$k6_line" | awk '{print $2}')
k6_rss=$(echo "$k6_line" | awk '{print $3}')
else
k6_cpu=""; k6_mem=""; k6_rss=""
fi
# Chromium headless processes (sum across all matching).
# `|| true` for same reason as the k6 pgrep above -- no match is normal.
chrome_pids="$(find_chrome_pids || true)"
chrome_cnt=0
chrome_cpu=0
chrome_mem=0
chrome_rss=0
if [ -n "${chrome_pids:-}" ]; then
for p in $chrome_pids; do
line=$(ps -o '%cpu=,%mem=,rss=' -p "$p" 2>/dev/null | tr -s ' ')
[ -z "$line" ] && continue
cpu=$(echo "$line" | awk '{print $1}')
mem=$(echo "$line" | awk '{print $2}')
rss=$(echo "$line" | awk '{print $3}')
chrome_cpu=$(awk "BEGIN{print $chrome_cpu + $cpu}")
chrome_mem=$(awk "BEGIN{print $chrome_mem + $mem}")
chrome_rss=$(awk "BEGIN{print $chrome_rss + $rss}")
chrome_cnt=$((chrome_cnt + 1))
done
fi
if [ "$chrome_cnt" -eq 0 ]; then
chrome_cpu=""; chrome_mem=""; chrome_rss=""
fi
# NIC throughput
nic_csv="$(sample_nic_bytes "$NIC")"
rx="$(echo "$nic_csv" | cut -d, -f1)"
tx="$(echo "$nic_csv" | cut -d, -f2)"
if [ -n "${prev_rx:-}" ] && [ -n "$rx" ]; then
rx_per_s=$(awk "BEGIN{print ($rx - $prev_rx) / $INTERVAL}")
tx_per_s=$(awk "BEGIN{print ($tx - $prev_tx) / $INTERVAL}")
else
rx_per_s=""; tx_per_s=""
fi
prev_rx="$rx"
prev_tx="$tx"
echo "$ts,$uptime,$sys_user,$sys_sys,$sys_idle,$k6_cpu,$k6_mem,$k6_rss,$chrome_cpu,$chrome_mem,$chrome_rss,$chrome_cnt,$NIC,$rx,$tx,$rx_per_s,$tx_per_s"
sleep "$INTERVAL"
done
run-with-monitor.sh 3.9 KB
#!/usr/bin/env bash
# Run a k6 script with the LG resource sidecar (lg-monitor.sh).
#
# Required for any test type beyond smoke, so we can tell whether the laptop
# running k6 is the bottleneck rather than the server-under-test. See the
# k6-perf-test-website skill's lg-monitoring.md.
#
# Usage:
# tools/run-with-monitor.sh tests/wN-<short-name>/smoke.js
# tools/run-with-monitor.sh tests/wN-<short-name>/stress.js
# INTERVAL=2 tools/run-with-monitor.sh tests/wN-<short-name>/spike.js # finer sampling
#
# Writes:
# /tmp/perf-lg-monitor/<workflow>-<test-type>-<timestamp>.csv full samples
# /tmp/perf-lg-monitor/<workflow>-<test-type>-<timestamp>.k6.log full k6 output
#
# On exit, prints a summary of LG resource usage and a saturation verdict
# (OK / NOTE / WARNING). Treat WARNING runs as inconclusive.
set -u
if [ $# -lt 1 ]; then
echo "usage: $0 <k6-script-path> [k6-args...]" >&2
exit 1
fi
K6_SCRIPT="$1"; shift
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Identify workflow + test type from path.
WF=$(basename "$(dirname "$K6_SCRIPT")")
TT=$(basename "$K6_SCRIPT" .js)
TS=$(date +%Y%m%d-%H%M%S)
LOGDIR="/tmp/perf-lg-monitor"
mkdir -p "$LOGDIR"
CSV="$LOGDIR/$WF-$TT-$TS.csv"
K6LOG="$LOGDIR/$WF-$TT-$TS.k6.log"
echo "=== Run: $WF · $TT · $(date +%H:%M:%S) ==="
echo "Monitor CSV: $CSV"
echo "k6 log : $K6LOG"
# Start monitor in background.
bash "$SCRIPT_DIR/lg-monitor.sh" > "$CSV" &
MON_PID=$!
trap 'kill "$MON_PID" 2>/dev/null; wait "$MON_PID" 2>/dev/null; exit' INT TERM EXIT
# Brief grace so the monitor captures a baseline sample.
sleep 2
# Run k6 (env vars including BASE_URL inherit).
echo "--- k6 starting ---"
k6 run "$K6_SCRIPT" "$@" 2>&1 | tee "$K6LOG"
K6_RC="${PIPESTATUS[0]}"
echo "--- k6 finished (rc=$K6_RC) ---"
# Stop monitor.
kill "$MON_PID" 2>/dev/null
wait "$MON_PID" 2>/dev/null
trap - INT TERM EXIT
# --- Summarise the CSV ----------------------------------------------------------
echo
echo "=== LG monitor summary ==="
if ! command -v python3 >/dev/null 2>&1; then
echo "(python3 not found; raw CSV at $CSV)"
exit "$K6_RC"
fi
python3 - "$CSV" <<'PY'
import csv, sys, statistics
def to_f(v):
try: return float(v)
except Exception: return None
with open(sys.argv[1]) as f:
rows = list(csv.DictReader(f))
if len(rows) < 2:
print("Not enough samples to summarise.")
sys.exit()
def col(name):
return [v for r in rows for v in [to_f(r.get(name, ''))] if v is not None]
def stat(vals, fmt='{:.1f}'):
if not vals: return 'n/a'
return f"min={fmt.format(min(vals))} avg={fmt.format(statistics.mean(vals))} max={fmt.format(max(vals))}"
duration = rows[-1].get('uptime_s', '?')
try:
interval = int(rows[1]['uptime_s']) - int(rows[0]['uptime_s'])
except Exception:
interval = '?'
print(f"samples : {len(rows)}")
print(f"duration : {duration}s")
print(f"interval : {interval}s")
print()
print(f"sys_cpu_idle : {stat(col('sys_cpu_idle'))} (lower = laptop more saturated)")
print(f"k6 %CPU : {stat(col('k6_cpu'))}")
print(f"k6 RSS (MB) : {stat([v/1024 for v in col('k6_rss_kb')])}")
print(f"chrome %CPU : {stat(col('chrome_cpu_total'))}")
print(f"chrome RSS MB : {stat([v/1024 for v in col('chrome_rss_kb_total')])}")
print(f"chrome procs : {stat(col('chrome_proc_count'), '{:.0f}')}")
print(f"NIC rx MB/s : {stat([v/1e6 for v in col('nic_rx_bytes_per_s')], '{:.2f}')}")
print(f"NIC tx MB/s : {stat([v/1e6 for v in col('nic_tx_bytes_per_s')], '{:.2f}')}")
print()
# Saturation verdict
idle = col('sys_cpu_idle')
if idle:
min_idle = min(idle)
if min_idle < 10:
print(f"WARNING: system idle dropped to {min_idle:.1f}% -- LG was saturated; k6 numbers unreliable")
elif min_idle < 30:
print(f"NOTE: system idle dipped to {min_idle:.1f}% -- LG had headroom but not much")
else:
print(f"OK: system idle stayed >= {min_idle:.1f}% -- LG had plenty of headroom")
PY
exit "$K6_RC"
functional-tests.md 10.6 KB
# Building functional tests
Per workflow, you produce two functional tests:
- **`protocol.js`** — single-iteration, single-VU, hand-cleaned from
`from-har.js`. Uses `expect()` for hard assertions.
- **`browser.js`** — single-iteration, single-VU, hand-converted
from the Playwright recorder. Uses `expect()` for hard assertions.
Both must pass via `./tests/run-all.sh` **before any load test runs**.
## Contents
- [`protocol.js` — cleaning `from-har.js`](#protocoljs-cleaning-from-harjs)
- Step 1: Move `User-Agent` to `options.userAgent`
- Step 2: Rename the group
- Step 3: Parameterise the base URL
- Step 4: Replace recorded credentials with test credentials
- [Cookies, CSRF, and k6's CookieJar API](#cookies-csrf-and-k6s-cookiejar-api) — `r.cookies` vs `r.json()`; `jar:` vs `cookies:` footgun
- Step 5: Drop the auto-inserted `sleep(1)`
- Step 6: Add `expect()` on every load-bearing response
- [Why hard assertions in functional tests but `check()` in load tests](#why-hard-assertions-in-functional-tests-but-check-in-load-tests)
- [`browser.js` — 5-step Playwright → k6/browser conversion](#browserjs-5-step-conversion-from-playwright-recorder)
- Step 1: Replace imports
- Step 2: Replace launch/context setup with `browser.newPage()`
- Step 3: Keep the page-interaction body verbatim
- Step 4: Replace `expect` (Playwright) with k6-testing `expect`
- [Step 4.5: `newPage()` vs `newContext().newPage()`](#step-45-newpage-vs-newcontextnewpage) — when to reach for context-level control
- Step 5: Wrap in `try / finally`
- [Running functional tests](#running-functional-tests)
- [What "passing" means](#what-passing-means)
## protocol.js: cleaning `from-har.js`
`har-to-k6` produces a verbatim transcript of the HAR. It is not
suitable as a maintainable test. Apply these cleanups:
### 1. Move `User-Agent` to `options.userAgent`
`har-to-k6` sets `User-Agent`, `sec-ch-ua`, `sec-ch-ua-mobile`,
`sec-ch-ua-platform` on every request. Drop them; set the UA once:
```js
const USER_AGENT =
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36';
export const options = {
vus: 1,
iterations: 1,
userAgent: USER_AGENT,
};
```
The UA must be a **real Chrome** string. Headless UAs trigger
bot-blocking.
### 2. Rename the group
har-to-k6 names the group from the HAR's `_pageref`, which is opaque
(`page_0`, `page_1`, …). Replace with a descriptive name:
```js
group('w1-login-then-purchase', function () { /* ... */ });
```
### 3. Parameterise the base URL
```js
const BASE_URL = __ENV.BASE_URL || 'https://target-host.example';
```
Replace every absolute URL in `from-har.js` with
``${BASE_URL}/path``.
### 4. Replace recorded credentials with test credentials
If the HAR contains a session cookie or bearer token, replace it
with:
- A well-known test token (e.g. `__ENV.TEST_TOKEN`).
- Or a login step at the top of the iteration body.
**Do not commit recorded credentials.** The HAR captures the live
session; treat it like a secret. The cleanup step is where this
data becomes safe to commit.
#### Cookies, CSRF, and k6's CookieJar API
k6 has two distinct cookie surfaces that are easy to confuse. Get
them wrong and your authenticated workflow looks like it works
but actually replays no session at all.
**Reading cookies the server *set***: response cookies are on the
`r.cookies` object, keyed by name, valued as an array of cookie
records. A common CSRF pattern is the server returning an empty
body but setting a `csrf_token` cookie:
```js
// WRONG — reads from JSON body, which is empty.
const r = http.post(`${BASE_URL}/api/csrf-token`);
const csrf = r.json('csrf_token'); // undefined
// RIGHT — read the Set-Cookie value.
const r = http.post(`${BASE_URL}/api/csrf-token`);
const csrf = r.cookies.csrf_token && r.cookies.csrf_token[0].value;
```
**Storing cookies across requests** (login → authenticated requests):
By default k6 maintains a **per-VU global cookie jar**, automatically.
For a normal logged-in workflow you don't need to do anything — just
hit `POST /login`, then make subsequent requests on the same VU, and
the session cookie is carried.
If you do need an explicit jar (e.g. multiple parallel users in one
VU), the per-request option name is `jar:`, not `cookies:`:
```js
// WRONG — `cookies` expects a name→value object, not a jar. k6 ignores
// the jar here, so the request silently uses the default per-VU jar.
const jar = new http.CookieJar();
http.get(url, { cookies: jar });
// RIGHT — use jar:, or just rely on the default per-VU jar.
const jar = new http.CookieJar();
http.get(url, { jar });
```
**Sending a CSRF token** that arrived via cookie:
```js
http.post(`${BASE_URL}/api/rate`, body, {
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrf, // pulled from r.cookies.csrf_token[0].value
},
});
```
Verify the contract works in your `protocol.js` smoke run before
trusting it under load — silent CSRF-missing 403s are a classic way
to discover the issue only on stress day.
### 5. Drop the auto-inserted `sleep(1)`
har-to-k6 adds `sleep(1)` at the end of the iteration. Functional
tests are single-iteration; remove it.
### 6. Add `expect()` on every load-bearing response
```js
import { expect } from 'https://jslib.k6.io/k6-testing/0.5.0/index.js';
// Status assertion on every static asset (so a hash-renamed bundle
// after a rebuild fails the test loudly rather than silently 404):
for (const [kind, path] of assets) {
const res = http.get(`${BASE_URL}${path}`, { /* ... */ });
expect(res.status, `asset ${path}`).toBe(200);
}
// Body-shape assertion on the load-bearing response:
expect(res.status).toBe(200);
const data = res.json('result');
expect(data).not.toBeNull();
expect(typeof data.id).toBe('string');
expect(data.id.length).toBeGreaterThan(0);
```
Rule of thumb: every `http.*` call gets at least a status
`expect()`. The response that carries the workflow's payload gets
additional body-shape assertions.
### Why hard assertions in functional tests but `check()` in load tests
| Functional test | Load test |
|------------------------------------------|------------------------------------|
| `expect()` aborts iteration on failure | `check()` records a metric |
| Single iteration → abort = failed test | Many iterations → don't poison run |
| Used to validate the script is correct | Used to measure under load |
In the load script you'll also add `tags: { name: 'EndpointName' }`
to each request for per-endpoint thresholds (see
`slo-design.md`).
## browser.js: 5-step conversion from Playwright recorder
The body of the Playwright recorder is the body of the
`k6/browser` default function, modulo framework scaffolding.
### Step 1: Replace imports
```js
// Recorder:
const { chromium } = require('playwright');
// k6/browser:
import { browser } from 'k6/browser';
import { expect } from 'https://jslib.k6.io/k6-testing/0.5.0/index.js';
```
### Step 2: Replace launch / context setup with `browser.newPage()`
```js
// Recorder:
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({ /* ... */ });
const page = await context.newPage();
// k6/browser:
export const options = {
scenarios: {
wN_<short_name>: {
executor: 'shared-iterations',
vus: 1, iterations: 1,
options: { browser: { type: 'chromium' } },
},
},
};
export default async function () {
const page = await browser.newPage();
try {
// ... body ...
} finally {
await page.close();
}
}
```
### Step 3: Keep the page-interaction body verbatim
The Playwright `page.*` API is the same in k6/browser. `page.goto`,
`page.locator`, `page.waitForResponse`, `Promise.all(...)`, all
work identically.
The hydration-signal wait you used in the recorder transfers
verbatim — keep it.
### Step 4: Replace `expect` (Playwright) with k6-testing `expect`
```js
// Recorder (Playwright):
import { expect } from '@playwright/test';
await expect(button).toBeVisible();
// k6/browser:
import { expect } from 'https://jslib.k6.io/k6-testing/0.5.0/index.js';
await expect(button).toBeVisible();
```
The k6-testing `expect()` API is a deliberate subset of Playwright's
`expect()` — most assertions transfer 1:1. `toBeVisible`,
`toContainText`, `toHaveText`, `toBeEnabled`, etc. all work.
### Step 4.5: `newPage()` vs `newContext().newPage()`
The templates use `browser.newPage()` because it's the right default
for **stateless** iterations — each iteration gets a fresh page, and
k6 does NOT share cookies between iterations of the same VU when you
call `browser.newPage()`. For 99% of workflow tests this is what you
want.
Use `browser.newContext()` first if your test specifically needs:
- A custom user agent or locale per iteration that overrides the
global `options.userAgent`.
- Cookies preloaded into the browser before navigation (e.g. testing
a partially-authenticated state without going through the login UI).
- Explicit cookie *isolation* in a scenario that creates multiple
pages per iteration — `newContext()` is the boundary in that case.
```js
// Default (recommended):
const page = await browser.newPage();
// Only when you need context-level control:
const context = await browser.newContext({ userAgent: '...', locale: 'en-GB' });
const page = await context.newPage();
try {
// ...
} finally {
await page.close();
await context.close(); // also close the context
}
```
Don't reach for `newContext()` "just to be safe" — it adds complexity
and the cleanup ordering matters. Stick with `newPage()` unless one of
the cases above applies.
### Step 5: Wrap in `try / finally`
```js
export default async function () {
const page = await browser.newPage();
try {
// ... body ...
} finally {
await page.close(); // always close the page; resource leak otherwise
}
}
```
In the load-test versions (e.g. `smoke.js`, `average.js`), the
wrapper expands to `try / catch / finally` with an
`iteration_completed` Rate — see `slo-design.md`.
## Running functional tests
```bash
# All workflows, both kinds:
./tests/run-all.sh
# Just one:
k6 run tests/wN-<short-name>/protocol.js
K6_BROWSER_HEADLESS=true k6 run tests/wN-<short-name>/browser.js
```
`run-all.sh` writes per-test logs to `${TMPDIR}/k6-run-all/` so a
failure can be drilled in.
Exit code = failure count. Treat any non-zero exit as
"do not proceed to load testing".
## What "passing" means
For protocol tests: every `expect()` resolves true. k6 prints
`✓ all checks passed`. Exit code 0.
For browser tests: same, plus the test ran headless without
crashing the chromium process. If k6 reports the iteration
"interrupted", investigate before treating the test as flaky.
gotchas.md 11.4 KB
# Generic gotchas
Things this skill has learned the hard way. All non-app-specific.
None of these are framework / language / database gotchas — those
are emergent findings, not assumptions.
## Recording / functional
### Third-party RUM and error reporters pollute HAR captures
Public websites typically embed third-party agents: RUM
(Real User Monitoring), error reporters, ad networks, analytics,
A/B test scripts, social-media widgets. Their requests:
- Inflate the HAR by 10-100×.
- Add unrelated endpoints to your per-endpoint threshold list.
- Cause k6 to send test traffic to third-party collectors (rude
and may breach their TOS).
**Fix:** `recordHar.urlFilter` regex that allow-lists only the
target host(s). See `recording-with-playwright.md`.
### `HeadlessChrome` UA triggers bot-blocking
Many production sites filter the default headless UA at the WAF
or CDN level. Symptoms:
- 403 / 429 / 503 on the first request.
- Redirects to a bot-challenge page.
- Empty responses.
**Fix:** set `options.userAgent` to a real Chrome UA on every k6
script, and `browserContext({ userAgent: ... })` on every
Playwright recorder.
### Hydration timing breaks recorders
SPAs render some markup before client JS hydrates and attaches
event handlers. If the recorder clicks before hydration, the
click does nothing.
**Fix:** wait for a post-hydration sentinel locator (an interactive
element that only exists after the framework has booted). See
`recording-with-playwright.md`.
## SLO design
### `http_req_duration p(95) < 500` hides slow endpoints
The global threshold is dominated by the fastest, most-frequent
endpoints (static assets, small JSON). A slow critical endpoint
hides in the aggregate.
**Fix:** tag every protocol request with `tags: { name: '...' }`
and threshold per tag.
### `group()` does not work in async (browser) code
k6's `group()` does not measure awaited code reliably. The
group_duration metric will not capture what you intended.
**Fix:** use `performance.mark/measure` inside `page.evaluate()`
and record a custom Trend. See `slo-design.md`.
### Web Vitals thresholds may need loosening — but never silently
Some real apps have deterministic layout shifts (e.g. a widget that
re-renders once data loads) the team has accepted. If you raise
`browser_web_vital_cls` from `< 0.1` to `< 0.2` to make tests
pass, **report it**: which workflow, which selector, the
deterministic CLS value, and the customer's decision not to fix.
Silent loosening is the #1 way perf tests stop catching regressions.
### Functional tests use `expect()`; load tests use `check()` + tags
`expect()` aborts iteration on failure. That's right for functional
tests (single iteration, abort = failed test) but wrong for load
tests (many iterations, abort poisons the run).
`check()` records a metric (`checks` rate) and continues. Pair it
with `tags: { name: '...' }` on the underlying http call so failures
show up per-endpoint in the summary.
### In browser iterations use `asyncCheck` from `k6-utils`, not bare `check()`
The load-test templates import
`import { check as asyncCheck } from 'https://jslib.k6.io/k6-utils/1.5.0/index.js'`
for assertions inside the browser scenario. This is deliberate.
Standard `check()` from `k6` is **synchronous**: it evaluates each
predicate immediately and expects a boolean back. Browser locator
methods (`isVisible()`, `textContent()`, …) are **async** and return
Promises. A Promise is always truthy, so a bare `check()` against an
async predicate:
- passes every time, regardless of the actual page state, and
- never awaits the assertion, so the check is meaningless.
The iteration shows green while the assertion never really ran —
the same silent-green-failure class as the library-mixing gotcha
above. `asyncCheck` from `k6-utils` awaits the predicate before
recording the result.
Rule: synchronous protocol code → `check()` from `k6`; async
browser code → `asyncCheck` (`check` from `k6-utils`).
### Pick one `expect`/`check` library per workflow — don't mix
The templates ship `expect()` from **`k6-testing`** (a JS library
loaded over HTTPS — Jest-style: `expect(r.status).toBe(200)`) in
`protocol.js` and `browser.js`, and bare `check()` from `k6` in the
load-test files (`smoke.js`, `average.js`, ...).
The exact import URL the templates use is:
```js
import { expect } from 'https://jslib.k6.io/k6-testing/0.5.0/index.js';
```
**Do NOT replace this with any of the following — they look
similar but are different code and will break in stock k6:**
| Wrong import | Why it breaks |
|--------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------|
| `import { expect } from 'k6/x/expect'` | `k6/x/*` are xk6 extensions that must be compiled into a custom k6 binary. Stock k6 fails at provisioning. |
| `import { expect } from 'https://jslib.k6.io/k6chaijs/4.3.4.3/index.js'` | Different assertion style: `.to.equal()` chains. If you import this and use `.toBe()` syntax, every call TypeErrors. |
| `import { expect } from '@playwright/test'` | Playwright lib; doesn't exist in k6's runtime. |
When you adapt a template into a real workflow, **stay with the
library the template chose**. Mixing libraries inside the same
iteration produces silent test invalidation:
- Importing `expect` from `k6-testing` and then calling
`.to.equal()` (Chai/k6chaijs syntax) throws
`TypeError: Cannot read property 'equal' of undefined or null`
on every iteration.
- k6 then registers **zero** `checks` for the iteration. The
threshold `checks: ['rate>0.99']` passes with `rate=0.00%`
(k6 treats an empty metric as non-violating).
- All check failures are masked. The smoke run appears green but
the assertions never ran.
Rule: the import path determines the assertion API. `k6-testing` =
`.toBe()` / `.toContain()` / `.toEqual()`. `k6chaijs` =
`.to.equal()` / `.to.include()` / `.to.deep.equal()`. Don't
cross-import.
### Workflows with expected 4xx/5xx responses break the default `http_req_failed` threshold
Some workflows intentionally exercise the *failure* path — e.g.
"anonymous user tries to rate a pizza, expect 401", "request a
deleted resource, expect 404". k6 counts any 4xx/5xx as a failed
request by default, so a workflow that produces one expected 401
out of every 5 requests will sit at a 20% `http_req_failed` rate
and immediately blow the template's
`http_req_failed: ['rate<0.01']` threshold.
You have two correct fixes; pick one per workflow and **document
the choice** in `runbook.md`:
**Fix A — module-level: tell k6 the expected status is not a failure.**
This is the cleaner option when the failure path is part of the
contract:
```js
import http from 'k6/http';
// Treat HTTP 401 as a non-failure response for this workflow's
// anonymous-rate check; all other non-2xx still count as failed.
http.setResponseCallback(
http.expectedStatuses({ min: 200, max: 299 }, 401),
);
```
**Fix B — per-request: tag the expected-failure call and threshold
its tag separately.** Useful when only one specific request is the
expected-failure case:
```js
http.post(`${BASE_URL}/api/rate`, body, {
tags: { name: 'AnonRateExpected401', expectedNon2xx: 'true' },
});
// thresholds:
'http_req_failed{expectedNon2xx:true}': ['rate<1.0'], // permits 100% failed
'http_req_failed{expectedNon2xx:!true}': ['rate<0.01'], // 2xx-only requests stay at <1%
```
Do **not** "fix" this by relaxing the global `http_req_failed`
threshold from `rate<0.01` to `rate<0.25`. That hides real
failures elsewhere in the workflow.
## Load generation
### LG saturation masquerades as server slowness
A CPU-pegged laptop running k6 silently throttles its own request
rate. Symptoms: lower-than-expected RPS, higher-than-expected
latency, "iterations interrupted".
**Fix:** always run with `run-with-monitor.sh`. Treat WARNING
verdicts (sys_cpu_idle < 10%) as inconclusive runs.
### Browser VUs cost ~1 GB RSS each
Don't stack browser VUs to "drive more load". Use protocol VUs
for load; keep browser VUs at 1 per scenario as a Web Vitals
canary.
### Custom Trend metrics accumulate in k6 client memory
Long browser soaks (60+ minutes) show k6 RSS climbing on the LG.
This is **not necessarily a server-side leak** — k6 accumulates
every metric sample in memory for the run summary.
**Verify** against the backend's memory metrics before reporting
a leak. If backend memory is flat but k6 RSS climbs, the climb is
client-side metric accumulation.
### `${ARRAY[-1]}` is bash 4+; macOS ships bash 3.2
Negative-index array subscript syntax was added in bash 4. macOS
ships bash 3.2 for licensing reasons. Helper scripts that use
`${arr[-1]}` will fail on macOS with `bad array subscript`.
**Fix:** explicit index arithmetic:
```bash
LAST_INDEX=$(( ${#arr[@]} - 1 ))
last="${arr[$LAST_INDEX]}"
```
## Cloud k6
### Browser VU-hours cost 10× protocol VU-hours
A 70-minute soak with 10 protocol + 1 browser VU costs:
`(10 × 70/60) + (1 × 70/60 × 10) = 11.67 + 11.67 = 23.3 VUh`.
The single browser VU costs as much as all 10 protocol VUs.
Confirm with the user before running browser-heavy soaks in cloud.
### Local results may disagree with cloud results
Possible reasons (all legitimate):
- LG was saturated locally.
- Network path differs (CDN edge location).
- Cloud `cloud.distribution` spreads VUs geographically.
- IP allow-list / WAF treats cloud LG IPs differently.
Trust cloud for measurement, local for validation. Don't blend them.
### `k6 cloud login` failures
If `k6 cloud run` fails with authentication errors, the user
hasn't completed the Grafana Cloud k6 auth flow on this machine.
Don't try to fix it inside this skill — pause and ask them to
authenticate (typically `k6 cloud login`, or whatever their
organisation's auth process is) before retrying.
## Reporting
### Vague findings are useless
"Latency is high" is not a finding. "GetRecommendation p(95) hit
1.4s at iteration ~200; corresponded to LG WARNING verdict; see
log path X" is.
Every finding needs: a specific metric, a specific window, and a
specific evidence path (k6 summary log, LG CSV, Grafana panel).
### Don't fabricate backend findings from client-side signals
"The database is slow" cannot be concluded from k6 alone. You can
say "the recommend endpoint's response time is high" — that's a
client-side observable. "The database is slow" requires backend
investigation per §9 of SKILL.md.
### Don't recommend fixes
The customer's engineers know their code. The skill reports what
k6 observed and what Grafana shows. It does **not** recommend code
changes. Hand the evidence back and let the team decide.
## Process
### Always elicit workflows before scaffolding
Without explicit workflows, every later step is guesswork. The
elicitation step exists for this reason; skipping it produces
tests that measure the wrong thing.
### Don't proceed to load testing until functional tests pass
`./tests/run-all.sh` must exit 0. A failing functional test
means the script has a bug; running load against it produces
noise, not signal.
### One file per test type, not a dispatcher
Tempting to write `load.js` with `LOAD_TYPE=__ENV.LOAD_TYPE`.
Reject the temptation. Each file should read cleanly in isolation
during incident review. See `hybrid-load-design.md`.
grafana-investigation.md 7.8 KB
# Backend investigation with Grafana
**Only applies if the customer owns the backend and has Grafana
access.** Skip this whole section if either is "no".
The goal: correlate k6's load-side signals (failed thresholds,
latency spikes, error rates) with backend-side signals (RED
metrics, error logs, profiles) to produce specific evidence.
## Non-negotiable: do not assume the stack
The skill is language-agnostic. **Do not** guess:
- Which language the backend is in (Go / Python / Java / Node /
Rust / …).
- Which datasources are configured (Prom / Loki / Tempo /
Pyroscope — any subset is possible).
- Which label keys identify the service (`service_name`, `service`,
`app`, `job`, `namespace`, `container`, …).
- Which metric exposition is in use (default Prom exporters,
OpenTelemetry, custom metrics).
Discover all of these from the live Grafana before formulating
queries.
## Step 1: discover datasources
Prefer `mcp-grafana` for in-session, structured discovery:
```
list_datasources()
```
Fall back to `gcx`:
```bash
gcx datasources list -o json
```
Record the UIDs and types. Subsequent queries need them.
If neither `mcp-grafana` nor `gcx` is configured for the user's
Grafana instance, pause and ask them to authenticate one of them
before continuing.
## Step 2: ask the user for service labels
Read the user's `runbook.md` from elicitation. If they recorded
`service labels`, use them. If not, ask:
> "What label and value identify your service in Prometheus? For
> example, some teams use `service_name="my-app"`, others use
> `service="my-app"` or `job="my-app"`. Please tell me the exact
> key and value."
Confirm by running a smoke query:
```promql
up{<label_key>="<label_value>"}
```
If `up` returns no series, the label is wrong. Ask again or use
`mcp-grafana`'s label discovery:
```
list_label_names(datasource_uid=...)
list_label_values(datasource_uid=..., label="service_name")
```
## Step 3: identify the k6 run window
For every load test run, you have:
- A start timestamp (from the k6 invocation).
- An end timestamp (from the k6 summary).
- A workflow name (`tests/wN-<short-name>/`).
- A test type (`smoke` / `average` / `stress` / …).
- An LG monitor CSV with per-second samples.
**Use those exact timestamps** as the `from` / `to` parameters in
every Grafana query. Don't query "last 1h" — that includes time
before and after the test, which contaminates the signal.
## Step 4: correlate signals
For each k6 threshold that failed, find the corresponding backend
signal.
### 4a. RED metrics (rate / errors / duration)
```promql
# Request rate
sum by (route) (
rate(<your-http-request-counter>{<label>="<value>"}[1m])
)
# Error rate
sum by (route) (
rate(<your-http-request-counter>{<label>="<value>",status=~"5.."}[1m])
) /
sum by (route) (
rate(<your-http-request-counter>{<label>="<value>"}[1m])
)
# Latency p95
histogram_quantile(0.95,
sum by (route, le) (
rate(<your-http-request-duration-bucket>{<label>="<value>"}[1m])
)
)
```
Generic metric name placeholders shown — replace with the
actual metric names from the customer's Prom. Discover them with:
```bash
gcx metrics query -d <prom-uid> 'group by (__name__) ({<label>="<value>"})' -o json
```
### 4b. Error logs
```logql
{<label>="<value>"} |= "error" | line_format ...
```
Filter by the k6 run window (`from` / `to`).
If the customer uses structured logging (JSON or logfmt), parse:
```logql
{<label>="<value>"} | json | level="error"
```
### 4c. Traces (if Tempo is configured)
```bash
# Find slow traces in the window
gcx traces query -d <tempo-uid> \
--query '{service.name="<value>" && duration > 1s}' \
--start <iso> --end <iso>
```
A representative trace from the slow window often explains *which*
downstream call is the bottleneck.
### 4d. Profiles (if Pyroscope is configured)
This is the high-value signal for CPU-bound bottlenecks. Be
careful to scope to the run window only:
```bash
gcx pyroscope query-profile -d <pyro-uid> \
--query '<profile-type>{<label>="<value>"}' \
--from <iso> --to <iso>
```
Look at the top frames. **Do not** assume what they mean — just
report them. The customer's engineers know their codebase; you
don't.
## Step 4½: verify absence before reporting it
A claim that a datasource has no data in the test window is a **strong claim**
that often drives architectural recommendations. Before making it, run **all
three** of these checks. If any one disagrees, you have a query bug, not data
absence:
1. **Label endpoint sanity check.** Run `gcx <product> labels -d <uid>` (or
`-l <key>` for a specific label) for the datasource. If the label endpoint
returns *any* values for the relevant key (e.g. `resource.service.name`
returns the service), the datasource has indexed data — your *query* is
what's wrong, not the datasource.
2. **Raw response, not parsed.** Re-run the same query **without** any `--json
<field>` filter and read the raw output. `gcx --json <field>` extracts a
specific top-level field; if you guessed the wrong field name, you'll get
`{"<field>": null}` and mistake it for emptiness. The hint `gcx` prints on
every call (`use --json list to discover fields, --json field1,field2 to
select`) is your prompt to do this. Discover fields first, filter after.
3. **Wider window.** Re-run with a window 10× as long (e.g. `--from now-24h`).
If still empty, the datasource is plausibly empty; if data appears, you had
a clock-skew, retention-edge, or time-zone bug.
Only after **all three** confirm absence is the finding "no data in datasource
X" valid. Otherwise the finding is "my query returned no results", which is
not the same thing. **Never** report a tracing / profile / log gap without
running these checks.
If both `gcx` and `mcp-grafana` are installed, an optional fourth check is to
re-run the same query through the other tool. Two independent JSON shapes
can't both be wrong the same way.
### Failure case to remember
In a past run of this skill the agent ran
`gcx traces query ... --json data` and got `{"data": null}` back. It treated
that as "Tempo has no traces" and wrote a finding labelled "tracing pipeline
silently broken". In reality the response field is `traces`, not `data`;
Tempo had full coverage and a representative slow trace would have pinpointed
the bottleneck root cause one level deeper than Pyroscope alone could. The
agent had already queried the label endpoint and received non-empty results
(check 1 above), which contradicted the absence claim — but didn't notice.
Don't let that happen again.
## Step 5: hand back specific evidence
Bad finding:
> "The backend was slow during stress."
Good finding:
> "During the stress test of W3 (2026-05-13 22:14-22:30 UTC), the
> `recommend` endpoint's p95 latency rose from 120ms at baseline
> to 1.4s at peak load. Correlating with Pyroscope (link), the
> top frame consumed 53% of CPU samples in the window. Customer
> engineers should investigate whether this code path can be
> optimised or moved off the hot loop."
Every finding gets:
- The k6 run identifier and window.
- The specific metric or log query (so the customer can reproduce).
- A Grafana panel link if a relevant dashboard exists.
- A neutral observation, not a fix recommendation.
## Tool selection (gcx vs mcp-grafana)
- **In-session, structured, single query:** prefer `mcp-grafana`.
- **Multiple queries scripted in shell, multi-context, CI:** prefer
`gcx`.
- **Tempo trace selectors:** mcp-grafana has richer selector
support.
Both are acceptable. Don't argue with the user's preferred tool.
## When the customer doesn't own the backend
Skip this entire workflow. The report should explicitly state:
> "Backend-side investigation was not performed because the
> customer does not own the backend. Findings are limited to
> what k6 can observe from the client side: response status,
> latency, body, and Web Vitals."
This is a perfectly valid outcome. Don't fabricate backend
findings from client-side signals.
hybrid-load-design.md 5.6 KB
# Hybrid load test design
Each test type ships as a hybrid: a **protocol scenario** that
drives the bulk of the load, plus a **single-VU browser scenario**
that measures Web Vitals under that load.
## Why hybrid
A protocol-only test measures backend throughput and latency well,
but says nothing about whether the **user-facing page** is still
responsive. A browser-only test measures Web Vitals correctly but
hits VU-count ceilings (browser VUs are expensive — typically
1 GB RSS per VU) long before you reach the backend's bottleneck.
Hybrid runs both: protocol VUs scale the load, the lone browser VU
acts as a "canary user" reporting LCP / INP / CLS / iteration
duration while the backend is stressed.
## Why one browser VU and not more
- One browser VU is enough to detect Web Vitals regressions caused
by backend load. The page's `time-to-LCP` will visibly degrade
when the backend slows.
- Adding more browser VUs roughly multiplies LG memory pressure
without improving signal quality.
- A second browser VU adds noise to a breakpoint test (timing
variance across pages obscures the cliff).
**Exception: breakpoint test omits the browser scenario entirely.**
The breakpoint is hunting protocol throughput; a single browser VU
mid-test adds noise without contributing.
## Scenario shape
```js
export const options = {
userAgent: USER_AGENT,
scenarios: {
protocol: {
executor: 'ramping-vus', // or constant-vus / ramping-arrival-rate
exec: 'protocolIteration',
// ... ramp specific to test type ...
},
browser: {
executor: 'constant-vus',
exec: 'browserIteration',
vus: 1,
duration: '<matches protocol duration>',
options: { browser: { type: 'chromium' } },
},
},
thresholds: { /* SLOs + per-endpoint + per-iteration + web vitals */ },
};
export function protocolIteration() { /* ... */ }
export async function browserIteration() { /* ... */ }
```
## Why one file per test type rather than a `LOAD_TYPE` dispatcher
A single `load.js` with `const LOAD_TYPE = __ENV.LOAD_TYPE` and a
big `optionsByType` lookup is tempting. The skill rejects that in
favour of six separate files. Reasons:
1. **Each `options` block is self-documenting.** When you open
`stress.js` you see immediately what the ramp does. No need to
trace through a dispatch table.
2. **Tuning is per-test-type.** When you adjust the stress ramp
from `0→50→0` to `0→80→0`, you change one file. The smoke
defaults don't accidentally shift.
3. **Cloud config differs per type.** When pushing to Grafana
Cloud k6, you often want different region distribution per
test type. Per-file `cloud { distribution: ... }` is clean.
4. **The agent runs one type at a time.** No real workflow runs
all six in one shell. Optimising for "all six in one file"
optimises a case that never happens.
5. **Diffability.** When you tune average.js, the git diff is
confined to that file. With the dispatcher, every tuning
shows up as a diff to the same file, obscuring history.
## Why no shared `tests/lib/`
The bundled templates duplicate the iteration body across:
- `protocol.js` (functional)
- `browser.js` (functional)
- `smoke.js` (load)
- `average.js` (load)
- `stress.js` (load)
- `spike.js` (load)
- `soak.js` (load)
- `breakpoint.js` (load, protocol body only)
Across one workflow, that's roughly 8 copies. The skill **prefers
this duplication** to extracting a shared helper. Reasons:
1. **Incident-review readability.** During a post-mortem you read
the failing test top-to-bottom. A file that imports four helpers
from `tests/lib/` requires jumping around to understand what
actually fired.
2. **Threshold tags are per-file.** The functional `protocol.js`
uses `expect()`. The load `protocol` scenario uses `check()` +
`tags`. A shared helper has to abstract over both, which adds
complexity that doesn't repay itself.
3. **`sleep()` calls differ.** Functional tests don't sleep. Load
tests insert randomised think-time between user actions. The
sleep points are part of the workflow's identity in the load
test.
4. **Browser iterations are async; protocol are sync.** Any shared
helper has to be one or the other. Helpers that try to be both
end up as awkward thin wrappers.
5. **Most tuning is per-file.** When you adjust the stress thresholds
after seeing results, you touch `stress.js`. A shared helper
reduces lines of diff but increases coupling.
The argument against duplication is "DRY". For perf test scripts,
the value of being able to *read one file and understand the
test* outweighs the cost of duplicating a 30-line iteration body
across six load files.
## What may be shared
A small set of constants is acceptable to share via `__ENV` or a
single top-of-file include:
- `BASE_URL`, `USER_AGENT`, test credentials — read from `__ENV`.
- A `restrictions` payload or canonical request body if it's
re-used identically — declare once at the top of each file (not
imported from a sibling).
What is **not** shared:
- The iteration body (sequence of `http.*` calls + `check()`).
- The threshold dictionary.
- The scenario options.
## Adding a new workflow later
The duplication makes adding a new workflow mechanical:
```bash
cp -R tests/workflow.template tests/wN-<short-name>
# Then for each .js in the new folder:
# - Replace <WORKFLOW_PLACEHOLDER> with wN-<short-name>
# - Edit the iteration body for the new user actions
# - Edit the per-endpoint thresholds for the new endpoints
```
A shared helper structure would require breaking the abstraction
to add a workflow with different timing or different endpoints,
which is most workflows.
lg-monitoring.md 4.1 KB
# Load-generator monitoring (LG sidecar)
## Why this exists
A load generator that runs out of CPU, memory, or NIC bandwidth
**silently throttles its own request rate**. The k6 results then
show:
- Lower-than-expected request rate (looks like the server is slow).
- Higher-than-expected latency (because k6 itself is slow to enqueue
the next request, not because the response is slow).
- "Iterations interrupted" with cryptic timeout messages.
Without an LG monitor running alongside k6, you cannot distinguish
"server is slow" from "laptop is at 100% CPU and k6 is queueing
its own work".
**Rule: any test type beyond smoke must run with the monitor
sidecar.** The smoke is short enough that LG saturation is
unlikely; everything else can hit it.
## What the sidecar samples
At a fixed interval (default 5s), one CSV row containing:
| Column | Why |
|---------------------------|-----------------------------------------|
| timestamp_iso, uptime_s | timeline |
| sys_cpu_user/sys/idle | system-wide CPU; idle is the headline |
| k6_cpu / k6_mem / k6_rss | the k6 process itself |
| chrome_cpu_total / mem / rss / proc_count | browser VU footprint |
| nic_rx_bytes / nic_tx_bytes / per_s | network throughput |
The post-run summary computes min/avg/max for the headline columns
and emits a verdict.
## Verdict thresholds
The bundled `run-with-monitor.sh` emits:
- **OK**: minimum `sys_cpu_idle ≥ 30%`. LG had plenty of headroom.
- **NOTE**: 10% ≤ min idle < 30%. LG had headroom but not much.
- **WARNING**: min idle < 10%. LG was saturated; k6 numbers are
unreliable.
When you see WARNING, treat the run as **inconclusive** and either:
- Reduce VUs and re-run.
- Move the test type to cloud (revisit elicitation §1).
- Split the test across multiple LGs.
Do **not** report findings derived from a WARNING run.
## How chromium is detected
The sidecar identifies test-spawned Chromium processes by the
`--headless` flag on their command line. The user's regular
Chrome (browsing real websites in another window) does **not**
have that flag, so it is excluded from the chromium-process count.
If you launch k6/browser with `K6_BROWSER_HEADLESS=false` for
debugging, the sidecar will not see the chromium processes and
the chromium columns will be empty.
## Cross-platform notes
The bundled script uses `uname -s` to branch between macOS and
Linux command syntax:
- **CPU**: macOS uses `top -l 1 -s 0`; Linux uses `top -bn1` or
`mpstat 1 1` if available.
- **NIC**: macOS uses `netstat -ib`; Linux reads
`/proc/net/dev` or `ip -s link`.
- **Default route**: macOS `route get default`; Linux `ip route
show default`.
Windows is not supported directly — run the skill from WSL2 instead.
## Reading a monitor CSV
If you want to drill in past the summary:
```bash
# Quick view of saturation timeline
awk -F, 'NR==1{print; next} $5 != "" {print $1, $5}' \
/tmp/perf-lg-monitor/wN-stress-*.csv
# Max chromium RSS over the run
awk -F, 'NR>1 && $11 != "" {print $11}' \
/tmp/perf-lg-monitor/wN-soak-*.csv | sort -n | tail -1
```
For a long soak run, plotting `k6_rss_kb` over time is more
revealing than the min/avg/max summary — a steady upward slope is
the signal of accumulation (whether real leak or client-side
metric accumulation; see gotchas).
## Limitations
- Process metrics are sampled, not integrated. A short CPU spike
between samples can be missed. Lower `INTERVAL` (e.g. `INTERVAL=2`)
for spike tests where bursts matter.
- NIC bytes are measured at the interface level — VPN tunnels and
loopback are not visible. If you run k6 against `localhost`, the
NIC counters will be ~0.
- The sidecar adds <1% overhead but is not free. Don't extrapolate
millisecond-precision timings from sidecar-instrumented runs.
## Integration with k6 cloud runs
The sidecar only helps for **local** runs. Cloud k6 runs LGs in
Grafana's infrastructure; the LG monitor doesn't see them.
For cloud runs:
- LG load is automatically tracked by Grafana Cloud k6.
- Inspect the LG utilisation panels in the cloud test run UI to
confirm cloud LGs themselves were not the bottleneck.
local-vs-cloud.md 5.2 KB
# Local vs Grafana Cloud k6
The skill's per-customer decision (recorded in `runbook.md` during
elicitation) determines where each of the six test types runs. This
doc is the reference for the tradeoffs and the framing.
## The framing
**Local is for validation. Cloud is for scale.**
- Local k6 confirms the *script* behaves correctly. All thresholds
compile, all assertions hold, no scripting errors. A passing
local smoke is a precondition for trusting cloud results.
- Cloud k6 confirms *the system under test* behaves correctly
under realistic load. A single laptop usually cannot drive
enough load to reach a production website's ceiling.
## Why a laptop often can't reach the ceiling
Typical limits a laptop hits before the SUT does:
- **CPU.** k6 itself uses CPU per VU; chromium uses ~1 core per
browser VU. 50 protocol VUs + 1 browser VU often pegs an 8-core
laptop.
- **Memory.** Each browser VU consumes ~1 GB RSS. Beyond 2-3
browser VUs you hit swap and timings become meaningless.
- **NIC.** Saturating a 1 Gbit link from a single laptop is
possible but rarely happens before CPU does.
- **TCP socket limits.** Many OSes default to ~28k ephemeral
ports. At very high request rates you exhaust the pool.
The LG sidecar (see `lg-monitoring.md`) tells you which of these
you've hit.
A cloud LG fleet of 10 nodes lifts all of these limits by ~10×.
For most public websites, that's enough to find the cliff.
## The cost model
Grafana Cloud k6 bills in **virtual user hours (VUh)**:
- 1 protocol VU running for 1 hour = 1 VUh.
- 1 browser VU running for 1 hour = **10 VUh.**
Free-tier limits are finite and change over time. Always check
the Grafana Cloud k6 UI or `gcx` for current limits before
running long tests.
Budget-hostile test types:
| Test type | VUh estimate (defaults) | Risk |
|-------------|--------------------------------|-----------------|
| smoke | 3 VUs × 1m + 1 br × 1m ≈ 0.22 VUh | safe |
| average | 20 × 14m + 1 br × 14m ≈ 7 VUh | safe |
| stress | 50 × 20m + 1 br × 20m ≈ 20 VUh | moderate |
| spike | 100 × 2m + 1 br × 2m ≈ 3.6 VUh | safe |
| soak | 10 × 70m + 1 br × 70m ≈ 23 VUh | **moderate-high** (browser VU runs long) |
| breakpoint | up to maxVUs × 20m, no browser ≈ 30-100 VUh | **high** (variable) |
These are starting defaults. A 100-VU stress for 60 minutes is
~150 VUh; do it twice and you've used a typical small-tier budget.
## Decision matrix the customer typically lands at
| Test type | Common choice |
|-------------|---------------------------------------------------------|
| smoke | local (validation, free, fast) |
| average | cloud (real measurement; LG is unlikely to saturate) |
| stress | cloud (LG ceiling matters; need to reach the cliff) |
| spike | local or cloud — depends on target rate |
| soak | local (no fleet cost) or cloud (real-LG fidelity) |
| breakpoint | cloud (LG ceiling materially affects the result) |
But every cell is the customer's call. Some customers run
everything local; some run everything cloud. Don't override the
elicitation answer.
## The validation-then-measure flow
For any test type assigned to cloud:
1. **Local smoke** (always, even if smoke itself is cloud-bound).
Catches scripting errors cheaply.
2. **Local short run** of the assigned test type (e.g. 2-minute
subset of stress). Confirms thresholds compile and don't fire
spuriously.
3. **Cloud run** of the full test type.
4. **Analyse** the cloud run via the Grafana Cloud k6 UI or via
`gcx` for scripted access.
Skipping step 2 is a common cause of "10 VUh burned for a typo".
## Pushing to cloud
```bash
# After `k6 cloud login` succeeds:
k6 cloud run tests/wN-<short-name>/stress.js
```
The k6 binary will:
- Upload the script.
- Provision LG capacity per `options.cloud.distribution` (if set)
or use the default region.
- Stream results back to your terminal.
- Print a final summary with a URL to the cloud test run.
Use the URL in the final report's Evidence section.
## When cloud results disagree with local
It happens. Reasons:
- **LG was saturated locally.** Cloud's headroom reveals the real
ceiling.
- **Network path differs.** Cloud LGs may have lower latency to a
CDN edge than your laptop does.
- **Geographic distribution.** Cloud `options.cloud.distribution`
spreads VUs across regions; local is a single point.
- **IP allow-lists / WAFs.** Cloud LG IPs may be allow-listed
differently from your laptop.
When in doubt: **trust cloud for measurement, trust local for
script validation.** That's the whole framing.
## Tool preference for cloud
If `gcx` is configured for Grafana Cloud k6, prefer it for:
- Listing recent test runs.
- Programmatic threshold queries.
- Downloading run summaries.
Use `mcp-k6` (if available) for in-session script work tied to a
cloud run.
For diagnosing a failed cloud test, open the run in the Grafana
Cloud k6 UI, inspect the thresholds tab, the per-metric timeline,
and any failed checks; then correlate with backend signals per
`grafana-investigation.md` if the user owns the backend.
recording-with-playwright.md 5.6 KB
# Recording with Playwright
Per workflow, you produce one Playwright recorder
(`recordings/scripts/wN-<short-name>.js`) that captures a HAR. The HAR is then
converted to a k6 protocol script via `har-to-k6`.
## Recorder template anatomy
The bundled template has four critical parts:
### 1. Headless Chromium with a real Chrome UA
```js
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36',
recordHar: { /* see below */ },
});
```
**Why a real UA:** the default headless UA includes the string
`HeadlessChrome`, which triggers bot-blocking on many production
sites. Set a real Chrome UA on both the recorder (`userAgent` in
`browserContext`) and the k6 scripts (`options.userAgent`).
### 2. `recordHar.urlFilter` — the critical regex
```js
recordHar: {
path: HAR_PATH,
mode: 'full',
content: 'embed',
urlFilter: /^https?:\/\/(target-host\.example|localhost)(:\d+)?\//,
},
```
**Why:** third-party traffic from the target site (RUM agents,
error reporters, ad networks, analytics, …) pollutes:
- the recorded request count (inflating k6's apparent load),
- per-endpoint thresholds (third-party endpoints have no relation
to your SLOs),
- the HAR file size (10-100× bloat is common).
`urlFilter` accepts a regex or string. **Always use a regex** that
allow-lists the target host(s) only.
### 3. Belt-and-braces `context.route`
```js
await context.route('**', (route) => {
if (isAllowedHost(route.request().url())) return route.continue();
return route.abort();
});
```
`recordHar.urlFilter` filters at HAR-write time but the browser
still **sends** the requests. The `context.route` filter aborts at
the network layer so:
- The third party doesn't get test traffic (politeness, and avoids
polluting their dashboards).
- Bandwidth during recording is minimised.
Both filters are needed. `route.abort` alone leaves `status: -1`
entries in the HAR (har-to-k6 then generates broken k6 code).
### 4. Hydration-signal wait
Single-page apps render some markup before client JS hydrates and
attaches event handlers. If your recorder clicks a button before
hydration, the click does nothing.
```js
await page.goto(BASE_URL, { waitUntil: 'load' });
// Wait for the post-hydration sentinel. Pick a selector that ONLY
// exists once the SPA has booted — typically an interactive element
// (button, link) that is rendered by the framework, not the SSR.
const sentinel = page.locator('button[name="primary-action"]');
await sentinel.waitFor({ state: 'visible' });
```
`waitUntil: 'load'` is necessary but not sufficient — the DOM is
ready before JS has wired up handlers. The sentinel locator
guarantees hydration completed.
## The full recording pipeline
```
recordings/scripts/wN-<short-name>.js (Playwright -- source of truth)
├── node recordings/scripts/wN-<short-name>.js ⟶ recordings/har/wN-<short-name>.har
│ └── npx har-to-k6 wN-<short-name>.har ⟶ tests/wN-<short-name>/from-har.js (raw)
│ └── hand cleanup ⟶ tests/wN-<short-name>/protocol.js (final)
└── 5-step manual conversion ⟶ tests/wN-<short-name>/browser.js (final)
```
The 5-step manual conversion is in
`references/functional-tests.md`.
## How to spot a polluted HAR
After `node recordings/scripts/wN-<short-name>.js`:
```bash
# Count entries by host
jq '.log.entries | map(.request.url) | group_by(. | capture("//(?<h>[^/:]+)").h) | map({host: .[0] | capture("//(?<h>[^/:]+)").h, count: length})' recordings/har/wN-<short-name>.har
```
If you see any host other than your allow-listed target, the
`urlFilter` regex needs widening or tightening.
## How to spot missing hydration
After `npx har-to-k6 ... -o from-har.js`, run the script once:
```bash
k6 run --vus 1 --iterations 1 tests/wN-<short-name>/from-har.js
```
If you see the homepage in the request list but **none** of the
subsequent API calls fired by client JS, the recorder clicked
before hydration. Add a wait on a post-hydration sentinel and
re-record.
## Re-recording when the app changes
Re-record when:
- The bundled hash-named static assets change paths (e.g. SvelteKit
rebuilds change `/_app/immutable/nodes/4.<hash>.js`). The
protocol test will fail with a 404 on the asset, which is the
intended signal.
- The API or workflow changes the recorded sequence of requests.
- You want a fresh HAR for analysis (e.g. comparing before/after a
backend change).
```bash
# 1. Re-run the recorder
node recordings/scripts/wN-<short-name>.js
# 2. Regenerate the raw k6 script
npx har-to-k6 recordings/har/wN-<short-name>.har -o tests/wN-<short-name>/from-har.js
# 3. By hand: bring any new asset paths or request sequences into
# tests/wN-<short-name>/protocol.js.
# 4. Verify
./tests/run-all.sh
```
## Why HARs are committed to git
- Reproducibility: anyone reading the repo sees what was captured.
- Diff-ability: when the app is rebuilt, `git diff` on the HAR
shows what changed at the protocol layer.
- Small enough: typical HAR is 300 KB - 2 MB; usually fine to
commit. If your app produces > 10 MB HARs, narrow the
`urlFilter` further (you're probably capturing CDN assets you
don't need).
## Tool preference
If `mcp-k6` is configured, prefer its Playwright capture and
Playwright→k6/browser migration tools. They handle:
- Real UA selection.
- Hydration-wait scaffolding.
- Selector extraction.
This skill's hand-written approach is the **fallback** when
`mcp-k6` isn't available, and the **specification** for what
`mcp-k6`'s output should resemble.
reporting.md 5.8 KB
# Final report template
Fill in this template at the end of the engagement. Hand the
filled-in report to the user as the final artefact.
Be specific. Every claim cites evidence. No hand-wavy summaries.
---
## Report template
```markdown
# Performance test report — <site>
**Date**: <YYYY-MM-DD>
**Target**: <https://example.com>
**Tester**: <agent or human name>
## Summary
- **Workflows tested**: wN-<short-name>, …
- **Test types run**:
- smoke — local ✓ / cloud N/A
- average — local ✓ / cloud ✓
- stress — local ✓ / cloud ✓
- spike — local ✓ / cloud N/A
- soak — local ✓ / cloud N/A
- breakpoint — local ✓ / cloud ✓
- **Backend investigated**: yes (Grafana access via <url>) / no
- **Outcome**: <pass / pass-with-findings / fail>
## SLOs and threshold results
| SLO | Result | Notes |
|--------------------------------------------------|-----------|----------------------|
| http_req_failed rate < 0.01 | PASS / FAIL | <window or n/a> |
| http_req_duration p(95) < 500ms | PASS / FAIL | <window or n/a> |
| http_req_duration{name:CreateOrder} p(95) < 800ms| PASS / FAIL | failed at <window> |
| iteration_duration{scenario:browser} p(95) < 10s | PASS / FAIL | |
| browser_web_vital_lcp p(95) < 2500ms | PASS / FAIL | |
| browser_web_vital_inp p(95) < 200ms | PASS / FAIL | |
| browser_web_vital_cls p(95) < 0.1 | PASS / FAIL | loosened to <0.2 for W1 — see Finding N |
| iteration_completed{scenario:browser} rate > 0.99| PASS / FAIL | |
## Findings
Ordered by severity. Each finding has: observation, evidence,
suggested next step (neutral — for the user's team to evaluate).
### Finding 1 — <one-line summary>
**Severity**: critical / high / medium / low / informational
**Observation**:
During the stress test of W3 (started 2026-05-13 22:14 UTC, ended
22:30 UTC), the `GetRecommendation` endpoint's p(95) latency rose
from 120ms at baseline to 1.4s at peak load (50 VUs). The
threshold `http_req_duration{name:GetRecommendation} p(95) <
1000ms` failed.
**Evidence**:
- k6 summary: `/tmp/perf-lg-monitor/w3-anon-recommend-stress-20260513-221400.k6.log`
- LG monitor: `/tmp/perf-lg-monitor/w3-anon-recommend-stress-20260513-221400.csv`
(sys_cpu_idle stayed ≥ 51% throughout — LG was not the
bottleneck)
- Grafana panel: <link> showing backend latency in the same
window
- Pyroscope: <link> showing <top frame> consumed 53% of CPU
samples
**Suggested next step**:
Customer engineers should investigate whether the
`<top frame from Pyroscope>` code path can be optimised or
moved off the hot loop. Without that, the system will not
meet the GetRecommendation SLO above ~40 concurrent users.
### Finding 2 — …
(repeat the structure)
## Loosened or skipped thresholds
If you raised any threshold from the default, list each here with
the cause. Never silently loosen.
| Threshold | Original | Loosened to | Cause |
|--------------------------------------|----------|-------------|----------------------------------------|
| browser_web_vital_cls{workflow:w1} | < 0.1 | < 0.2 | Deterministic CLS=0.15 in ratings widget; team accepted, will not fix in test window |
## Evidence index
All file paths and Grafana URLs referenced in findings.
### k6 outputs
- `/tmp/perf-lg-monitor/w1-*-{smoke,average,stress,spike,soak}-*.k6.log`
- `/tmp/perf-lg-monitor/w2-*-{smoke,average,stress,spike,soak}-*.k6.log`
- …
### LG monitor CSVs
- `/tmp/perf-lg-monitor/*.csv`
### Cloud k6 runs
- <Grafana Cloud k6 URL> — w3 stress, 2026-05-13
- <Grafana Cloud k6 URL> — w3 breakpoint, 2026-05-13
### Grafana investigation
- Datasource UIDs used: prom=<uid>, loki=<uid>, tempo=<uid>, pyroscope=<uid>
- Service labels: `service_name="<value>"`
- Run windows correlated:
- w3 stress: 2026-05-13 22:14-22:30 UTC
- w3 breakpoint: 2026-05-13 23:01-23:21 UTC
## Methodology notes
- Test suite committed at: <repo / path>
- k6 version: <e.g. v2.0.1>
- Node.js version: <e.g. 23.0.0>
- LG host: <hostname / spec — e.g. MacBook Pro M2 Max, 32GB>
- LG sidecar interval: 5s (default)
- Hybrid scenario shape: 1 protocol scenario + 1 browser VU
(except breakpoint, protocol-only)
- Threshold strategy: global SLO + per-endpoint tags + per-iteration
+ LCP/INP/CLS Web Vitals + custom action Trend
(see <skill reference>)
## Suggested next steps (overall)
- Address Findings 1-N in priority order.
- Re-run stress and breakpoint after each fix to measure
improvement.
- Consider adding the SLO thresholds in this report to your CI
pipeline using `k6 run --threshold=...` so regressions surface
before deploy.
- Schedule a quarterly re-run to detect drift.
```
---
## Writing rules
### Be specific
- "Latency increased" → ❌
- "GetRecommendation p(95) rose from 120ms to 1.4s between 22:14
and 22:24 UTC" → ✓
### Cite evidence
Every numeric claim has a file path or URL. If you can't cite it,
don't claim it.
### Stay neutral
The skill **reports**, doesn't **recommend code**. "Customer should
fix X by doing Y" — never. "Customer should investigate whether X
can be optimised" — yes.
### Don't fabricate
If backend access was not available, the "Backend investigated"
flag is `no` and there are no Pyroscope / Tempo evidence cites.
Don't paper over the gap with client-side speculation.
### Severity guide
- **critical**: SLO failed, user-facing impact, blocker for
production.
- **high**: SLO failed, scope-limited to a specific workflow.
- **medium**: threshold trending toward fail; near the cliff.
- **low**: cosmetic or rare-edge-case behaviour.
- **informational**: observation, not a problem.
When in doubt, use a lower severity. Inflating severity erodes
the report's credibility.
slo-design.md 8.4 KB
# SLO design and threshold strategy
This skill's bundled templates use a four-layer threshold strategy:
1. **Global SLOs** — overall error rate + latency.
2. **Per-endpoint thresholds** — tag every protocol request,
threshold per tag.
3. **Per-iteration thresholds** — the user-perceived workflow time.
4. **Web Vitals + custom action Trend** — page responsiveness under
load.
This document explains the rationale for each layer and how to tune
them for the user's stated SLOs.
## Layer 1: Global SLOs
```js
http_req_failed: ['rate<0.01'], // < 1% requests fail
http_req_duration: ['p(95)<500'], // p95 across all requests < 500ms
checks: ['rate>0.99'], // > 99% of in-iteration checks pass
```
These are starting defaults. Tune to the user's Q6 answers from
the elicitation script. Common adjustments:
- Public website with heavy CDN: `http_req_duration p(95) < 300ms`.
- API gateway with downstream calls: `http_req_duration p(95) <
800ms`.
- High-error-budget app: `http_req_failed rate < 0.05`.
## Layer 2: Per-endpoint thresholds
The global `http_req_duration p(95) < 500` is dominated by the
fastest, most-frequent endpoints (typically static assets and
small JSON endpoints). The slow, critical endpoints — the ones that
hurt users most — hide in the aggregate.
**Tag every protocol request:**
```js
http.get(`${BASE_URL}/api/recommend`, {
tags: { name: 'GetRecommendation' },
});
http.post(`${BASE_URL}/api/order`, body, {
tags: { name: 'CreateOrder' },
});
```
**Then threshold per tag:**
```js
thresholds: {
// global SLOs
http_req_failed: ['rate<0.01'],
http_req_duration: ['p(95)<500'],
checks: ['rate>0.99'],
// per-endpoint
'http_req_duration{name:GetRecommendation}': ['p(95)<1000', 'p(99)<1500'],
'http_req_duration{name:CreateOrder}': ['p(95)<800'],
'http_req_duration{name:GetCatalogue}': ['p(95)<400'],
'http_req_duration{name:GetConfig}': ['p(95)<300'],
},
```
Rule of thumb:
- One tag per business action that has its own SLO.
- Static assets and incidental fetches (images, fonts) do not need
their own tag — they're already covered by the global threshold.
- Tag-name convention: `<HTTP-verb><Resource>` PascalCase, no
hyphens, no slashes. `GetRecommendation`, not `get-/recommend`.
## Layer 3: Per-iteration thresholds
```js
'iteration_duration{scenario:browser}': ['p(95)<10000'], // 10s end-to-end
```
This is the **user-perceived** workflow time. Set it to roughly
**2× the smoke median** of `iteration_duration{scenario:browser}`.
Smoke gives you a baseline; the load tests' p95 should stay near
the smoke median × 2 even under stress.
The skill recommends two iteration thresholds:
```js
'iteration_duration{scenario:browser}': ['p(95)<10000'], // smoke + load
'iteration_completed{scenario:browser}': ['rate>0.99'], // < 1% throws
```
`iteration_completed` is a custom Rate — see Layer 4 / async section.
## Layer 4: Web Vitals + custom action Trend
### Web Vitals (browser scenario only)
The skill restricts Web Vitals to **LCP, INP, CLS**:
```js
browser_web_vital_lcp: ['p(95)<2500'],
browser_web_vital_inp: ['p(95)<200'],
browser_web_vital_cls: ['p(95)<0.1'],
```
These are Google's "good" thresholds. The skill explicitly drops:
- **FCP** — superseded by LCP; rarely the first regression to fire.
- **TBT** — useful for lab synthetics but noisy under load.
- **TTFB** — measure server-side via `http_req_duration` instead.
**Loosening CLS for known accepted issues:** some real apps have a
deterministic layout shift (e.g. a ratings widget that re-renders
once data loads). If the team has chosen not to fix it, you may
raise the threshold to `< 0.2` — **but flag it in the report**.
Never silently raise a threshold.
### Custom action Trend (for the slow user action)
Web Vitals measure *initial render*. They miss post-click latency
for actions like "submit form", "compute recommendation", "load
next page". Add a custom Trend.
**In async (browser) code, `group()` does NOT work reliably.** k6's
`group()` does not wrap awaited code correctly; the group_duration
will not match what you intended. Use `performance.mark()` +
`performance.measure()` inside `page.evaluate()`:
```js
import { Trend } from 'k6/metrics';
const timeToResult = new Trend('time_to_result', true);
await page.evaluate(() => performance.mark('action-start'));
await Promise.all([
page.waitForResponse(r => r.url().includes('/api/action')),
button.click(),
]);
await resultLocator.waitFor({ state: 'visible' });
const ms = await page.evaluate(() => {
performance.mark('action-end');
return performance.measure('action', 'action-start', 'action-end').duration;
});
timeToResult.add(ms);
```
**Threshold:**
```js
time_to_result: ['p(95)<3000'],
```
**A threshold on a metric with zero samples passes vacuously.** If you
keep `time_to_result: ['p(95)<3000']` but never call `timeToResult.add()`
(the templates ship that call commented out), k6 reports the threshold
green while measuring nothing — the same empty-metric footgun described
for `checks` in `gotchas.md`. When you adapt a load template, either wire
up the `performance.mark`/`measure` block so the Trend gets samples, or
remove the threshold. Never ship it empty and trust the green.
### Custom Rate for browser iteration completion
Browser iterations throw on locator timeouts, evaluate errors,
network failures. Without instrumentation, those are invisible in
the threshold report (a thrown iteration is "interrupted" in k6's
summary, not "failed").
Wrap every browser iteration:
```js
import { Rate } from 'k6/metrics';
const iterationCompleted = new Rate('iteration_completed');
export async function browserIteration() {
const page = await browser.newPage();
let success = true;
try {
// ... workflow body ...
} catch (e) {
success = false;
console.error(`browser iteration failed: ${e?.message || e}`);
throw e; // re-throw so k6 also marks iteration interrupted
} finally {
iterationCompleted.add(success);
await page.close();
}
}
```
**Threshold:**
```js
'iteration_completed{scenario:browser}': ['rate>0.99'],
```
## `group()` for sync (protocol) code
In **protocol** scenarios (synchronous, no `await`), `group()`
*does* work and produces a usable `group_duration` metric:
```js
import { group } from 'k6';
export function protocolIteration() {
group('checkout', () => {
http.get(`${BASE_URL}/cart`);
http.post(`${BASE_URL}/api/checkout`, body);
http.get(`${BASE_URL}/order-confirmation`);
});
}
// threshold:
'group_duration{group:::checkout}': ['p(95)<2000'],
```
Use this for sub-iteration timing of a multi-step flow inside the
protocol body. Don't try it in browser code.
## Threshold layering summary
| Layer | What | Where applied |
|------------------|-----------------------------------|--------------------------|
| Global | `http_req_failed`, aggregate p95 | All non-breakpoint types |
| Per-endpoint | `http_req_duration{name:...}` | All non-breakpoint types |
| Per-iteration | `iteration_duration{scenario:browser}` | All non-breakpoint types |
| Web Vitals | LCP / INP / CLS | All non-breakpoint types |
| Custom action | `time_to_*` Trend | All non-breakpoint types |
| Iteration health | `iteration_completed` Rate | All non-breakpoint types |
| Group duration | `group_duration{group:::...}` | Where sync protocol flow needs sub-timing |
For **breakpoint**, thresholds switch to abort-on-fail signals:
```js
thresholds: {
http_req_failed: [{ threshold: 'rate<0.05', abortOnFail: true,
delayAbortEval: '30s' }],
http_req_duration: [{ threshold: 'p(95)<2000', abortOnFail: true,
delayAbortEval: '30s' }],
checks: ['rate>0.95'],
},
```
The point of breakpoint is to *find* where it breaks; abort-on-fail
stops the run at the cliff. See `test-types.md`.
## Tuning workflow
1. Start with the template defaults.
2. Run smoke and **read the actual results** for each threshold.
3. Adjust thresholds to be **2× the smoke p95** for non-critical
endpoints, and to the user's stated SLO for critical ones.
4. Run average and stress; expect some thresholds to fail under
stress — that's the whole point.
5. After all test types have run, the failing thresholds become
the findings in the final report.
Don't loosen thresholds to make tests pass. Either:
- Confirm with the user that the SLO has shifted (and document it).
- Or report the failure and stop.
test-types.md 7.3 KB
# Test types
Six test types, one file per type, all hybrid except breakpoint.
| Type | Purpose | Executor | Default ramp |
|-------------|----------------------------------------|----------------------|------------------------------|
| smoke | sanity check the script + thresholds | constant-vus | 3 VUs × 1m |
| average | expected production load | ramping-vus | 0→20→0 over 14m |
| stress | beyond expected, find the cliff | ramping-vus | 0→50→0 over 20m |
| spike | sudden VU jump, check recovery | ramping-vus | 0→100→0 over 2m |
| soak | sustained load, find leaks / drift | ramping-vus | 0→10→0 over 70m |
| breakpoint | ramping arrival rate, find the ceiling | ramping-arrival-rate | 5/s→500/s over 20m, abortOnFail |
Defaults are starting points. Always tune after smoke.
## smoke
Goal: confirm the script behaves correctly under production-like
but trivially small load. **Always run before any other test
type.** If smoke fails, fix the script before scaling.
```js
scenarios: {
protocol: {
executor: 'constant-vus',
exec: 'protocolIteration',
vus: 3, duration: '1m',
},
browser: { executor: 'constant-vus', vus: 1, duration: '1m',
exec: 'browserIteration',
options: { browser: { type: 'chromium' } } },
},
thresholds: { /* full SLO + per-endpoint + iteration + web vitals */ },
```
A passing smoke means: thresholds compile, the script doesn't error,
all assertions hold at low load. **Smoke is not a measurement.**
## average
Expected production load. Tune `target` VUs to match the customer's
typical concurrent user count.
```js
protocol: {
executor: 'ramping-vus',
exec: 'protocolIteration',
startVUs: 0,
stages: [
{ duration: '2m', target: 20 }, // ramp up
{ duration: '10m', target: 20 }, // hold
{ duration: '2m', target: 0 }, // ramp down
],
},
browser: { /* constant 1 VU for the full 14m */ },
```
Pass criteria: every SLO threshold holds.
## stress
Beyond expected load. Goal: find where SLOs start to break.
```js
protocol: {
executor: 'ramping-vus',
exec: 'protocolIteration',
startVUs: 0,
stages: [
{ duration: '5m', target: 50 },
{ duration: '10m', target: 50 },
{ duration: '5m', target: 0 },
],
},
```
Expected outcome: some thresholds fail. The **specific** thresholds
that fail tell you which part of the system is the bottleneck.
Report each failure with its tag (which endpoint), peak VU count,
and timestamp.
## spike
Sudden jump in VUs; goal is to verify the system recovers.
```js
protocol: {
executor: 'ramping-vus',
exec: 'protocolIteration',
startVUs: 0,
stages: [
{ duration: '30s', target: 100 }, // spike
{ duration: '1m', target: 100 }, // hold at peak
{ duration: '30s', target: 0 }, // drop
],
},
```
What to look for:
- During the spike: do `http_req_failed` and latency stay within
acceptable bounds? (Some degradation is expected.)
- After the drop: does the system return to baseline?
- Cold caches, connection pool warmup, autoscaler latency — all
surface here.
## soak
Sustained moderate load over a long window. Goal: find memory
leaks, connection drift, scheduled-job interference, cache
eviction patterns.
```js
protocol: {
executor: 'ramping-vus',
exec: 'protocolIteration',
startVUs: 0,
stages: [
{ duration: '5m', target: 10 },
{ duration: '60m', target: 10 },
{ duration: '5m', target: 0 },
],
},
```
What to look for:
- Is `iteration_duration` flat, or trending up?
- Is k6's RSS (LG monitor) climbing without bound? See gotchas:
the climb may be client-side metric accumulation, not a real
leak. Verify against backend metrics before reporting.
- Are there periodic spikes (cron jobs, GC, log rotations)?
**Soak is the most likely test type to exhaust Grafana Cloud k6
budget.** Confirm with the user before pushing to cloud.
## breakpoint
Find the ceiling. **Protocol-only** (no browser scenario — adds
noise to the signal).
```js
scenarios: {
protocol: {
executor: 'ramping-arrival-rate',
exec: 'protocolIteration',
startRate: 5,
timeUnit: '1s',
preAllocatedVUs: 50,
maxVUs: 500,
stages: [{ duration: '20m', target: 500 }],
},
},
thresholds: {
http_req_failed: [{ threshold: 'rate<0.05', abortOnFail: true,
delayAbortEval: '30s' }],
http_req_duration: [{ threshold: 'p(95)<2000', abortOnFail: true,
delayAbortEval: '30s' }],
checks: ['rate>0.95'],
},
```
The `abortOnFail` thresholds stop the run once SLOs break. The
`delayAbortEval` window prevents instantaneous fluctuations from
triggering an abort prematurely.
Read the final iteration rate / arrival rate at the abort point —
that's the breakpoint. Document it in the report.
**Why arrival rate, not VUs:** the cliff is in **requests per
second**, not in concurrent users. VU-based ramps are bounded by
iteration duration; if iterations slow down, VUs back off and you
never reach the cliff. `ramping-arrival-rate` injects requests at
a fixed schedule regardless of iteration speed.
**Two ways the arrival-rate advantage gets silently lost — avoid both:**
- **Think-time sleep in the iteration body.** Every started iteration
holds a VU until it finishes. A 1-4s `sleep()` (the think-time the
other test types use) makes each iteration last ~2.5s, so one VU
serves only ~0.4 iters/s. The breakpoint body must run requests
back-to-back with **no** think-time. Think-time belongs in
average/stress/soak, not breakpoint.
- **`maxVUs` set below `target_rate × iteration_seconds`.** When k6
runs out of VUs it logs `Insufficient VUs, reached N active VUs and
cannot initialize more` and emits `dropped_iterations`; the achieved
rate plateaus from VU exhaustion, not from the backend. If you see
those messages, the run found *your VU ceiling*, not the server's —
raise `maxVUs` (and confirm there's no stray think-time) and re-run.
## When to use each
Phase the test types as the project matures:
1. **Always start with smoke.** Until smoke is green, nothing else
is meaningful.
2. **Run average next** to confirm SLOs hold at production load.
3. **Run stress** to find the cliff and get the first set of
findings.
4. **Run spike** if the customer cares about traffic surges
(launches, marketing campaigns, news cycles).
5. **Run soak** before any deployment that introduces persistent
state (caches, connection pools, in-memory caches).
6. **Run breakpoint** when you want a single number to report:
"system handles X req/s before degrading".
## Local vs cloud per test type
Decided per-customer in workflow elicitation. The skill does **not**
hardcode this. See `local-vs-cloud.md`.
A typical decision matrix the customer may end up at:
| Test type | Common choice |
|-------------|----------------------------------------|
| smoke | local (validation) |
| average | cloud (real measurement) |
| stress | cloud (reach the ceiling) |
| spike | local OR cloud (depends on target rate)|
| soak | local (cheap) OR cloud (real LGs) |
| breakpoint | cloud (LG ceiling matters) |
But every one of these is the customer's call.
workflow-elicitation.md 6.8 KB
# Workflow elicitation — verbatim question script
Read the questions below to the user **before scaffolding anything**.
Capture answers in a `runbook.md` in the target project directory.
Every later step depends on these answers.
If the user can't or won't answer the workflow question (Q1), stop
and clarify. Do not guess workflows.
---
## Question script
Read these in order. Adapt phrasing only if the user has already
volunteered an answer.
### Q1. Workflows
> Before we write any code, I need you to name the workflows you want
> covered. Think of a workflow as a single connected sequence of user
> actions that produces a measurable outcome — for example, "log in,
> add an item to the cart, check out", or "open the admin dashboard
> and approve a pending request".
>
> Please give me **2 to 4 workflows**, each with:
> - A short name (e.g. "checkout", "admin-approve", "anon-search").
> - A one-sentence description of what the user does.
> - Whether it requires authentication.
### Q2. Credentials
> For any auth-required workflow above, please provide test
> credentials. These should be:
> - **Dedicated test accounts**, not real users.
> - Allowed to perform the workflow's write actions safely (no real
> payments, no real data deletion).
>
> If you don't have test accounts yet, we need to pause and have you
> create them before continuing.
### Q3. Read vs write
> For each workflow, is it read-only, or does it write data to the
> backend? Examples:
> - Browsing a catalogue → read-only.
> - Posting a comment, placing an order, updating a profile → write.
### Q4. Destructive actions
> Are there any actions in your workflows that would be destructive
> if repeated thousands of times during a soak run? Common examples:
> - Payments (real money or test-card limits).
> - Account creation (DB bloat, email-vendor rate limits).
> - Sending notifications to real users.
> - Deletion of real data.
>
> List them and we'll either skip them in soak or substitute with a
> dry-run endpoint.
### Q5. Worry list
> Which one workflow do you most worry about under load? This is the
> one we'll spend the most time tuning thresholds on.
### Q6. Existing SLOs
> Do you already have SLOs in mind for this app? Please share:
> - Latency target (e.g. "p95 < 500ms").
> - Error rate target (e.g. "< 0.1% error").
> - Throughput target (e.g. "100 req/s sustained").
>
> If you don't have specific numbers, we'll use sensible defaults and
> tune after smoke.
### Q7. Backend ownership
> Do you own the backend serving this website, or only the front
> end? If you own it, do you have Grafana access (or equivalent
> observability)?
>
> If yes, please tell me:
> - Grafana URL.
> - Service name / labels used in your metrics.
> - Whether Prometheus, Loki, Tempo, Pyroscope are all configured
> (or which subset).
### Q8. Per-test-type local vs cloud
> k6 supports six test types. For each, we need to decide whether
> to run it locally on your laptop or in Grafana Cloud k6. The
> tradeoffs are:
>
> - **Local**: free, but a single laptop usually can't drive enough
> load to hit a production website's ceiling. Good for validating
> that scripts behave correctly.
> - **Grafana Cloud k6**: scales horizontally so you can actually
> reach the ceiling. Free tier is finite. **Browser VU-hours are
> billed 10× protocol VU-hours.** Soak and breakpoint are the
> most likely to exhaust budget.
>
> Where would you like to run each test type?
>
> - smoke (<1 min, low VUs, sanity check): local / cloud / both / skip
> - average (expected production load): local / cloud / both / skip
> - stress (beyond expected, find cliff): local / cloud / both / skip
> - spike (sudden VU jump): local / cloud / both / skip
> - soak (sustained, find leaks/drift): local / cloud / both / skip
> - breakpoint (find ceiling): local / cloud / both / skip
### Q9. Target URL and constraints
> What's the target URL? Are there:
> - IP allow-lists that might block Grafana Cloud k6 LGs?
> - Rate-limiters / WAFs that might throttle tests?
> - Maintenance windows or off-peak times we should target?
> - Any CDN edge nodes we should avoid hitting (a static asset CDN
> used to keep an SLO honest, but not the system-under-test)?
### Q10. Run plan sign-off
After capturing Q1-Q9, write a `runbook.md` summarising:
```markdown
# Run plan — <site>
## Workflows
1. **wN-<short-name>** — <description> (read-only / write, auth: yes/no)
2. ...
## Credentials
- wN: provided / will be provided / not required
## Destructive actions
- ...
## SLOs
- Latency: ...
- Error rate: ...
- Throughput: ...
## Backend ownership
- Owns backend: yes / no
- Grafana: <url>
- Service labels: ...
- Datasources: Prom / Loki / Tempo / Pyroscope
## MCP tools planned for this project
List the MCP tools you'll lean on at each step. Spelling them out
in the runbook makes the rest of the workflow self-checking — if
you scaffold without an `mcp-k6` step but the runbook says you'll
use it, that's a flag to come back and not handwrite the migration.
- HAR → k6 protocol conversion: `npx har-to-k6` (CLI, always)
- Playwright recorder → k6/browser migration: `mcp-k6` if installed,
otherwise the 5-step procedure in `references/functional-tests.md`
- k6 script authoring / validation: `mcp-k6` if installed
- Backend investigation (if backend is owned): `mcp-grafana` if
installed, otherwise `gcx` CLI; see `references/grafana-investigation.md`
## Run matrix
| Test type | Where |
|-------------|----------------------|
| smoke | local / cloud / both / skip |
| average | ... |
| ... | ... |
## Constraints
- IP allow-list: ...
- Rate limiters: ...
- Maintenance windows: ...
```
Then read it back to the user and ask:
> "Does this run plan look right? Anything to add or change before
> we scaffold?"
Only proceed to §2 of the SKILL after the user explicitly confirms.
---
## Common deflections and how to handle them
- **"Just figure out the workflows from the website."** → Decline.
Workflows encode the user's business priorities; the test results
only matter if the workflows reflect what real users do. Push
back: "Tell me the 2-4 paths your users hit most often, or the
ones that worry you most."
- **"Test everything."** → Decline. Decompose into named workflows.
"Everything" is not testable; named paths are.
- **"I'll add SLOs later."** → Accept, but record sensible defaults
in §10's run plan and flag them as "default, pending user
confirmation" so the final report can call out the assumption.
- **"Just use cloud for everything."** → Confirm budget awareness:
re-read the cost reminder from Q8, then proceed.
- **"Just use local for everything."** → Note that you may not reach
the ceiling. Flag in the run plan: "local-only — results bounded
by LG capacity".
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/grafana/skills/blob/main/LICENSE