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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ jobs:
cache: true
- name: gofmt
run: test -z "$(gofmt -l .)" || { gofmt -l .; exit 1; }
# The gRPC hooks exist only in the patched k6 (see patches/); the code
# using them needs -tags k6patched, so these steps build against stock k6
# and the patched-build job compiles the hooked code.
- name: go vet
run: go vet ./...
- name: go test
Expand All @@ -36,3 +39,23 @@ jobs:
run: bash scripts/check-source-md.sh
- name: Release tag script tests
run: bash scripts/tag-release_test.sh

patched-build:
# Builds the real binary (k6 patches applied, every extension linked) and
# runs the release gate on it, so a patch that no longer applies or hooked
# code that no longer compiles fails the PR.
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0
with:
go-version: "1.26.11"
cache: true
- name: Install xk6
run: go install go.k6.io/xk6/cmd/xk6@v1.4.12
- name: Build k6 (linux/amd64)
run: GOOS=linux GOARCH=amd64 CGO_ENABLED=0 ./build.sh --output dist/k6
- name: Release gate
run: bash scripts/release-gate.sh --binary dist/k6 --arch amd64
150 changes: 138 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,13 @@ Setting `schedule` together with `podRps` is an error. `_acquireUpTo(n)` takes
1..n grants at one instant and returns how many, so a batch can be sent in
slices that each fit the ceiling.

gRPC calls are paced too, with no script change: when the section is present,
the limiter is registered with the k6 gRPC hooks (see [k6 patches](#k6-patches)),
and each unary call and each stream open takes one grant from the same limiter
before it starts, so HTTP and gRPC share one rate. Messages inside a stream take
nothing. The wait runs on the call's own context, so a call whose deadline passes
while it waits fails with `DEADLINE_EXCEEDED` and is recorded as a failed call.

### `tagFilter`

`include` or `exclude` is a JSON string `{"test":[...],"group":[...],"scenario":[...]}`.
Expand All @@ -84,6 +91,28 @@ group and every nested group (`A` matches `::A::B`). The JS module exports
`_mode()`, `_shouldRunRequest(tags)`, `_shouldRunGroup(name)` and
`_shouldRunScenario(name)`.

### `grpcCapture`

Records a bounded sample of the run's gRPC calls (request message and metadata,
response message or error, headers and trailers) as JSON lines in `file`. It
uses the k6 gRPC hooks (see [k6 patches](#k6-patches)), so it sees every call
whatever way the script imports `k6/net/grpc`.

| Key | Meaning |
|---|---|
| `file` | required: a file the caller created; samples are appended (opened without `O_CREATE` and with `O_NOFOLLOW`) |
| `totalVUs` | the VU ids (1..totalVUs) capturing VUs are chosen from (default 1) |
| `vuSeed` | seed of the shuffle that picks the capturing VUs (truncated to 32 bits) |
| `maxCapturingVUs` | how many VUs capture (default 20) |
| `maxSuccess`, `maxErrors` | distinct successful / failing calls kept |
| `maxErrorsPerScenario` | failing calls kept per scenario (default 13) |
| `exclude` | `[{ "pattern": "...", "regex": false }]`: OK calls never kept, matched on the call name or full method with one leading `/` trimmed; a regex that does not compile (RE2) is skipped |

One sample is kept per (scenario, call name, status code). Messages are
protojson, cut at 64 KB; each metadata map is cut at 16 KB. A file that cannot
be opened or written turns capture off for the run, with one line on stderr.
Metadata is written as received: redact it before it leaves the machine.

### `sink`

Rows are posted as `JSONEachRow` to a ClickHouse-HTTP-compatible endpoint
Expand All @@ -109,8 +138,9 @@ Rows are posted as `JSONEachRow` to a ClickHouse-HTTP-compatible endpoint
| `summary` | a one-line run summary file written at stop; see below |

Every key added after the first release (`correlation.verdictMetric`,
`correlation.joinMetrics`, `hold`, `summary`, `cardinality.exemptMetrics` and the
column bounds) is optional; without them rows are byte-for-byte what they were.
`correlation.joinMetrics`, the `correlation.grpc*` keys, `hold`, `summary`,
`cardinality.exemptMetrics`, the column bounds and `omitEmpty`) is optional;
without them rows are byte-for-byte what they were.

#### Columns

Expand All @@ -130,13 +160,20 @@ WebSocket), `errorCount`, `url` (method-prefixed real URL), `requestName`
(method-prefixed name tag, or the metric name on WebSocket rows), `group`, `vus`,
`duration`, `latency`, `connect`, `bytesSent`, `bytesReceived`.

gRPC rows (see [gRPC rows](#grpc-rows)) read the same built-ins plus `protocol`
(empty on request and WebSocket rows, `grpc` or `grpc_stream` on gRPC rows),
`streamsOpened`, `msgsSent` and `msgsReceived` (0 on every other row).
`protocol` requires `correlation.grpcCallMetric` or `grpcStreamMetrics`; the three
counters require `grpcStreamMetrics`.

Request rows can also read `failedVerdict`: `1` when the
`correlation.verdictMetric` sample reported a failure, `0` when it reported
success and `-1` when none arrived (and on WebSocket rows). It requires
`correlation.verdictMetric`.

Check rows (`assertionColumns`): `timestamp`, `parentLabel` and `parentStatus`
(the name/url and status of the same VU's previous request), `failed`.
(the name/url and status of the same VU's previous request, or its previous gRPC
call when gRPC rows are configured), `failed`.

Numeric and boolean built-ins cannot be part of a fallback list.

Expand All @@ -151,6 +188,10 @@ A string-sourced column can carry optional bounds:
| `when` | `[{source, equals}]`: all must hold, else the column is empty (`0` for `uint`); without `equals` a condition holds on any non-empty value |
| `joinDefault` | written on a row a join sample reached when the sources give no valid value; requires `correlation.joinMetrics` |

Any column, computed ones included, can set `omitEmpty: true`: the column is
left out of a row whose value is `""`, `0` or `false`. Use it for columns only
some rows carry, such as the gRPC ones, so the other rows stay unchanged.

#### Correlation

| Key | Meaning |
Expand All @@ -164,6 +205,57 @@ A string-sourced column can carry optional bounds:
| `checkMetric` | the check metric (`checks`) |
| `verdictMetric` | a per-request pass/fail metric (e.g. `http_req_failed`), joined to its request by the same key as the phase metrics; feeds `computed:failedVerdict` |
| `joinMetrics` | metrics that never form rows: each sample's metadata is merged into the request row carrying the same `bytesIdMetaKey` id (requires `bytesIdMetaKey`). A sample that finds no row adds its value (1 to 1e6, anything else counts as 1) to the `unjoined` counter |
| `grpcCallMetric` | the metric that forms one gRPC call row per sample (k6: `grpc_req_duration`) |
| `grpcStreamMetrics` | `{streamsOpened, msgsSent, msgsReceived}`: the gRPC stream counters (k6: `grpc_streams`, `grpc_streams_msgs_sent`, `grpc_streams_msgs_received`), each optional |
| `grpcReflectionName` | the row name of a call with no `name`, `service`/`method` or `url` tag (k6's server-reflection call); default `__grpc_reflection_connect__`; requires `grpcCallMetric` |
| `grpcStreamBucket` | the time bucket stream counters are summed in (default `10s`); requires `grpcStreamMetrics` |

#### gRPC rows

Off unless `correlation.grpcCallMetric` or `grpcStreamMetrics` is set; until then
gRPC samples form no rows. Names are matched exactly, so a script's own `grpc_*`
metrics are never gRPC rows.

- **Call rows**: every `grpcCallMetric` sample is one row on arrival. `requestName`
is the `name` tag, else `/<service>/<method>`, else the `url` tag from its first
`/`, else `grpcReflectionName`; `url` is the `url` tag as is; `status` is the
`status` tag, or `NO_STATUS` when absent; `statusMessage` is the gRPC enum name
for 0 to 16 (`OK` ... `UNAUTHENTICATED`), else the status itself; `errorCount` is
0 only for status `0`; `duration` is the call time. With `sendTimeRestamp` the
row is stamped at the send instant (sample time minus duration).
- **The reflection call ending `CANCELLED`** (status `1` on a call named
`grpcReflectionName`) forms no row, marks no script data and is never a check's
parent. k6 cancels the reflection stream when `connect()` returns, so that
status is not a call. Every other reflection status is written, and a named call
ending `CANCELLED` stays an error.
- **Stream rows**: the stream counters are summed per `grpcStreamBucket`, row
name, `url`, `scenario`, `group` and every tag and metadata value the columns
read, until the next flush, into one row each: `protocol` `grpc_stream`, the
three counters, empty `status` and `statusMessage`, `duration` and `errorCount`
0, stamped at the first sample.
- gRPC rows leave on every flush, count as pending for the push marker, share the
`buffers.metricMax` cap (overflow is shed and counted) and mark `scriptData`.
A finished call becomes its VU's last request for check correlation (label =
`requestName`, status = `status`).

```json
{
"correlation": {
"grpcCallMetric": "grpc_req_duration",
"grpcStreamMetrics": {"streamsOpened": "grpc_streams", "msgsSent": "grpc_streams_msgs_sent",
"msgsReceived": "grpc_streams_msgs_received"}
},
"columns": [
{"name": "protocol", "from": "computed:protocol", "omitEmpty": true},
{"name": "streamsOpened", "from": "computed:streamsOpened", "omitEmpty": true},
{"name": "msgsSent", "from": "computed:msgsSent", "omitEmpty": true},
{"name": "msgsReceived", "from": "computed:msgsReceived", "omitEmpty": true}
]
}
```

(Only the keys gRPC adds are shown.) With `omitEmpty`, request and WebSocket
rows carry none of these columns and stay byte-for-byte what they were.

#### Hold

Expand All @@ -178,8 +270,8 @@ the same marker, is then not counted again. Requires `correlation.joinMetrics`.

`{dir, totalRows, scriptData, pushAttempted, iteration, iterationThreshold, dataMetricPrefixes}`.
`totalRows` holds the number of rows delivered. The others are written once with
`1`: `scriptData` on the first sample whose metric is the check metric or starts
with a `dataMetricPrefixes` entry, `pushAttempted` before the first POST, and
`1`: `scriptData` on the first sample whose metric is the check metric, a gRPC
row metric or starts with a `dataMetricPrefixes` entry, `pushAttempted` before the first POST, and
`iteration` after `iterationThreshold` (default 3) iterations. Stale markers are
removed at start. An empty name disables that marker.

Expand Down Expand Up @@ -247,8 +339,9 @@ ones.) The summary then reads, for example,

## Building k6 with the bundled extensions

`extensions.json` lists the k6 version (`k6Version`), this module (`repoPath: "."`)
and the third-party extensions bundled with it, each pinned to one version.
`extensions.json` lists the k6 version (`k6Version`), the k6 patches
(`k6Patches`), this module (`repoPath: "."`) and the third-party extensions
bundled with it, each pinned to one version.
`build.sh` turns it into a static binary with
[xk6](https://github.com/grafana/xk6) (needs Go, xk6 and jq):

Expand All @@ -259,9 +352,37 @@ scripts/release-gate.sh --binary dist/k6-linux-amd64 --arch amd64

`scripts/release-gate.sh` reads the binary's Go build information
(`go version -m`) and fails unless it is linux/`<arch>` with CGO off, links
`go.k6.io/k6/v2` at `k6Version`, links every pinned extension at exactly its
version (not replaced) and this module, and links no other xk6 module than the
ones k6 itself requires.
`go.k6.io/k6/v2` at `k6Version` (replaced by exactly the patched copy when
`k6Patches` is set), links every pinned extension at exactly its version (not
replaced) and this module, and links no other xk6 module than the ones k6
itself requires.

### k6 patches

`k6Patches` lists patch files under `patches/`. `build.sh` downloads the pinned
k6 source through the Go module proxy, copies it to
`/tmp/xk6-load-toolkit/k6-<version>-patched` (a fixed path, because the
directory is recorded in the binary's build info), applies each patch with
`git apply`, and builds with `--replace go.k6.io/k6/v2=<that directory>`. A patch
that no longer applies fails the build, and so does a binary not linked against
the patched copy. Bumping `k6Version` means re-checking every patch.

| Patch | Why |
|---|---|
| `k6-grpc-deadline.patch` | stock k6 drops the `grpc_req_duration` sample of a call that ends with `DEADLINE_EXCEEDED` (the deadline cancels the context the sample is pushed with); the patch pushes it against the VU context, so timed-out calls are counted |
| `k6-grpc-capture.patch` | adds `lib/netext/grpccapture`: a hook an extension registers to observe every gRPC call's stats (used by `grpcCapture`) and a pacer called before each unary call and stream open (used by `throughput`) |

The hooks live in k6's gRPC client rather than in a JavaScript wrapper around
`k6/net/grpc`, because a wrapper only sees calls made through the module's
default export: a script that writes `import { Client } from "k6/net/grpc"`,
`import { Client as C } ...` or `import * as grpc ...` bypasses it, and a wrapper
cannot recover the samples k6 drops for timed-out calls.

The Go code that uses the hooks (`internal/grpccapture/hook.go`,
`internal/throughput/grpc_hook.go`) builds only against the patched k6, with
`-tags k6patched`, which `build.sh` passes to xk6 (with xk6's default
`-trimpath` and `-ldflags=-s -w`). Without the tag it compiles to no-ops, so a
plain `go test ./...` runs against stock k6.

## Distribution

Expand All @@ -285,12 +406,15 @@ scripts/release-gate.sh --binary dist/k6-linux-amd64 --arch amd64 --manifest ext

```
register.go the only root file: init() registers the output and the two JS
modules with k6; the package exports nothing
modules with k6 and connects the gRPC hooks; the package exports
nothing
patches/ the k6 patches build.sh applies
internal/config/ reads the document at init, applies env.unset, strict decode,
composes the capability sections and validates each one
internal/sink/ the output: buffers, columns, cardinality guard, markers
internal/throughput/ the limiter, the schedule and their JS module; testdata/ holds
the schedule fixtures and their generator
internal/grpccapture/ the gRPC call capture and its k6-hook adapter (hook.go)
internal/tag-filter/ the tag filter, its JS module and the check-sample policy
(package tagfilter: Go package names cannot contain '-',
so importers use `tagfilter "…/internal/tag-filter"`)
Expand Down Expand Up @@ -318,8 +442,10 @@ interface; the root package hands it over.
## Tests

```sh
go test ./...
go test ./... # unit tests, against stock k6
scripts/release-gate_test.sh
GOOS=linux GOARCH=amd64 ./build.sh --output dist/k6 && \
scripts/release-gate.sh --binary dist/k6 --arch amd64 # compiles the hooked code
```

## License
Expand Down
25 changes: 19 additions & 6 deletions SOURCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,21 @@ Read this file at that tag (or commit):

| Component | Go module | Version | Commit | Licence | Source |
|---|---|---|---|---|---|
| k6 | `go.k6.io/k6/v2` | v2.2.0 | `00a9a1b7f552d6bb4337278b10ae25aac0f4e666` | AGPL-3.0 | <https://github.com/grafana/k6/tree/v2.2.0> |
| k6 | `go.k6.io/k6/v2` | v2.2.0 | `00a9a1b7f552d6bb4337278b10ae25aac0f4e666` | AGPL-3.0 | <https://github.com/grafana/k6/tree/v2.2.0>, with the patches below |
| xk6-load-toolkit | `github.com/browserstack/xk6-load-toolkit` | the image's `org.opencontainers.image.version` label | the `commit` in `build-info.json` (also the `org.opencontainers.image.revision` label) | AGPL-3.0 | <https://github.com/browserstack/xk6-load-toolkit/tree/<tag>> |

### k6 patches (`k6Patches` in `extensions.json`)

The binary links k6 with these patches applied, in this order, by `build.sh`
(`git apply` on the pinned k6 source, then `xk6 build --replace`). Both files
are in this repository, so the patched k6 source is the k6 commit above plus
these files.

| Patch | What it changes |
|---|---|
| [`patches/k6-grpc-deadline.patch`](patches/k6-grpc-deadline.patch) | Pushes a finished gRPC call's `grpc_req_duration` sample against the VU context instead of the call's own, so calls that end with `DEADLINE_EXCEEDED` are recorded (stock k6 drops them, because the deadline cancels the call's context). |
| [`patches/k6-grpc-capture.patch`](patches/k6-grpc-capture.patch) | Adds the `lib/netext/grpccapture` package: a hook an extension can register to observe every gRPC call's stats (used by the `grpcCapture` capability) and a pacer called before each unary call and stream open (used by the throughput limiter). With nothing registered each call pays one atomic load. |

### Third-party extensions (15, pinned in `extensions.json`)

| Extension | Go module | Version | Commit | Licence | Source |
Expand Down Expand Up @@ -93,9 +105,10 @@ All in this repository at the same commit:

| File | Role |
|---|---|
| [`extensions.json`](extensions.json) | The manifest: the k6 version and every extension with its pinned version. |
| [`build.sh`](build.sh) | Turns the manifest into `xk6 build --k6-version … --with <module>@<version> …` and runs it with CGO off. |
| [`scripts/release-gate.sh`](scripts/release-gate.sh) | Reads the binary's `go version -m` output and fails unless every pin above is linked at exactly its version. |
| [`extensions.json`](extensions.json) | The manifest: the k6 version, the k6 patches and every extension with its pinned version. |
| [`build.sh`](build.sh) | Applies the k6 patches to a copy of the pinned k6 source at `/tmp/xk6-load-toolkit/k6-<version>-patched`, turns the manifest into `xk6 build --k6-version … --with <module>@<version> … --replace go.k6.io/k6/v2=<that directory> --build-flags -trimpath --build-flags "-ldflags=-s -w" --build-flags -tags=k6patched` and runs it with CGO off. |
| [`patches/`](patches) | The k6 patches listed above. |
| [`scripts/release-gate.sh`](scripts/release-gate.sh) | Reads the binary's `go version -m` output and fails unless every pin above is linked at exactly its version, and k6 is replaced by exactly the patched copy. |
| This file | The builder stage below, the toolchain pins and the component list. |

### Builder stage
Expand Down Expand Up @@ -153,6 +166,6 @@ RUN GOOS=linux GOARCH="$TARGETARCH" CGO_ENABLED=0 ./build.sh --output /out/k6 &&

## Keeping this file current

A change to `extensions.json`, to the Go image or `go-version`, or to the xk6
version must update this file in the same commit, so that this file at any
A change to `extensions.json`, to a file in `patches/`, to the Go image or
`go-version`, or to the xk6 version must update this file in the same commit, so that this file at any
commit describes the binaries built from that commit.
Loading
Loading