diff --git a/.github/workflows/benchmark.yaml b/.github/workflows/benchmark.yaml index 3a165a5936..19196063ee 100644 --- a/.github/workflows/benchmark.yaml +++ b/.github/workflows/benchmark.yaml @@ -18,6 +18,9 @@ on: runs: description: "The number of runs on each benchmark" default: "5" + regions: + description: "Regions to run the registry-* variations from: keys of the REGISTRY_RUNNERS repository variable (see docs/METHODOLOGY.md#regions)" + default: '["na", "eu"]' schedule: # GitHub Actions cron uses UTC. 10:17 UTC ~= 2:17 AM Pacific (PST). - cron: "17 10 * * *" @@ -34,6 +37,9 @@ jobs: outputs: skip_benchmarks: ${{ steps.check.outputs.skip_benchmarks }} partial_run: ${{ steps.partial.outputs.partial_run }} + pm_variations: ${{ steps.plan.outputs.pm_variations }} + registry_matrix: ${{ steps.plan.outputs.registry_matrix }} + registry_jobs: ${{ steps.plan.outputs.registry_jobs }} steps: - uses: actions/checkout@v6 with: @@ -98,6 +104,7 @@ jobs: IN_BINARIES: ${{ inputs.binaries || '' }} IN_WARMUP: ${{ inputs.warmup || '' }} IN_RUNS: ${{ inputs.runs || '' }} + IN_REGIONS: ${{ inputs.regions || '' }} run: | # A dispatch with any non-default input produces a partial/tuned data # set: results stay in artifacts + logs but must not deploy to @@ -109,24 +116,40 @@ jobs: [[ "$IN_BINARIES" == '"npm,yarn,berry,zpm,pnpm,vlt,bun,deno,aube,upm,nx,turbo,vp,node"' ]] || partial=true [[ "$IN_WARMUP" == "2" ]] || partial=true [[ "$IN_RUNS" == "5" ]] || partial=true + [[ "$IN_REGIONS" == '["na", "eu"]' ]] || partial=true fi echo "partial_run=$partial" >> "$GITHUB_OUTPUT" if [[ "$partial" == "true" ]]; then echo "::notice::Partial run detected (non-default dispatch inputs) — gh-pages deploy will be skipped; results live in job logs and artifacts." fi + - name: Plan package-manager and registry jobs + id: plan + # Registry variations measure the network, so they run once per region + # on a runner pinned there; everything else measures the client and + # runs once. REGISTRY_RUNNERS (a repository variable, JSON) says which + # runner each region uses; unset, only "na" runs, on the GitHub-hosted + # runner it always used. See suite/scripts/plan-jobs.js. + env: + BENCH_FIXTURES: ${{ (github.event_name == 'push' && github.ref != 'refs/heads/main') && '["next", "astro", "vue", "svelte"]' || (inputs.fixtures || '["next", "astro", "vue", "svelte", "large", "babylon"]') }} + BENCH_VARIATIONS: ${{ inputs.variations || '["clean", "node_modules", "cache", "cache+node_modules", "cache+lockfile", "cache+lockfile+node_modules", "ci", "ci+setup", "lockfile", "lockfile+node_modules", "registry-clean", "registry-lockfile", "add-singleton", "remove-singleton", "add-overlap", "remove-overlap"]' }} + BENCH_REGIONS: ${{ inputs.regions || '["na", "eu"]' }} + REGISTRY_RUNNERS: ${{ vars.REGISTRY_RUNNERS }} + RUN_ID: ${{ github.run_id }} + run: node suite/scripts/plan-jobs.js benchmark: name: "Run Benchmarks" runs-on: ubuntu-24.04-arm needs: [detect-changes] - if: needs.detect-changes.outputs.skip_benchmarks != 'true' + if: needs.detect-changes.outputs.skip_benchmarks != 'true' && needs.detect-changes.outputs.pm_variations != '[]' timeout-minutes: 120 environment: Benchmark strategy: fail-fast: false matrix: fixture: ${{ fromJson((github.event_name == 'push' && github.ref != 'refs/heads/main') && '["next", "astro", "vue", "svelte"]' || (inputs.fixtures || '["next", "astro", "vue", "svelte", "large", "babylon"]')) }} - variation: ${{ fromJson(inputs.variations || '["clean", "node_modules", "cache", "cache+node_modules", "cache+lockfile", "cache+lockfile+node_modules", "ci", "ci+setup", "lockfile", "lockfile+node_modules", "registry-clean", "registry-lockfile", "add-singleton", "remove-singleton", "add-overlap", "remove-overlap"]') }} + # Everything but registry-*, which runs per region in benchmark-registries. + variation: ${{ fromJson(needs.detect-changes.outputs.pm_variations) }} include: - variation: "build" fixture: "next" @@ -136,7 +159,6 @@ jobs: fixture: "run" permissions: contents: read - id-token: write env: # rc.21 is advertised by the canary channel but its Linux ARM64 npm binary is missing. BENCH_ZPM_VERSION: "6.0.0-rc.20" @@ -157,24 +179,6 @@ jobs: working-directory: suite run: | bash ./scripts/setup.sh - - name: Configure AWS Credentials - if: startsWith(matrix.variation, 'registry-') - uses: aws-actions/configure-aws-credentials@v6 - with: - role-to-assume: ${{ secrets.AWS_ROLE_ARN }} - aws-region: us-east-1 - - name: Get CodeArtifact Token - if: startsWith(matrix.variation, 'registry-') - id: aws - run: | - CODEARTIFACT_AUTH_TOKEN=$(aws codeartifact get-authorization-token \ - --domain vlt \ - --domain-owner 451504312483 \ - --region us-east-1 \ - --query authorizationToken \ - --output text) - echo "::add-mask::$CODEARTIFACT_AUTH_TOKEN" - echo "token=$CODEARTIFACT_AUTH_TOKEN" >> "$GITHUB_OUTPUT" - name: Tune benchmark settings id: tune run: | @@ -192,18 +196,96 @@ jobs: ;; esac - # Registry variations also get reduced runs (6 registries × iterations must fit in 90min) - case "${{ matrix.variation }}" in - registry-*) - warmup=1 - runs=3 - echo "Registry variation detected — using warmup=$warmup, runs=$runs" - ;; - esac - echo "warmup=$warmup" >> "$GITHUB_OUTPUT" echo "runs=$runs" >> "$GITHUB_OUTPUT" - name: Run Benchmarks variations + env: + BENCH_WARMUP: ${{ steps.tune.outputs.warmup }} + BENCH_RUNS: ${{ steps.tune.outputs.runs }} + run: | + ./suite/bench run \ + --fixtures="${{ matrix.fixture }}" \ + --variation="${{ matrix.variation }}" + - name: Upload Benchmark Results + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v7 + with: + name: results-${{ matrix.fixture }}-${{ matrix.variation }} + path: ./suite/results/${{ matrix.fixture }}/${{ matrix.variation }}/ + retention-days: 7 + - name: Upload Versions Info + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v7 + with: + name: versions-${{ matrix.fixture }}-${{ matrix.variation }} + path: ./suite/results/versions.json + retention-days: 7 + + benchmark-registries: + # The registry-* variations, once per region. A registry benchmark measures + # the network between the runner and each registry, so where the runner + # sits is part of the result: each region's jobs run on a runner pinned to + # that region (REGISTRY_RUNNERS; see docs/METHODOLOGY.md#regions) and + # record where they actually landed (runner.json -> regions.json). + name: "Run Registry Benchmarks (${{ matrix.region }})" + runs-on: ${{ matrix.runner }} + needs: [detect-changes] + if: needs.detect-changes.outputs.skip_benchmarks != 'true' && needs.detect-changes.outputs.registry_jobs != '0' + timeout-minutes: 120 + environment: Benchmark + # A region other than the default must not cost the night's results: if + # its runners break, the other regions and every package manager still + # publish, and that region's numbers are simply missing for the day. + continue-on-error: ${{ matrix.region != 'na' }} + strategy: + fail-fast: false + matrix: ${{ fromJson(needs.detect-changes.outputs.registry_matrix) }} + permissions: + contents: read + id-token: write + env: + # rc.21 is advertised by the canary channel but its Linux ARM64 npm binary is missing. + BENCH_ZPM_VERSION: "6.0.0-rc.20" + BENCH_INCLUDE: ${{ fromJson(inputs.binaries || '"npm,yarn,berry,zpm,pnpm,vlt,bun,deno,aube,upm,nx,turbo,vp,node"') }} + BENCH_REGION: ${{ matrix.region }} + BENCH_REGION_LABEL: ${{ matrix.label }} + steps: + - uses: actions/checkout@v6 + - name: Install Node + uses: actions/setup-node@v6 + with: + node-version: "26" + package-manager-cache: false + - name: Install & Setup Tools + working-directory: suite + run: | + bash ./scripts/setup.sh + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@v6 + with: + role-to-assume: ${{ secrets.AWS_ROLE_ARN }} + # Where the CodeArtifact domain is, not where the runner is. + aws-region: us-east-1 + - name: Get CodeArtifact Token + id: aws + run: | + CODEARTIFACT_AUTH_TOKEN=$(aws codeartifact get-authorization-token \ + --domain vlt \ + --domain-owner 451504312483 \ + --region us-east-1 \ + --query authorizationToken \ + --output text) + echo "::add-mask::$CODEARTIFACT_AUTH_TOKEN" + echo "token=$CODEARTIFACT_AUTH_TOKEN" >> "$GITHUB_OUTPUT" + - name: Tune benchmark settings + id: tune + run: | + # Registry variations always run warmup=1, runs=3, whatever the + # inputs: 6 registries × iterations must fit in the timeout. (The + # same override the single benchmark job applied before the split.) + echo "warmup=1" >> "$GITHUB_OUTPUT" + echo "runs=3" >> "$GITHUB_OUTPUT" + - name: Run Registry Benchmarks env: VLT_REGISTRY: https://registry.vlt.io/vlt-benchmarks/npm/ VLT_TOKEN: ${{ secrets.VLT_REGISTRY_AUTH_TOKEN }} @@ -220,25 +302,46 @@ jobs: ./suite/bench run \ --fixtures="${{ matrix.fixture }}" \ --variation="${{ matrix.variation }}" + - name: Record where this job ran + # After the benchmark, never before: it sends one request to each + # registry, which must not warm anything the benchmark measures. + if: ${{ !cancelled() }} + env: + BENCH_FIXTURE: ${{ matrix.fixture }} + BENCH_VARIATION: ${{ matrix.variation }} + VLT_TOKEN: ${{ secrets.VLT_REGISTRY_AUTH_TOKEN }} + CODEARTIFACT_AUTH_TOKEN: ${{ steps.aws.outputs.token }} + CLOUDSMITH_REGISTRY: ${{ secrets.CLOUDSMITH_REGISTRY }} + CLOUDSMITH_TOKEN: ${{ secrets.CLOUDSMITH_TOKEN }} + GH_REGISTRY: ${{ secrets.GH_REGISTRY }} + GH_AUTH_TOKEN: ${{ secrets.GH_AUTH_TOKEN }} + JFROG_REGISTRY: ${{ secrets.JFROG_REGISTRY }} + JFROG_TOKEN: ${{ secrets.JFROG_TOKEN }} + run: | + bash suite/scripts/registry/runner-info.sh suite/scripts \ + "suite/results/${{ matrix.fixture }}/${{ matrix.name }}/runner.json" - name: Upload Benchmark Results if: ${{ !cancelled() }} uses: actions/upload-artifact@v7 with: - name: results-${{ matrix.fixture }}-${{ matrix.variation }} - path: ./suite/results/${{ matrix.fixture }}/${{ matrix.variation }}/ + name: results-${{ matrix.fixture }}-${{ matrix.name }} + path: ./suite/results/${{ matrix.fixture }}/${{ matrix.name }}/ retention-days: 7 - name: Upload Versions Info if: ${{ !cancelled() }} uses: actions/upload-artifact@v7 with: - name: versions-${{ matrix.fixture }}-${{ matrix.variation }} + name: versions-${{ matrix.fixture }}-${{ matrix.name }} path: ./suite/results/versions.json retention-days: 7 + process: name: "Process Results" runs-on: ubuntu-24.04-arm - needs: [detect-changes, benchmark] - if: needs.detect-changes.outputs.skip_benchmarks != 'true' + needs: [detect-changes, benchmark, benchmark-registries] + # !failure() rather than the implicit success(): a dispatch can ask for + # only one kind of benchmark, and the other kind's job is then skipped. + if: ${{ !cancelled() && !failure() && needs.detect-changes.outputs.skip_benchmarks != 'true' }} timeout-minutes: 10 steps: - uses: actions/checkout@v6 @@ -271,11 +374,12 @@ jobs: const failures = [] for (const entry of fs.readdirSync('suite/results').sort()) { - const match = /^results-(.+)-(registry-[a-z]+)$/.exec(entry) + // results--registry-[@] + const match = /^results-(.+?)-(registry-[a-z]+)(?:@([a-z]{2,8}))?$/.exec(entry) if (!match) continue const file = path.join('suite/results', entry, 'benchmarks.json') if (!fs.existsSync(file)) continue - const label = `${match[1]} ${match[2]}` + const label = `${match[1]} ${match[2]} (${match[3] ?? 'na'})` const vlt = (JSON.parse(fs.readFileSync(file, 'utf8')).results ?? []) .find((r) => r.command === 'vlt') @@ -367,9 +471,10 @@ jobs: // registry name rather than a package manager. const dir = 'suite/results/latest' for (const entry of fs.readdirSync(dir).sort()) { - const match = /^(.+)-(registry-[a-z]+)\.json$/.exec(entry) + // -registry-[@].json + const match = /^(.+?)-(registry-[a-z]+)(?:@([a-z]{2,8}))?\.json$/.exec(entry) if (!match) continue - const label = `${match[1]} ${match[2]}` + const label = `${match[1]} ${match[2]} (${match[3] ?? 'na'})` // Registries where every run failed are stamped with a non-zero // exit code and a zero mean by clean-benchmarks and rendered as @@ -444,6 +549,7 @@ jobs: needs: - detect-changes - benchmark + - benchmark-registries - process - deploy steps: @@ -463,5 +569,6 @@ jobs: The benchmark run failed and needs to be retriggered. Detect Changes: ${{ needs.detect-changes.result }} Benchmark: ${{ needs.benchmark.result }} + Registry benchmarks: ${{ needs.benchmark-registries.result }} Process: ${{ needs.process.result }} Deploy: ${{ needs.deploy.result }} diff --git a/README.md b/README.md index 198e973b6a..282188eff7 100644 --- a/README.md +++ b/README.md @@ -17,9 +17,9 @@ taking no new measurements. ## Environment We currently only test a `linux` runner, the most common GitHub Actions -environment. The workflow label is read from the workflows themselves — all six -benchmark jobs in `.github/workflows/benchmark.yaml` and -`.github/workflows/reprocess.yml` set `runs-on: ubuntu-24.04-arm`: +environment. The workflow label is read from the workflows themselves — every +package-manager and task-runner job in `.github/workflows/benchmark.yaml`, and +every job in `.github/workflows/reprocess.yml`, sets `runs-on: ubuntu-24.04-arm`: - Workflow label: `ubuntu-24.04-arm` - VM: Linux (Ubuntu 24.04) @@ -39,6 +39,11 @@ not measurements taken here. > producing the numbers. If you are comparing these results against your own, > that difference matters more than any of the figures above. +The registry benchmarks are the exception: they run once **per region** +(North America and Europe), each on a runner pinned to that region by the +`REGISTRY_RUNNERS` repository variable, and record where they actually ran. +See [Regions in docs/METHODOLOGY.md](docs/METHODOLOGY.md#regions). + We may add Mac/Windows in the future but it will likely exponentially increase the already slow run time of the suite (**~40min**). ## Overview @@ -106,12 +111,17 @@ Registry benchmarking is available in the `registry-clean` and `registry-lockfil - `npm` (`https://registry.npmjs.org/`) - `vlt` (`https://registry.vlt.io/vlt-benchmarks/npm/`) -- `aws` (CodeArtifact benchmark registry) +- `aws` (CodeArtifact benchmark registry, `us-east-1`) +- `cloudsmith` (`CLOUDSMITH_REGISTRY`) +- `github` (GitHub Packages, `GH_REGISTRY`) +- `jfrog` (JFrog Artifactory, `JFROG_REGISTRY`) Defaults: -- Local and CI run `npm,vlt,aws` by default for `registry-*` variations. +- Local and CI run all six by default for `registry-*` variations. - You can limit registries with `--registries` (wrapper) or `BENCH_INCLUDE_REGISTRY` (script-level env). +- `--region=` (or `BENCH_REGION`) files the results under that region + (`@`); it does not move the machine. CI sets it per region. Examples: @@ -123,6 +133,11 @@ Examples: CODEARTIFACT_AUTH_TOKEN= ./suite/bench run --variation=registry-clean --fixtures=next --registries=aws ``` +```bash +# File a run as Europe's (from a machine that is actually in Europe) +./suite/bench run --variation=registry-clean --fixtures=next --registries=npm,vlt --region=eu +``` + Auth notes: - `aws` requires `CODEARTIFACT_AUTH_TOKEN`. diff --git a/apps/data/src/client.ts b/apps/data/src/client.ts index da194c82bf..8f5d108642 100644 --- a/apps/data/src/client.ts +++ b/apps/data/src/client.ts @@ -6,14 +6,17 @@ * reads across the workspace boundary on disk, so the same code works against * a local server and against the gh-pages origin. */ -import type { - BenchmarkFile, - ChartData, - Fixture, - PackageCount, - ProcessCount, - Variation, - Versions, +import { + DEFAULT_REGION, + type BenchmarkFile, + type ChartData, + type Fixture, + type PackageCount, + type ProcessCount, + type RegionId, + type RegionsFile, + type Variation, + type Versions, } from "@benchmarks/types"; import type { DataIndex, DataManifest, DirectoryEntry } from "./manifest.ts"; import { @@ -25,9 +28,18 @@ import { manifestShardPath, packageCountFile, processCountFile, + REGIONS_FILE, summaryPath, VERSIONS_FILE, } from "./paths.ts"; +import { + projectEntry, + projectIndex, + projectManifest, + projectSummary, + publishedRegions, + publishedVariation, +} from "./regions.ts"; import type { DateSummary } from "./summary.ts"; export type FetchLike = (url: string) => Promise<{ @@ -41,6 +53,13 @@ export interface DataClientOptions { baseUrl: string; /** Injectable for tests; defaults to global fetch. */ fetch?: FetchLike; + /** + * Which region's registry runs to show (src/regions.ts). Defaults to the + * default region, whose files are the unsuffixed ones every consumer read + * before regions existed -- so an existing caller sees the same tree, minus + * the other regions' `@` files. + */ + region?: RegionId; } export class DataFetchError extends Error { @@ -57,14 +76,23 @@ export class DataFetchError extends Error { export class DataClient { readonly baseUrl: string; + /** The region this client shows registry runs from. */ + readonly region: RegionId; readonly #fetch: FetchLike; constructor(options: DataClientOptions) { this.baseUrl = options.baseUrl; + this.region = options.region ?? DEFAULT_REGION; this.#fetch = options.fetch ?? ((url: string) => fetch(url) as unknown as ReturnType); } + /** The same tree through another region's view; this client is left as it is. */ + withRegion(region: RegionId): DataClient { + if (region === this.region) return this; + return new DataClient({ baseUrl: this.baseUrl, fetch: this.#fetch, region }); + } + url(...segments: string[]): string { return dataUrl(this.baseUrl, ...segments); } @@ -77,8 +105,8 @@ export class DataClient { } /** The light index: which dates exist, and the observed vocabularies. */ - getIndex(): Promise { - return this.#get(INDEX_FILE); + async getIndex(): Promise { + return projectIndex(await this.#get(INDEX_FILE), this.region); } /** @@ -87,8 +115,8 @@ export class DataClient { * Prefer {@link getDirectoryEntry} when one directory is wanted. Reach for * this only for genuinely cross-date work. */ - getManifest(): Promise { - return this.#get(MANIFEST_FILE); + async getManifest(): Promise { + return projectManifest(await this.#get(MANIFEST_FILE), this.region); } /** @@ -98,8 +126,17 @@ export class DataClient { * same object as `getManifest().entries[name]`, so switching between the two * changes cost and nothing else. */ - getDirectoryEntry(name: string): Promise { - return this.#get(...manifestShardPath(name)); + async getDirectoryEntry(name: string): Promise { + return projectEntry(await this.#get(...manifestShardPath(name)), this.region); + } + + /** + * The regions one directory published registry results from, default first, + * whatever this client's own region is. Reads the same shard as + * {@link getDirectoryEntry}, before projection. + */ + async getPublishedRegions(name: string): Promise { + return publishedRegions(await this.#get(...manifestShardPath(name))); } getBenchmark( @@ -107,7 +144,10 @@ export class DataClient { fixture: Fixture, variation: Variation | string, ): Promise { - return this.#get(date, benchmarkFile(fixture, variation)); + return this.#get( + date, + benchmarkFile(fixture, publishedVariation(variation, this.region)), + ); } getPackageCount( @@ -115,7 +155,10 @@ export class DataClient { fixture: Fixture, variation: Variation | string, ): Promise { - return this.#get(date, packageCountFile(fixture, variation)); + return this.#get( + date, + packageCountFile(fixture, publishedVariation(variation, this.region)), + ); } /** @@ -128,12 +171,15 @@ export class DataClient { fixture: Fixture, variation: Variation | string, ): Promise { - return this.#get(date, processCountFile(fixture, variation)); + return this.#get( + date, + processCountFile(fixture, publishedVariation(variation, this.region)), + ); } /** Every benchmark file of one date in one fetch (src/summary.ts); 404 until a deploy has written it. */ - getSummary(date: string): Promise { - return this.#get(...summaryPath(date)); + async getSummary(date: string): Promise { + return projectSummary(await this.#get(...summaryPath(date)), this.region); } getChartData(date: string): Promise { @@ -144,4 +190,13 @@ export class DataClient { getVersions(date: string): Promise { return this.#get(date, VERSIONS_FILE); } + + /** + * Where each region's registry jobs ran on one date (`regions.json`), for + * every region regardless of this client's own. Rejects with a 404 on any + * date before regions were recorded. + */ + getRegions(date: string): Promise { + return this.#get(date, REGIONS_FILE); + } } diff --git a/apps/data/src/index.ts b/apps/data/src/index.ts index fe84553d83..ce73f5d60f 100644 --- a/apps/data/src/index.ts +++ b/apps/data/src/index.ts @@ -21,12 +21,24 @@ export { packageCountFile, parseDataFile, processCountFile, + REGIONS_FILE, SUMMARY_DIR, summaryPath, VERSIONS_FILE, type FileKind, type ParsedDataFile, } from "./paths.ts"; +export { + isRegional, + projectEntry, + projectIndex, + projectManifest, + projectSummary, + projectVariation, + publishedRegions, + publishedVariation, + REGIONAL_PREFIX, +} from "./regions.ts"; export { scanRoots } from "./scan.ts"; export { buildSummary, diff --git a/apps/data/src/paths.ts b/apps/data/src/paths.ts index 1852cca603..0522c0ea21 100644 --- a/apps/data/src/paths.ts +++ b/apps/data/src/paths.ts @@ -8,6 +8,11 @@ import { type Fixture, FIXTURES, type Variation } from "@benchmarks/types"; export const CHART_DATA_FILE = "chart-data.json"; export const VERSIONS_FILE = "versions.json"; +/** + * Where each region's registry jobs ran, per date. Its name has no `-`, so + * {@link parseDataFile} never mistakes it for a fixture's file. + */ +export const REGIONS_FILE = "regions.json"; export const LATEST_DIR = "latest"; /** Names this package publishes at the root of the served tree. */ diff --git a/apps/data/src/regions.ts b/apps/data/src/regions.ts new file mode 100644 index 0000000000..02bd1aaa17 --- /dev/null +++ b/apps/data/src/regions.ts @@ -0,0 +1,130 @@ +/** + * One region's view of the published tree. + * + * Registry variations can be published once per region (`registry-clean` for + * the default region, `registry-clean@eu` for Europe; see `@benchmarks/types`). + * A consumer asks for one region at a time and sees that region's files under + * the plain variation names, so everything downstream of the client -- scenario + * lists, averages, trends, summaries -- works on any region without knowing + * regions exist. + * + * The rules, for a view of region R: + * + * - `x@R` is shown as `x`. + * - `x@S`, for any other region S, is hidden. + * - An unsuffixed `x` is the default region's. It is shown when R is the + * default region, and also when `x` is not regional at all (a package-manager + * or task-runner variation, which is run once and belongs to every region). + * An unsuffixed REGISTRY variation is hidden from any other region's view: + * North American numbers must never be read as European ones, even on a date + * Europe did not run. + */ +import { DEFAULT_REGION, regionalVariation, splitRegion, type RegionId } from "@benchmarks/types"; +import type { DataIndex, DataManifest, DirectoryEntry, VariationsByFixture } from "./manifest.ts"; +import { SUMMARY_PACKAGE_COUNTS, type DateSummary } from "./summary.ts"; + +/** Variations measured from more than one region. Everything else is run once. */ +export const REGIONAL_PREFIX = "registry-"; + +export const isRegional = (variation: string): boolean => variation.startsWith(REGIONAL_PREFIX); + +/** A published variation as region `region` sees it, or `undefined` when that view hides it. */ +export const projectVariation = (published: string, region: RegionId): string | undefined => { + const { variation, region: from } = splitRegion(published); + if (from === region) return variation; + if (from !== DEFAULT_REGION) return undefined; + return isRegional(variation) ? undefined : variation; +}; + +/** The published name to fetch for a variation, as region `region` names it. */ +export const publishedVariation = (variation: string, region: RegionId): string => + isRegional(variation) ? regionalVariation(variation, region) : variation; + +const projectList = (list: readonly string[], region: RegionId): string[] => [ + ...new Set( + list.flatMap((v) => { + const shown = projectVariation(v, region); + return shown === undefined ? [] : [shown]; + }), + ), +]; + +const projectByFixture = ( + byFixture: VariationsByFixture | undefined, + region: RegionId, +): VariationsByFixture => { + const out: VariationsByFixture = {}; + for (const [fixture, list] of Object.entries(byFixture ?? {})) { + const shown = projectList(list ?? [], region).sort(); + if (shown.length > 0) out[fixture] = shown; + } + return out; +}; + +/** + * The regions a directory published registry results from, the default region + * first and the rest alphabetically. Read off a RAW (unprojected) entry. + */ +export const publishedRegions = (entry: DirectoryEntry): RegionId[] => { + const found = new Set(); + for (const list of Object.values(entry.benchmarks ?? {})) { + for (const published of list ?? []) { + const { variation, region } = splitRegion(published); + if (isRegional(variation)) found.add(region); + } + } + return [...found].sort((a, b) => + a === DEFAULT_REGION ? -1 : b === DEFAULT_REGION ? 1 : a.localeCompare(b), + ); +}; + +export const projectEntry = (entry: DirectoryEntry, region: RegionId): DirectoryEntry => ({ + ...entry, + benchmarks: projectByFixture(entry.benchmarks, region), + packageCounts: projectByFixture(entry.packageCounts, region), + processCounts: projectByFixture(entry.processCounts, region), +}); + +export const projectIndex = (index: DataIndex, region: RegionId): DataIndex => + Array.isArray(index.variations) + ? { ...index, variations: projectList(index.variations, region).sort() } + : index; + +export const projectManifest = (manifest: DataManifest, region: RegionId): DataManifest => ({ + ...manifest, + entries: Object.fromEntries( + Object.entries(manifest.entries ?? {}).map(([name, entry]) => [ + name, + entry === undefined ? undefined : projectEntry(entry, region), + ]), + ), +}); + +/* Variation-keyed records, with reserved `#` keys passed through untouched. */ +const projectKeys = ( + record: { readonly [key: string]: T }, + region: RegionId, +): { [key: string]: T } => { + const out: { [key: string]: T } = Object.create(null); + for (const [key, value] of Object.entries(record)) { + if (key.startsWith("#")) { + out[key] = value; + continue; + } + const shown = projectVariation(key, region); + if (shown !== undefined) out[shown] = value; + } + return out; +}; + +export const projectSummary = (summary: DateSummary, region: RegionId): DateSummary => { + const out = projectKeys(summary as { readonly [key: string]: unknown }, region); + const counts = out[SUMMARY_PACKAGE_COUNTS]; + if (typeof counts === "object" && counts !== null && !Array.isArray(counts)) { + out[SUMMARY_PACKAGE_COUNTS] = projectKeys( + counts as { readonly [key: string]: unknown }, + region, + ); + } + return out as DateSummary; +}; diff --git a/apps/data/test/regions.test.ts b/apps/data/test/regions.test.ts new file mode 100644 index 0000000000..f4b4b599f9 --- /dev/null +++ b/apps/data/test/regions.test.ts @@ -0,0 +1,162 @@ +import { describe, expect, it } from "vitest"; +import { DataClient, type FetchLike } from "../src/client.ts"; +import type { DirectoryEntry } from "../src/manifest.ts"; +import { + projectEntry, + projectSummary, + projectVariation, + publishedRegions, + publishedVariation, +} from "../src/regions.ts"; +import { SUMMARY_PACKAGE_COUNTS, SUMMARY_VERSIONS, type DateSummary } from "../src/summary.ts"; + +/* A date that ran registries from North America (unsuffixed) and Europe (@eu). */ +const entry: DirectoryEntry = { + name: "2026-12-01", + isLatest: false, + fileCount: 0, + benchmarks: { + next: ["clean", "registry-clean", "registry-clean@eu", "registry-lockfile", "run"], + vue: ["registry-clean"], + astro: ["registry-lockfile@eu", "registry-lockfile@apac"], + }, + packageCounts: { next: ["clean", "registry-clean", "registry-clean@eu"] }, + processCounts: { next: ["clean"] }, + hasChartData: true, + hasVersions: true, +}; + +describe("projectVariation", () => { + it("shows the default region's files as published and hides every suffixed one", () => { + expect(projectVariation("registry-clean", "na")).toBe("registry-clean"); + expect(projectVariation("clean", "na")).toBe("clean"); + expect(projectVariation("registry-clean@eu", "na")).toBeUndefined(); + }); + + it("shows a region's own files under the plain name", () => { + expect(projectVariation("registry-clean@eu", "eu")).toBe("registry-clean"); + expect(projectVariation("registry-clean@apac", "eu")).toBeUndefined(); + }); + + it("never lets the default region's registry runs stand in for another region's", () => { + expect(projectVariation("registry-clean", "eu")).toBeUndefined(); + }); + + it("keeps variations that are run once, in every region's view", () => { + expect(projectVariation("cache+lockfile", "eu")).toBe("cache+lockfile"); + expect(projectVariation("run", "eu")).toBe("run"); + }); +}); + +describe("publishedVariation", () => { + it("names the file to fetch", () => { + expect(publishedVariation("registry-clean", "na")).toBe("registry-clean"); + expect(publishedVariation("registry-clean", "eu")).toBe("registry-clean@eu"); + expect(publishedVariation("clean", "eu")).toBe("clean"); + }); +}); + +describe("publishedRegions", () => { + it("lists the regions registry files came from, default first", () => { + expect(publishedRegions(entry)).toEqual(["na", "apac", "eu"]); + }); + + it("is empty for a date that ran no registry variation", () => { + expect(publishedRegions({ ...entry, benchmarks: { next: ["clean", "run"] } })).toEqual([]); + }); +}); + +describe("projectEntry", () => { + it("is the tree as it looked before regions, for the default region", () => { + const na = projectEntry(entry, "na"); + expect(na.benchmarks).toEqual({ + next: ["clean", "registry-clean", "registry-lockfile", "run"], + vue: ["registry-clean"], + }); + expect(na.packageCounts).toEqual({ next: ["clean", "registry-clean"] }); + }); + + it("is Europe's registry runs plus everything run once, for eu", () => { + const eu = projectEntry(entry, "eu"); + expect(eu.benchmarks).toEqual({ + next: ["clean", "registry-clean", "run"], + astro: ["registry-lockfile"], + }); + expect(eu.packageCounts).toEqual({ next: ["clean", "registry-clean"] }); + expect(eu.processCounts).toEqual({ next: ["clean"] }); + }); + + it("leaves the entry it was given alone", () => { + projectEntry(entry, "eu"); + expect(entry.benchmarks["next"]).toContain("registry-clean@eu"); + }); +}); + +describe("projectSummary", () => { + const result = { command: "npm", mean: 1, stddev: 0, exit_codes: [0] }; + const summary = { + clean: { next: [result] }, + "registry-clean": { next: [result] }, + "registry-clean@eu": { next: [{ ...result, mean: 2 }] }, + [SUMMARY_VERSIONS]: { npm: "12.0.0" }, + [SUMMARY_PACKAGE_COUNTS]: { + "registry-clean": { next: { npm: { count: 1 } } }, + "registry-clean@eu": { next: { npm: { count: 2 } } }, + }, + } as unknown as DateSummary; + + it("renames a region's variations and keeps the reserved keys", () => { + const eu = projectSummary(summary, "eu") as { [key: string]: unknown }; + expect(Object.keys(eu).sort()).toEqual( + ["#packageCounts", "#versions", "clean", "registry-clean"].sort(), + ); + expect((eu["registry-clean"] as DateSummary[string])?.["next"]?.[0]?.mean).toBe(2); + expect(eu[SUMMARY_PACKAGE_COUNTS]).toEqual({ + "registry-clean": { next: { npm: { count: 2 } } }, + }); + expect(eu[SUMMARY_VERSIONS]).toEqual({ npm: "12.0.0" }); + }); +}); + +describe("DataClient regions", () => { + const recording = (body: unknown): { fetch: FetchLike; urls: string[] } => { + const urls: string[] = []; + const fetch: FetchLike = (url) => { + urls.push(url); + return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(body) }); + }; + return { fetch, urls }; + }; + + it("fetches the region's files under the plain variation name", async () => { + const { fetch, urls } = recording({}); + const client = new DataClient({ baseUrl: "https://x.test", fetch }).withRegion("eu"); + expect(client.region).toBe("eu"); + await client.getBenchmark("2026-12-01", "next", "registry-clean"); + await client.getPackageCount("2026-12-01", "next", "registry-lockfile"); + await client.getBenchmark("2026-12-01", "next", "clean"); + await client.getRegions("2026-12-01"); + expect(urls).toEqual([ + "https://x.test/2026-12-01/next-registry-clean%40eu.json", + "https://x.test/2026-12-01/next-registry-lockfile%40eu-package-count.json", + "https://x.test/2026-12-01/next-clean.json", + "https://x.test/2026-12-01/regions.json", + ]); + }); + + it("defaults to the default region and returns itself for it", () => { + const client = new DataClient({ baseUrl: "https://x.test" }); + expect(client.region).toBe("na"); + expect(client.withRegion("na")).toBe(client); + }); + + it("projects the shard it fetches", async () => { + const { fetch } = recording(entry); + const eu = await new DataClient({ + baseUrl: "https://x.test", + fetch, + region: "eu", + }).getDirectoryEntry("2026-12-01"); + expect(eu.benchmarks["vue"]).toBeUndefined(); + }); +}); diff --git a/apps/www/src/app/[section]/[[...params]]/markdown.ts b/apps/www/src/app/[section]/[[...params]]/markdown.ts index e45fd5d3c6..de3e3fa38f 100644 --- a/apps/www/src/app/[section]/[[...params]]/markdown.ts +++ b/apps/www/src/app/[section]/[[...params]]/markdown.ts @@ -131,4 +131,5 @@ export const slots = { "per-package-table": figure("per-package-table"), "package-count": figure("package-count"), "process-count": figure("process-count"), + "registry-origins": figure("registry-origins"), } satisfies Slots; diff --git a/apps/www/src/app/[section]/[[...params]]/page.tsx b/apps/www/src/app/[section]/[[...params]]/page.tsx index b632c27df5..3d778b2dac 100644 --- a/apps/www/src/app/[section]/[[...params]]/page.tsx +++ b/apps/www/src/app/[section]/[[...params]]/page.tsx @@ -31,7 +31,14 @@ import { } from "@/components/report-shell"; import { SelectionChips, type ServerChip } from "@/components/selection-chips"; import { ShowAllTools, ToolsMenu } from "@/components/tools-menu"; -import { CountTable, Leaderboard, PerFixtureTable, TrendByTool } from "@/components/sections"; +import { + CountTable, + Leaderboard, + PerFixtureTable, + RegistryOrigins, + TrendByTool, +} from "@/components/sections"; +import { SegmentedLinks } from "@/components/segmented"; import { TOCMinimap } from "@/components/toc-minimap"; import { FixtureName, ToolName } from "@/components/tool-name"; import { formatDuration, longDate } from "@/lib/findings"; @@ -44,6 +51,15 @@ import { loadCatalog } from "@/lib/catalog"; import { dataClient } from "@/lib/data"; import { averagedNote, PER_PACKAGE_DERIVED } from "@/lib/markdown"; import { loadReport } from "@/lib/report"; +import { + DEFAULT_REGION, + regionLabel, + regionShort, + runnerPhrase, + summariseRuns, + whereRunsRan, +} from "@/lib/regions"; +import { originRows } from "@/lib/registries"; import { withAverage } from "@/lib/scenarios"; import { isSectionId, SECTION_DEFS, SECTIONS } from "@/lib/sections"; import { fixtureLabel, toolLabel } from "@/lib/tools"; @@ -79,6 +95,7 @@ export const generateMetadata = async ({ reportHref(`/og${path}`, { fixture, date, + region: query.region, ...(figure === null ? {} : { hide: query.hide, range: query.range, from: query.from, to: query.to }), @@ -188,6 +205,10 @@ const Report = async ({ const report = result.report; const { scenario, run, filters, finding, baseline, caveats, trend } = report; + const regionSummary = + report.region === null || report.region.runs === null + ? null + : summariseRuns(report.region.runs); const note = scenario.averageOf === null ? null : averagedNote(scenario.averageOf, longDate); const { date } = run; const { fixture, hide: hidden } = filters; @@ -554,6 +575,31 @@ const Report = async ({ /> ), + "registry-origins": + report.region === null ? null : ( +
+ Measured from {regionLabel(report.region.current)}: {whereRunsRan(regionSummary)}. + {regionSummary !== null && regionSummary.edges.length > 0 + ? ` Cloudflare answered the runners from ${regionSummary.edges.join(", ")}.` + : ""}{" "} + First byte is the median time to the first byte of one request to each registry, sent + after the benchmark from the same runners: a distance, not a result. Plan and origin + are the benchmark account's, as each vendor describes them. + + } + > + +
+ ), }; /* The non-default selections the menus beside them do not already show, @@ -636,8 +682,7 @@ const Report = async ({ ) : ( `, averaged over ${scenario.averageOf.scenarios.length} scenarios` )} - , from the run of {longDate(date)} on GitHub-hosted{" "} - ubuntu-24.04-arm runners. + , from the run of {longDate(date)}, {runnerPhrase(report.region)}. {section === "registries" ? " Every registry is installed from with the same npm client." : ""} @@ -651,26 +696,43 @@ const Report = async ({ } action={ -
- - {run.isLatest ? null : ( - +
+ {report.region === null || report.region.available.length < 2 ? null : ( + ({ + key: r, + label: regionLabel(r), + selected: r === report.region?.current, + href: reportHref(path, { + ...query, + date: filters.date, + region: r === DEFAULT_REGION ? null : r, + }), + }))} + /> )} +
+ + {run.isLatest ? null : ( + + )} +
} /> diff --git a/apps/www/src/app/methodology/components.tsx b/apps/www/src/app/methodology/components.tsx index a6d6c571aa..0ff28898ab 100644 --- a/apps/www/src/app/methodology/components.tsx +++ b/apps/www/src/app/methodology/components.tsx @@ -2,7 +2,15 @@ import Link from "next/link"; import { Heading } from "@/components/heading"; import { InlineCode, Marked } from "@/components/inline-code"; import type { SectionScenarios } from "@/lib/page-tree"; -import { METHOD, READING, RESOURCES, RUNNER, RUNNER_NOTE, TRADEMARK } from "@/lib/metadata"; +import { + METHOD, + READING, + REGIONS_NOTE, + RESOURCES, + RUNNER, + RUNNER_NOTE, + TRADEMARK, +} from "@/lib/metadata"; import { DESCRIPTIONS, scenarioPath, stateParts } from "@/lib/scenarios"; import { SECTION_DEFS, SECTIONS } from "@/lib/sections"; @@ -27,6 +35,7 @@ export const Environment = () => ( ))}

{RUNNER_NOTE}

+

{REGIONS_NOTE}

); diff --git a/apps/www/src/app/og/[[...path]]/route.tsx b/apps/www/src/app/og/[[...path]]/route.tsx index f48e44b5fa..27b99a06d6 100644 --- a/apps/www/src/app/og/[[...path]]/route.tsx +++ b/apps/www/src/app/og/[[...path]]/route.tsx @@ -39,7 +39,7 @@ export const GET = async ( try { const search = new URL(request.url).searchParams; const asked = loadReportParams(search); - const { fixture, date } = asked; + const { fixture, date, region } = asked; const figure = ogFigure(search.get("figure")); const client = dataClient(); const index = await client.getIndex(); @@ -52,11 +52,12 @@ export const GET = async ( query: figure === null ? /* A one-run trend window: the card draws no trend, so none is fetched. */ - { ...defaults, fixture, date, from: run, to: run } + { ...defaults, fixture, date, region, from: run, to: run } : { ...defaults, fixture, date, + region, hide: asked.hide, range: asked.range, from: asked.from, diff --git a/apps/www/src/app/openapi.json/route.ts b/apps/www/src/app/openapi.json/route.ts index 6cbb53874e..46199a25a8 100644 --- a/apps/www/src/app/openapi.json/route.ts +++ b/apps/www/src/app/openapi.json/route.ts @@ -40,6 +40,11 @@ const viewParams = [ { type: "string" }, "One fixture; absent means all of them. One the scenario did not publish is a 400.", ), + query( + "region", + { type: "string", pattern: "^[a-z]{2,8}$" }, + "Registries only: the region the registry benchmarks were run from, e.g. `eu`; absent means `na`, the default. A region the run did not publish is a 400. Ignored in the other sections.", + ), query( "range", { type: "string", enum: PRESETS.map((p) => p.value), default: "1m" }, diff --git a/apps/www/src/components/sections.tsx b/apps/www/src/components/sections.tsx index dccc37d39f..f55f9c7a6c 100644 --- a/apps/www/src/components/sections.tsx +++ b/apps/www/src/components/sections.tsx @@ -6,6 +6,7 @@ import { windowChange } from "@/lib/figures"; import { formatDuration, formatVersus } from "@/lib/findings"; import type { SectionId } from "@/lib/sections"; import { fixtureLabel, toolLabel } from "@/lib/tools"; +import { popLabel, type OriginRow } from "@/lib/registries"; import { DataTable, type Column, type Row } from "@/components/data-table"; import { FixtureName, ToolName } from "@/components/tool-name"; import { SparklineECharts } from "./charts-echarts-dots"; @@ -440,3 +441,93 @@ export const CountTable = ({ return ; }; + +/* ------------------------------------------------------------------ */ +/* Where it ran (registries) */ +/* ------------------------------------------------------------------ */ + +/** + * What each registry is, beside how far it was: the plan the benchmark's + * account is on, where the vendor says it serves from, whether that plan can + * choose, and -- measured, from this region's runners -- the time to a first + * byte and the CDN edge that answered. The last two are distance, not results: + * one request each, after the benchmark, never part of a timed install. + */ +export const RegistryOrigins = ({ + rows, + regionShort, +}: { + rows: readonly OriginRow[]; + regionShort: string; +}) => { + const priced = rows.some((r) => r.deliveryPerGb !== null); + const columns: Column[] = [ + { id: "tool", label: "Registry", name: "registry" }, + { id: "plan", label: "Plan", name: "plan" }, + { id: "origin", label: "Serves from", name: "serves from" }, + { id: "choice", label: "Region choice on this plan", name: "region choice" }, + ...(priced + ? [ + { + id: "price", + label: "Delivery per GB", + name: "delivery per GB", + align: "right", + } as Column, + ] + : []), + { + id: "ttfb", + label: `First byte from ${regionShort}`, + name: `first byte from ${regionShort}`, + align: "right", + }, + { id: "pop", label: "CDN edge", name: "CDN edge" }, + ]; + const text = (value: string | null, title: string) => + value === null ? { sort: null, node: } : { sort: value, node: value }; + const tableRows: Row[] = rows.map((r) => ({ + id: r.tool, + cells: { + tool: { + sort: toolLabel(r.tool, "registries"), + node: , + }, + plan: text(r.plan, "Not recorded"), + origin: + r.origin === null + ? { sort: null, node: } + : { + sort: r.origin, + node: + r.source === null ? ( + r.origin + ) : ( + + {r.origin} + + {r.source.label} + + + ), + }, + choice: text(r.regionChoice, "Not recorded"), + ...(priced ? { price: text(r.deliveryPerGb, "Not tracked yet") } : {}), + ttfb: + r.ttfb === null + ? { sort: null, node: } + : { sort: r.ttfb, node: {Math.round(r.ttfb * 1000)}ms }, + pop: + r.pops.length === 0 + ? { sort: null, node: } + : { + sort: r.pops.join(","), + node: {r.pops.map(popLabel).join(", ")}, + }, + }, + })); + return ; +}; diff --git a/apps/www/src/components/site-footer.tsx b/apps/www/src/components/site-footer.tsx index 07e0529004..cf7bb36480 100644 --- a/apps/www/src/components/site-footer.tsx +++ b/apps/www/src/components/site-footer.tsx @@ -38,7 +38,10 @@ const LINK = * 2. The original listed the processor as "4 cores (Ampere Altra Arm)". The * model name has no source in this repository, so it is gone. The workflow * label is read off .github/workflows/benchmark.yaml, which runs every - * benchmark job on ubuntu-24.04-arm; Ubuntu 24.04 and arm64 follow from it. + * package-manager and task-runner job on ubuntu-24.04-arm; Ubuntu 24.04 and + * arm64 follow from it. Registry jobs are the exception: they run once per + * region on the runner REGISTRY_RUNNERS names (ubuntu-24.04-arm when it is + * unset), and record where they were -- see REGIONS_NOTE in lib/metadata.ts. * The remaining figures are GitHub's published specification for standard * public runners, attributed as such rather than stated as measured here. * diff --git a/apps/www/src/lib/markdown.ts b/apps/www/src/lib/markdown.ts index c028388e54..69e46abce1 100644 --- a/apps/www/src/lib/markdown.ts +++ b/apps/www/src/lib/markdown.ts @@ -15,7 +15,9 @@ import { } from "./figures"; import { formatDuration, formatVersus } from "./findings"; import { formatMs, type CountRow, type FixtureRow } from "./measurements"; -import { METHOD, RESOURCES, RUNNER, RUNNER_NOTE } from "./metadata"; +import { METHOD, REGIONS_NOTE, RESOURCES, RUNNER, RUNNER_NOTE } from "./metadata"; +import { regionLabel, runnerPhrase, summariseRuns, whereRunsRan } from "./regions"; +import { originRows, popLabel } from "./registries"; import { rowsOf } from "./chart-model"; import { rangeLabel, reportHref } from "./params"; import type { TrendPoint } from "./load"; @@ -426,9 +428,45 @@ export const figureMarkdown = (report: ReportModel, origin: string): FigureMarkd "", ], "process-count": [counts(report, report.processCounts), ""], + "registry-origins": originsMarkdown(report), }; }; +/** "Registries under test": where the runs came from, then what each registry is and how far it was. */ +const originsMarkdown = (report: ReportModel): string[] => { + if (report.region === null) return []; + const { current, runs } = report.region; + const summary = runs === null ? null : summariseRuns(runs); + const ms = (s: number | null) => (s === null ? "—" : `${Math.round(s * 1000)}ms`); + const rows = originRows([...report.ranked, ...report.unranked], summary?.registries ?? {}); + const priced = rows.some((r) => r.deliveryPerGb !== null); + return [ + `Measured from ${regionLabel(current)}: ${whereRunsRan(summary)}.${summary !== null && summary.edges.length > 0 ? ` Cloudflare answered the runners from ${summary.edges.join(", ")}.` : ""} First byte is the median time to the first byte of one request to each registry, taken after the benchmark from the same runners; it is a distance, not a result.`, + "", + table( + [ + "Registry", + "Plan", + "Serves from", + "Region choice on this plan", + ...(priced ? ["Delivery per GB"] : []), + "First byte", + "CDN edge", + ], + rows.map((r) => [ + label(report, r.tool), + r.plan ?? "—", + r.origin ?? "—", + r.regionChoice ?? "—", + ...(priced ? [r.deliveryPerGb ?? "—"] : []), + ms(r.ttfb), + r.pops.length === 0 ? "—" : r.pops.map(popLabel).join(", "), + ]), + ), + "", + ]; +}; + /** * What the per-package section says before its figures: that its numbers are * derived, and why a tool can be missing. The report's Markdown opens the @@ -502,8 +540,13 @@ export const runMarkdown = (report: ReportModel): string[] => { const fixtureCount = report.fixtures.length; return [ `- Run: ${run.date}${run.isLatest ? " (the latest run)" : ` (not the latest run; the latest is ${run.latest})`}. Results regenerate nightly.`, - `- Measured: mean ${report.measure} time ${filters.fixture === null ? `across ${fixtureCount} ${fixtureCount === 1 ? "fixture" : "fixtures"}` : `on the ${fixtureLabel(filters.fixture)} fixture`}${scenario.averageOf === null ? "" : `, averaged over ${scenario.averageOf.scenarios.length} scenarios (derived, not measured)`}, on GitHub-hosted ubuntu-24.04-arm runners.${section.id === "registries" ? " Every registry is installed from with the same npm client." : ""}`, + `- Measured: mean ${report.measure} time ${filters.fixture === null ? `across ${fixtureCount} ${fixtureCount === 1 ? "fixture" : "fixtures"}` : `on the ${fixtureLabel(filters.fixture)} fixture`}${scenario.averageOf === null ? "" : `, averaged over ${scenario.averageOf.scenarios.length} scenarios (derived, not measured)`}, ${runnerPhrase(report.region)}.${section.id === "registries" ? " Every registry is installed from with the same npm client." : ""}`, `- Filters in effect:`, + ...(report.region === null + ? [] + : [ + ` - region: ${report.region.current} (${regionLabel(report.region.current)}); this run published ${report.region.available.join(", ")}`, + ]), ` - fixture: ${filters.fixture === null ? `all (${report.fixtures.join(", ")})` : filters.fixture}`, ` - trend window: ${filters.window.custom ? "custom" : rangeLabel(filters.range).toLowerCase()}, ${filters.window.from} to ${filters.window.to}`, ` - trend metric: ${METRIC_TEXT[metric].name}`, @@ -549,6 +592,7 @@ export const referenceMarkdown = (report: ReportModel, origin: string): string[] "", RUNNER_NOTE, "", + ...(report.region === null ? [] : [REGIONS_NOTE, ""]), "## Data & source", "", ...report.raw.map((r) => `- Raw results, ${r.label} (JSON): ${r.href}`), @@ -653,6 +697,10 @@ export const reportMarkdown = (report: ReportModel, origin: string): string => { } } + if (items.has("registry-origins")) { + add("## Where it ran", "", "### Registries under test", "", ...body("registry-origins")); + } + add(...referenceMarkdown(report, origin)); return lines.join("\n"); }; diff --git a/apps/www/src/lib/mcp.ts b/apps/www/src/lib/mcp.ts index c3a45a68af..b2b97d90ae 100644 --- a/apps/www/src/lib/mcp.ts +++ b/apps/www/src/lib/mcp.ts @@ -27,6 +27,12 @@ const scenario = z "A scenario of the benchmark, e.g. clean or cache+lockfile, or average: the derived mean of them. list_benchmarks lists them.", ); const fixture = z.string().min(1).describe("One fixture; omitted means all of them."); +const region = z + .string() + .regex(/^[a-z]{2,8}$/, "A region id, e.g. na or eu.") + .describe( + "Registries only: the region the registry benchmarks were run from, e.g. eu; omitted means na.", + ); const tools = z.array(z.string().min(1)).describe("Tool keys, e.g. bun, npm; omitted means all."); export const inputs = { @@ -36,6 +42,7 @@ export const inputs = { scenario, date: date.optional().describe("A published run; omitted means the latest."), fixture: fixture.optional(), + region: region.optional(), hide: tools.optional().describe("Tools left out of the tables; rankings still count them."), metric: z.enum(METRICS).optional().describe("What the trend holds. Only total is measured."), }), @@ -48,6 +55,7 @@ export const inputs = { .optional() .describe("Window end, a published date. Omitted: the 30 days to the latest run."), fixture: fixture.optional(), + region: region.optional(), metric: z.enum(METRICS).optional(), exclude: z .array(z.string().regex(/^([^@]+@)?\d{4}-\d{2}-\d{2}$/, "YYYY-MM-DD or tool@YYYY-MM-DD.")) @@ -119,6 +127,7 @@ export const getResults = async ( const query = loadReportParams({ date: args.date, fixture: args.fixture, + region: args.region, hide: list(args.hide), metric: args.metric, }); @@ -135,6 +144,7 @@ export const getHistory = async ( ): Promise => { const query = loadReportParams({ fixture: args.fixture, + region: args.region, from: args.from, to: args.to, metric: args.metric, diff --git a/apps/www/src/lib/metadata.ts b/apps/www/src/lib/metadata.ts index afec204fa7..58f246dc11 100644 --- a/apps/www/src/lib/metadata.ts +++ b/apps/www/src/lib/metadata.ts @@ -129,6 +129,14 @@ export const RESOURCES = [ export const RUNNER_NOTE = "The label is read from the workflow. The remaining figures are GitHub's published specification for standard public runners, not measurements taken here."; +/** + * Registry benchmarks are the one kind run from more than one place. Kept + * conditional ("can be run") on purpose: which regions ran on a night is in + * that night's data, and a registry page names the region it shows. + */ +export const REGIONS_NOTE = + "Registry benchmarks are the exception. They measure the network between the runner and each registry, so where the runner sits is part of the result: they can be run from more than one region (North America, and Europe), each on a runner pinned to that region, and every job records where it actually ran, from the cloud's own metadata, and which CDN edge answered it. A registry page names the region it shows and offers every other region its run published. Registry runs from before regions were recorded used the runner above, wherever GitHub placed it."; + export const TRADEMARK = "All trademarks, logos and brand names are the property of their respective owners. All company, product and service names used on this site are for identification purposes only. Use of these names, trademarks and brands does not imply endorsement."; diff --git a/apps/www/src/lib/methodology-markdown.ts b/apps/www/src/lib/methodology-markdown.ts index 57dfc413ac..cb14cb0d44 100644 --- a/apps/www/src/lib/methodology-markdown.ts +++ b/apps/www/src/lib/methodology-markdown.ts @@ -1,5 +1,13 @@ import { mdxMarkdown, mdxSource } from "@/lib/mdx"; -import { METHOD, READING, RESOURCES, RUNNER, RUNNER_NOTE, TRADEMARK } from "@/lib/metadata"; +import { + METHOD, + READING, + REGIONS_NOTE, + RESOURCES, + RUNNER, + RUNNER_NOTE, + TRADEMARK, +} from "@/lib/metadata"; import type { SectionScenarios } from "@/lib/page-tree"; import { DESCRIPTIONS, scenarioPath, stateParts } from "@/lib/scenarios"; import { SECTION_DEFS, SECTIONS } from "@/lib/sections"; @@ -14,6 +22,8 @@ export const methodologyMarkdown = (scenarios: SectionScenarios, origin: string) ...RUNNER.map(([term, value]) => `- ${term}: \`${value}\``), "", RUNNER_NOTE, + "", + REGIONS_NOTE, ), Reading: lines(...READING.map((line) => `- ${line}`)), Scenarios: SECTIONS.map((section) => diff --git a/apps/www/src/lib/outline.ts b/apps/www/src/lib/outline.ts index 8a338445e4..c38ce4c1c5 100644 --- a/apps/www/src/lib/outline.ts +++ b/apps/www/src/lib/outline.ts @@ -32,6 +32,12 @@ export interface OutlineInput { /** Fixtures with a process-count file for this variation. */ readonly processCountFixtures: readonly string[]; readonly isScript: boolean; + /** + * Registries only: add where the runs came from and what each registry is + * (plan, origin, whether the plan lets the account choose). Registry numbers + * depend on that in a way a client's do not, so they are not read alone. + */ + readonly registries?: boolean; } const plural = (n: number, one: string, many: string): string => `${n} ${n === 1 ? one : many}`; @@ -100,6 +106,15 @@ export const buildOutline = (input: OutlineInput): OutlineSection[] => { }); } + if (input.registries === true) { + sections.push({ + id: "where", + title: "Where it ran", + summary: "The region these runs came from, and where each registry serves from", + items: [table("registry-origins", "Registries under test")], + }); + } + return sections; }; diff --git a/apps/www/src/lib/params.ts b/apps/www/src/lib/params.ts index a11241d0b8..54a17c2162 100644 --- a/apps/www/src/lib/params.ts +++ b/apps/www/src/lib/params.ts @@ -77,6 +77,13 @@ export const reportParams = { date: parseAsString, /** SERVER. One fixture; absent means all of them, averaged. */ fixture: parseAsString, + /** + * SERVER. Registries only: the region the registry benchmarks were run from + * (`eu`). Absent means the default region, `na` -- the only one there was + * before regions -- so every existing link means what it meant. Anywhere + * else, and on a run that did not publish the region, it is ignored. + */ + region: parseAsString, /** SERVER. A preset trend window, ending at the run shown; see `PRESETS`. */ range: parseAsRange.withDefault("1m"), /** SERVER. An exact trend window. Both must be published dates; see `trendWindow`. */ diff --git a/apps/www/src/lib/regions.ts b/apps/www/src/lib/regions.ts new file mode 100644 index 0000000000..c35301f076 --- /dev/null +++ b/apps/www/src/lib/regions.ts @@ -0,0 +1,160 @@ +/** + * Regions: where a registry benchmark was run from, in words. + * + * The id (`na`, `eu`) is the key the data uses (see `@benchmarks/types`). Its + * NAME lives here. What the region actually was on a given night -- which + * cloud, which data centre -- is never written here: it is read from that + * night's `regions.json`, which each job filled in from where it found itself. + * A label here says what we meant; the record says what happened. + */ +import { DEFAULT_REGION, isRegionId, type RegionId, type RegionRun } from "@benchmarks/types"; + +export { DEFAULT_REGION }; + +const NAMES: { readonly [region: string]: { readonly label: string; readonly short: string } } = { + na: { label: "North America", short: "NA" }, + eu: { label: "Europe", short: "EU" }, + apac: { label: "Asia-Pacific", short: "APAC" }, +}; + +/** "North America"; an id with no entry is shown as published, upper-cased. */ +export const regionLabel = (region: RegionId): string => + NAMES[region]?.label ?? region.toUpperCase(); + +export const regionShort = (region: RegionId): string => + NAMES[region]?.short ?? region.toUpperCase(); + +/** + * The region a page shows: the one asked for when this run published it, + * else the default. A region the run did not publish is ignored, as a stale + * fixture is, rather than answered with an empty page. + */ +export const resolveRegion = (asked: string | null, available: readonly RegionId[]): RegionId => + asked !== null && isRegionId(asked) && available.includes(asked) ? asked : DEFAULT_REGION; + +const PROVIDERS: { readonly [provider: string]: string } = { + aws: "AWS", + azure: "Azure", + gcp: "Google Cloud", +}; + +const providerLabel = (provider: string | undefined): string => + provider === undefined ? "Unknown cloud" : (PROVIDERS[provider] ?? provider); + +/** Distinct values with how many runs had each, most common first. */ +const tally = (values: readonly (string | undefined)[]): { value: string; count: number }[] => { + const counts = new Map(); + for (const v of values) if (v !== undefined && v !== "") counts.set(v, (counts.get(v) ?? 0) + 1); + return [...counts] + .map(([value, count]) => ({ value, count })) + .sort((a, b) => b.count - a.count || a.value.localeCompare(b.value)); +}; + +const median = (values: readonly number[]): number | null => { + const sorted = values.filter(Number.isFinite).sort((a, b) => a - b); + const mid = Math.floor(sorted.length / 2); + const upper = sorted[mid]; + if (upper === undefined) return null; + const lower = sorted.length % 2 === 1 ? upper : (sorted[mid - 1] ?? upper); + return (lower + upper) / 2; +}; + +export interface RegionSummary { + /** Jobs that recorded anything. */ + readonly jobs: number; + /** What the workflow asked for, e.g. "AWS eu-central-1 (Frankfurt)". */ + readonly requested: readonly string[]; + /** Where the jobs found themselves, e.g. "AWS eu-central-1", with how many jobs each. */ + readonly clouds: readonly { readonly value: string; readonly count: number }[]; + /** Jobs whose cloud could not be read. */ + readonly unlocated: number; + /** The Cloudflare data centres that answered the runners. */ + readonly edges: readonly string[]; + /** "4 vCPU ARM64", per job shape seen. */ + readonly machines: readonly string[]; + /** Per registry: the median of each job's median time to first byte, and the CDN PoPs seen. */ + readonly registries: { + readonly [registry: string]: + | { readonly ttfb: number | null; readonly pops: readonly string[]; readonly jobs: number } + | undefined; + }; +} + +/** One region's jobs on one night, summarised for a sentence and a table. */ +export const summariseRuns = (runs: readonly RegionRun[]): RegionSummary => { + const located = runs.filter((r) => r.cloud?.region !== undefined); + const registries: { [registry: string]: { ttfb: number | null; pops: string[]; jobs: number } } = + {}; + const names = [...new Set(runs.flatMap((r) => Object.keys(r.registries ?? {})))].sort(); + for (const name of names) { + const probes = runs.flatMap((r) => { + const p = r.registries?.[name]; + return p === undefined ? [] : [p]; + }); + registries[name] = { + ttfb: median(probes.flatMap((p) => (typeof p.ttfb === "number" ? [p.ttfb] : []))), + pops: tally(probes.map((p) => p.pop)).map((t) => t.value), + jobs: probes.length, + }; + } + return { + jobs: runs.length, + requested: tally(runs.map((r) => r.requested)).map((t) => t.value), + clouds: tally(located.map((r) => `${providerLabel(r.cloud?.provider)} ${r.cloud?.region}`)), + unlocated: runs.length - located.length, + edges: tally(runs.map((r) => r.edge?.colo)).map((t) => t.value), + machines: tally( + runs.map((r) => + r.cpus === undefined ? undefined : `${r.cpus} vCPU ${(r.arch ?? "").toUpperCase()}`.trim(), + ), + ).map((t) => t.value), + registries, + }; +}; + +/** + * Where a region's runs came from, as a phrase for the lede: "AWS eu-central-1", + * "Azure eastus2 (7 jobs) and AWS us-east-1 (5 jobs)", or -- with nothing + * recorded -- what was asked for, or that it was not recorded. + */ +export const whereRunsRan = (summary: RegionSummary | null): string => { + if (summary === null || summary.jobs === 0) return "a runner whose location was not recorded"; + const { clouds, requested, unlocated } = summary; + if (clouds.length === 0) { + const [asked] = requested; + return requested.length === 1 && asked !== undefined + ? `${asked} (location not confirmed by the runner)` + : "runners whose location was not recorded"; + } + const only = clouds[0]; + if (clouds.length === 1 && only !== undefined && unlocated === 0) return only.value; + const parts = clouds.map((c) => `${c.value} (${c.count} ${c.count === 1 ? "job" : "jobs"})`); + if (unlocated > 0) parts.push(`unknown (${unlocated} ${unlocated === 1 ? "job" : "jobs"})`); + const last = parts.pop(); + return parts.length === 0 ? (last ?? "") : `${parts.join(", ")} and ${last}`; +}; + +/** + * How the lede and the Markdown twin say where a report's runs came from. + * + * Package managers and task runners: the suite's runner, as it always was. + * Registries: the region, and where its jobs recorded they were -- or, on a + * date before anything was recorded, the runner every registry run then used, + * with its location stated as unrecorded rather than assumed. + */ +export const runnerPhrase = ( + region: { + readonly current: RegionId; + readonly available: readonly RegionId[]; + readonly runs: readonly RegionRun[] | null; + } | null, +): string => { + const legacy = "on GitHub-hosted ubuntu-24.04-arm runners"; + if (region === null) return legacy; + if (region.runs === null || region.runs.length === 0) { + return region.current === DEFAULT_REGION + ? `${legacy} (location not recorded)` + : `measured from ${regionLabel(region.current)} (runner location not recorded)`; + } + return `measured from ${regionLabel(region.current)}, on ${whereRunsRan(summariseRuns(region.runs))}`; +}; diff --git a/apps/www/src/lib/registries.ts b/apps/www/src/lib/registries.ts new file mode 100644 index 0000000000..a5318c17e3 --- /dev/null +++ b/apps/www/src/lib/registries.ts @@ -0,0 +1,135 @@ +/** + * What each registry under test IS, as distinct from how fast it was: the plan + * the benchmark's account is on, where the vendor says it serves from, and + * whether that plan lets the account choose. + * + * It matters to the numbers. A registry that serves from one place is fast near + * it and slow far from it, and on some plans that place cannot be changed -- + * Cloudsmith's Pro plan stores every repository in Dublin, so its North + * American numbers carry an Atlantic crossing no setting on that plan removes. + * The benchmark uses the cheapest plan each vendor offers that can host it (the + * free tier where there is one), and says so here rather than letting a reader + * assume an enterprise configuration. + * + * Hand-maintained, and the one place in the site that is: these are account + * facts, not measurements. `null` means "not yet written down", and the page + * shows it as missing rather than guessing. Measured location -- where the + * runner was, and which CDN edge answered it -- comes from each run's + * `regions.json`, never from here. + */ + +export interface RegistryFacts { + /** The plan the benchmark account is on. */ + readonly plan: string; + /** Where responses come from, as far as the vendor says; `null` when not yet recorded. */ + readonly origin: string | null; + /** Whether this plan lets the account choose where the registry serves from; `null` when not yet recorded. */ + readonly regionChoice: string | null; + /** + * Delivery (egress) price per GB on this plan, once it is tracked. Absent + * everywhere for now: the column appears when any registry has a value. + */ + readonly deliveryPerGb?: string; + /** Where a reader can check the plan or region claim. */ + readonly source?: { readonly label: string; readonly href: string }; +} + +export const REGISTRY_FACTS: { readonly [registry: string]: RegistryFacts | undefined } = { + npm: { + plan: "Free (the public registry)", + origin: "Cloudflare's CDN, in front of an origin npm does not publish", + regionChoice: "No", + }, + vlt: { + plan: "Free", + // TODO: where registry.vlt.io serves from (edge network and origin region), + // and whether a vlt registry can be pinned to a region. + origin: null, + regionChoice: null, + }, + aws: { + plan: "Pay as you go (no tiers)", + origin: "AWS us-east-1 (N. Virginia)", + regionChoice: "Yes: a CodeArtifact domain lives in the region it is created in", + source: { + label: "AWS CodeArtifact pricing", + href: "https://aws.amazon.com/codeartifact/pricing/", + }, + }, + cloudsmith: { + plan: "Pro", + origin: "Dublin, Ireland (Cloudsmith's default storage region)", + regionChoice: "Not on Pro: custom storage regions need Ultra or Enterprise", + source: { + label: "Cloudsmith: custom storage regions", + href: "https://docs.cloudsmith.com/repositories/custom-storage-regions", + }, + }, + github: { + plan: "Free", + origin: null, + regionChoice: "No (github.com)", + }, + jfrog: { + plan: "Pro", + // TODO: the cloud and region the benchmark's JFrog instance was created in. + origin: null, + regionChoice: "Yes: chosen when the instance is created (AWS, Google Cloud or Azure)", + source: { label: "JFrog pricing", href: "https://jfrog.com/pricing/" }, + }, +}; + +export const registryFacts = (registry: string): RegistryFacts | undefined => + REGISTRY_FACTS[registry]; + +/** One row of the "Registries under test" table: what a registry is, and how far it was from this region's runners. */ +export interface OriginRow { + readonly tool: string; + readonly plan: string | null; + readonly origin: string | null; + readonly regionChoice: string | null; + readonly deliveryPerGb: string | null; + /** Median time to first byte for one request to the registry, from this region; seconds. */ + readonly ttfb: number | null; + /** CDN points of presence its responses named, most common first. */ + readonly pops: readonly string[]; + readonly source: NonNullable | null; +} + +/** The table's rows, in the order the report ranks the registries. */ +export const originRows = ( + tools: readonly string[], + measured: { + readonly [registry: string]: + | { readonly ttfb: number | null; readonly pops: readonly string[] } + | undefined; + }, +): OriginRow[] => + tools.map((tool) => { + const facts = registryFacts(tool); + const probe = measured[tool]; + return { + tool, + plan: facts?.plan ?? null, + origin: facts?.origin ?? null, + regionChoice: facts?.regionChoice ?? null, + deliveryPerGb: facts?.deliveryPerGb ?? null, + ttfb: probe?.ttfb ?? null, + pops: probe?.pops ?? [], + source: facts?.source ?? null, + }; + }); + +/** A PoP as recorded (`cloudflare:FRA`) in words: "Cloudflare FRA". */ +export const popLabel = (pop: string): string => { + const [cdn, where] = pop.split(":"); + const name = + cdn === "cloudflare" + ? "Cloudflare" + : cdn === "cloudfront" + ? "CloudFront" + : cdn === "fastly" + ? "Fastly" + : (cdn ?? pop); + return where === undefined ? name : `${name} ${where}`; +}; diff --git a/apps/www/src/lib/report.ts b/apps/www/src/lib/report.ts index 509e9b7b29..a393f9e830 100644 --- a/apps/www/src/lib/report.ts +++ b/apps/www/src/lib/report.ts @@ -8,8 +8,19 @@ * and the same file is the source of the section lists this report refuses * to trust. */ -import { benchmarkFile, summaryVersions, type DataClient } from "@benchmarks/data"; -import type { Fixture, Versions } from "@benchmarks/types"; +import { + benchmarkFile, + publishedVariation, + summaryVersions, + type DataClient, +} from "@benchmarks/data"; +import { + DEFAULT_REGION, + type Fixture, + type RegionId, + type RegionRun, + type Versions, +} from "@benchmarks/types"; import type { inferParserType } from "nuqs/server"; import { publishedVariations } from "./catalog"; import { rowsOf, toDenseSeries, type DenseSeries } from "./chart-model"; @@ -30,6 +41,7 @@ import { } from "./measurements"; import { buildOutline, fixturesWith, type OutlineSection } from "./outline"; import { reportHref, reportParams, trendWindow } from "./params"; +import { resolveRegion } from "./regions"; import { DESCRIPTIONS, scenarioPath, @@ -117,6 +129,16 @@ export interface ReportModel { /** Every published date, ascending. */ readonly dates: readonly string[]; }; + /** + * Registries only (`null` elsewhere): which region's runs these numbers are + * from, which regions this run published, and where this region's jobs + * actually ran, as they recorded it (`null` on a date that recorded nothing). + */ + readonly region: { + readonly current: RegionId; + readonly available: readonly RegionId[]; + readonly runs: readonly RegionRun[] | null; + } | null; /** The scenario's page, unpinned. */ readonly path: string; /** The selections in effect, as resolved: a value the report ignored is not here. */ @@ -274,8 +296,8 @@ const partialNotes = (tools: readonly string[], section: SectionId): ReportNote[ export const loadReport = async ({ section, scenario, - query, - client = dataClient(), + query: asked, + client: base = dataClient(), }: { section: string; scenario?: string; @@ -284,13 +306,27 @@ export const loadReport = async ({ }): Promise => { if (!isSectionId(section)) return { status: "unknown-section", section }; const def = SECTION_DEFS[section]; - const index = await client.getIndex(); + const index = await base.getIndex(); /* A date the archive does not hold falls back to the latest, not to a 404. */ - const pinned = query.date !== null && index.dates.includes(query.date) ? query.date : null; + const pinned = asked.date !== null && index.dates.includes(asked.date) ? asked.date : null; const date = pinned ?? index.latest; if (date === null || index.latest === null) return { status: "no-dates", section }; + /* + * Registries can be run from more than one region; the page shows one at a + * time, through a client that names that region's files as the plain + * variations (apps/data, src/regions.ts) -- so everything below, the trend + * and the average included, is the same code for every region. A region this + * run did not publish is ignored, like a stale fixture. Elsewhere the + * parameter means nothing and is dropped. + */ + const regions = section === "registries" ? await base.getPublishedRegions(date) : []; + const region = section === "registries" ? resolveRegion(asked.region, regions) : DEFAULT_REGION; + const query: ReportQuery = { ...asked, region: region === DEFAULT_REGION ? null : region }; + const client = base.withRegion(region); + const recorded = section === "registries" ? await probe(() => client.getRegions(date)) : null; + const entry = await client.getDirectoryEntry(date); const scenarios = scenariosFor(section, publishedVariations(entry)); const listed = withAverage(scenarios); @@ -342,6 +378,7 @@ export const loadReport = async ({ const isScript = selected.kind === "other" && section === "task-runners"; const outline = buildOutline({ + registries: section === "registries", fixtures, packageCountFixtures: fixturesWith(entry.packageCounts, selected.variation).filter((f) => fixtures.includes(f), @@ -606,6 +643,14 @@ export const loadReport = async ({ }, }, run: { date, latest: index.latest, isLatest: date === index.latest, dates: index.dates }, + region: + section === "registries" + ? { + current: region, + available: regions.length === 0 ? [DEFAULT_REGION] : regions, + runs: recorded?.state === "present" ? (recorded.value[region]?.runs ?? null) : null, + } + : null, path, filters: { date: pinned, @@ -701,13 +746,19 @@ export const loadReport = async ({ fixture: b.fixture, scenario: selected.variation, label: fixtureLabel(b.fixture), - href: client.url(date, benchmarkFile(b.fixture as Fixture, selected.variation)), + href: client.url( + date, + benchmarkFile(b.fixture as Fixture, publishedVariation(selected.variation, region)), + ), })) : average.cells.map((c) => ({ fixture: c.fixture, scenario: c.variation, label: `${fixtureLabel(c.fixture)} · ${c.variation}`, - href: client.url(date, benchmarkFile(c.fixture as Fixture, c.variation)), + href: client.url( + date, + benchmarkFile(c.fixture as Fixture, publishedVariation(c.variation, region)), + ), })), citation: { ...citeFor({ benchmark: def.label, scenario: selected.variation, date }), @@ -725,6 +776,9 @@ export const ignoredSelection = (query: ReportQuery, report: ReportModel): strin if (query.date !== null && report.filters.date === null) { return `No run was published on ${query.date}.`; } + if (query.region !== null && report.region !== null && query.region !== report.region.current) { + return `No registry results from region "${query.region}" were published on ${report.run.date}. Regions: ${report.region.available.join(", ")}.`; + } if (query.fixture !== null && report.filters.fixture === null) { return `The ${report.scenario.variation} scenario published no "${query.fixture}" fixture on ${report.run.date}. Fixtures: ${report.publishedFixtures.join(", ")}.`; } diff --git a/apps/www/test/fixture-tree.ts b/apps/www/test/fixture-tree.ts index f64511e86f..94d37de029 100644 --- a/apps/www/test/fixture-tree.ts +++ b/apps/www/test/fixture-tree.ts @@ -47,7 +47,13 @@ DATES.forEach((date, i) => { name: date, isLatest: false, fileCount: 0, - benchmarks: { astro: ["clean", "registry-clean"], babylon: ["clean", "registry-clean"] }, + benchmarks: + i === DATES.length - 1 + ? { + astro: ["clean", "registry-clean", "registry-clean@eu"], + babylon: ["clean", "registry-clean", "registry-clean@eu"], + } + : { astro: ["clean", "registry-clean"], babylon: ["clean", "registry-clean"] }, packageCounts: { astro: ["clean"], babylon: ["clean"] }, processCounts: {}, hasChartData: false, @@ -72,8 +78,32 @@ DATES.forEach((date, i) => { put(`${date}/${fixture}-registry-clean.json`, { results: [result("npm", 20 * scale), result("vlt", 8 * scale)], }); + /* The latest run also ran registries from Europe, where npm is closer and vlt is not. */ + if (date === DATES.at(-1)) { + put(`${date}/${fixture}-registry-clean@eu.json`, { + results: [result("npm", 12), result("vlt", 6), result("cloudsmith", 9)], + }); + } } }); +/* Where the latest run's registry jobs ran: one region recorded, one not. */ +put(`${DATES.at(-1)}/regions.json`, { + eu: { + runs: FIXTURES.map((fixture) => ({ + fixture, + variation: "registry-clean", + requested: "AWS eu-central-1 (Frankfurt)", + arch: "ARM64", + cpus: 4, + cloud: { provider: "aws", region: "eu-central-1", zone: "eu-central-1a" }, + edge: { colo: "FRA", country: "DE" }, + registries: { + npm: { status: 200, ttfb: fixture === "astro" ? 0.01 : 0.03, pop: "cloudflare:FRA" }, + cloudsmith: { status: 200, ttfb: 0.04 }, + }, + })), + }, +}); /** What `fetch` would answer for a URL on the fake data origin. */ export const fakeFetch = async (url: string | URL | Request) => { diff --git a/apps/www/test/report.test.ts b/apps/www/test/report.test.ts index 6c50b18ce7..2d87096537 100644 --- a/apps/www/test/report.test.ts +++ b/apps/www/test/report.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { rowsOf, toTrendColumns, trendOf, type TrendRun } from "../src/lib/chart-model.ts"; import { loadReportParams } from "../src/lib/params.ts"; import { ignoredSelection, loadReport, type ReportModel } from "../src/lib/report.ts"; +import { reportMarkdown, runMarkdown } from "../src/lib/markdown.ts"; import { DataClient } from "@benchmarks/data"; import { loadScenario, loadSummaries, TREND_BUDGET } from "../src/lib/load.ts"; import { DATA_URL, DATES, fakeFetch, fixtureClient, summarisedClient } from "./fixture-tree.ts"; @@ -267,3 +268,82 @@ describe("the trend's run detail by column", () => { expect(JSON.stringify(toTrendColumns(runs)).length).toBeLessThan(JSON.stringify(runs).length); }); }); + +describe("registry regions", () => { + const registries = async (search = "") => { + const result = await load("registry-clean", search, "registries"); + if (result.status !== "ok") throw new Error(result.status); + return result.report; + }; + + it("shows the default region, and says which regions the run published", async () => { + const r = await registries(); + expect(r.region?.current).toBe("na"); + expect(r.region?.available).toEqual(["na", "eu"]); + // Nothing recorded for na on this run: the page says so rather than guessing. + expect(r.region?.runs).toBeNull(); + expect(r.tools).toEqual(["npm", "vlt"]); + expect(r.raw.map((f) => f.href)).toEqual([ + `${DATA_URL}/2026-10-13/astro-registry-clean.json`, + `${DATA_URL}/2026-10-13/babylon-registry-clean.json`, + ]); + }); + + it("reads another region's files under the same scenario", async () => { + const r = await registries("region=eu"); + expect(r.region?.current).toBe("eu"); + expect(r.scenario.variation).toBe("registry-clean"); + expect([...r.tools].sort()).toEqual(["cloudsmith", "npm", "vlt"]); + expect(r.leaderboard.find((row) => row.tool === "npm")?.mean).toBeCloseTo(12); + expect(r.region?.runs?.[0]?.cloud?.region).toBe("eu-central-1"); + expect(r.raw.map((f) => f.href)).toEqual([ + `${DATA_URL}/2026-10-13/astro-registry-clean%40eu.json`, + `${DATA_URL}/2026-10-13/babylon-registry-clean%40eu.json`, + ]); + expect(r.citation.path).toContain("region=eu"); + expect(r.outline.at(-1)?.id).toBe("where"); + }); + + it("never fills another region's trend with the default region's runs", async () => { + const r = await registries("region=eu&range=all"); + const npm = rowsOf(r.trend.series).map((row) => row["npm"] ?? null); + // Only the latest run published Europe; the earlier runs are holes, not North America. + expect(npm.filter((v) => v !== null)).toHaveLength(1); + }); + + it("ignores a region the run did not publish, and a strict reader is told", async () => { + const query = loadReportParams(new URLSearchParams("region=apac")); + const r = await registries("region=apac"); + expect(r.region?.current).toBe("na"); + expect(ignoredSelection(query, r)).toMatch(/region "apac"/); + // ...and on an older run, Europe is ignored the same way. + const old = await registries("region=eu&date=2026-10-12"); + expect(old.region).toMatchObject({ current: "na", available: ["na"] }); + }); + + it("says where the runs came from, and what each registry is, in the twin", async () => { + const eu = await registries("region=eu"); + const text = reportMarkdown(eu, "https://bench.test"); + expect(runMarkdown(eu).join("\n")).toContain("measured from Europe, on AWS eu-central-1."); + expect(runMarkdown(eu).join("\n")).toContain( + " - region: eu (Europe); this run published na, eu", + ); + expect(text).toContain("## Where it ran"); + expect(text).toContain( + "Measured from Europe: AWS eu-central-1. Cloudflare answered the runners from FRA.", + ); + expect(text).toMatch(/\| Cloudsmith \| Pro \| Dublin, Ireland .* \| 40ms \| — \|/); + expect(text).toMatch(/\| registry\.npmjs\.org \| Free .* \| 20ms \| Cloudflare FRA \|/); + // The default region on this run recorded nothing, and says so. + const na = await registries(); + expect(runMarkdown(na).join("\n")).toContain( + "on GitHub-hosted ubuntu-24.04-arm runners (location not recorded).", + ); + }); + + it("means nothing outside registries", async () => { + const r = await report("region=eu"); + expect(r.region).toBeNull(); + expect(r.citation.path).not.toContain("region"); + }); +}); diff --git a/docs/METHODOLOGY.md b/docs/METHODOLOGY.md index edb6323c9e..ec9c015836 100644 --- a/docs/METHODOLOGY.md +++ b/docs/METHODOLOGY.md @@ -284,6 +284,80 @@ performance. Registries observed in the published data: `npm`, `vlt`, `aws`, `aws` requires `CODEARTIFACT_AUTH_TOKEN`. Locally you can narrow the set with `--registries`. +### Regions + +A registry benchmark measures the network between the runner and each +registry as much as the registry itself, so **where the runner sits is part of +the result**. Cloudsmith's Pro plan, for example, serves every repository from +Dublin and cannot be moved; from a runner in Virginia each request crosses the +Atlantic. So the `registry-*` variations are run once **per region**, each on a +runner pinned to that region. Nothing else is: package-manager and task-runner +variations measure the client and run once, on `ubuntu-24.04-arm`. + +**Which regions.** Two, chosen to be where most of each continent's compute +and traffic already is, rather than next to any one registry: + +| id | Region | Pin its runners to | +| ---- | ------------- | ------------------------------------------------- | +| `na` | North America | US East (N. Virginia, `us-east-1` / `eastus`) | +| `eu` | Europe | Frankfurt (`eu-central-1` / `germanywestcentral`) | + +Frankfurt hosts a region of every major cloud and one of the world's largest +internet exchanges. Dublin (`eu-west-1`) would put the runner beside Cloudsmith's origin +and is deliberately not the default. Asia-Pacific (`apac`) can be added the +same way. + +**Publishing.** The default region, `na`, is published exactly as before, +without a suffix (`next-registry-clean.json`), so the archive keeps one +continuous series. Every other region appends `@` to the variation: +`next-registry-clean@eu.json`, `next-registry-clean@eu-package-count.json`. +`apps/data`'s client shows one region at a time under the plain variation +names, and hides the others; the site's registry pages take `?region=eu`. + +**Where it actually ran.** After its benchmark, each registry job runs +`suite/scripts/registry/runner-info.sh`, which records, without any IP address: +the cloud, region, zone and instance type from the cloud's instance metadata +service (Azure, AWS or Google); the Cloudflare data centre that answered the +runner; and, for each registry, the median of three timed requests to its base +URL (connect, TLS, first byte) and the CDN point of presence a response header +names. It runs after the benchmark so it cannot warm anything the benchmark +measures. `process-results.sh` gathers every job's record into +`/{date}/regions.json`, keyed by region. Before regions existed nothing was +recorded; those runs used GitHub-hosted runners wherever GitHub placed them +(GitHub-hosted Linux runners can land on Azure or AWS). + +**Configuring runners.** The workflow reads the `REGISTRY_RUNNERS` repository +variable: a JSON object from region id to the `runs-on` value for that +region's jobs and a description that is published as what was asked for. +`{run_id}` is replaced with the workflow run id. Unset, only `na` runs, on +`ubuntu-24.04-arm`, as before. For example, with [RunsOn](https://runs-on.com) +stacks deployed in `us-east-1` and `eu-central-1`: + +```json +{ + "na": { + "runs-on": "runs-on={run_id}/cpu=4/ram=16/family=m8g/image=ubuntu24-full-arm64/spot=false/region=us-east-1", + "label": "AWS us-east-1 (N. Virginia), 4 vCPU Graviton" + }, + "eu": { + "runs-on": "runs-on={run_id}/cpu=4/ram=16/family=m8g/image=ubuntu24-full-arm64/spot=false/region=eu-central-1", + "label": "AWS eu-central-1 (Frankfurt), 4 vCPU Graviton" + } +} +``` + +or, with GitHub larger runners on Azure private networking (x64 only outside +the US), a runner group per region: +`{"na": {"runs-on": {"group": "registry-na"}, "label": "..."}, "eu": {...}}`. + +Use the same machine shape in every region, so the region is the only thing +that changes between them. A region other than `na` is `continue-on-error`: +if its runners fail, every other result still publishes and that region is +missing for the night. A job waiting for a self-hosted runner that never comes +waits in the queue, so watch a new region's first nights. The `regions` +dispatch input runs a subset; anything but the default is a partial run and +does not deploy. + ## Script execution: the `run` fixture Spawning a process is a small part of any real build, but it is a workflow diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts index 72827cb654..3633bb5eb1 100644 --- a/packages/types/src/index.ts +++ b/packages/types/src/index.ts @@ -134,6 +134,131 @@ export type RegistryName = "aws" | "cloudsmith" | "github" | "jfrog" | "npm" | " /** Either kind of series name. */ export type SeriesName = PackageManager | RegistryName; +// --------------------------------------------------------------------------- +// Regions -- where a `registry-*` benchmark ran from +// --------------------------------------------------------------------------- + +/** + * Registry benchmarks measure the network between a runner and a registry, so + * where the runner sits changes the answer: a registry whose origin is in + * Dublin looks slow from Virginia and fast from Frankfurt. So the `registry-*` + * variations can be run from more than one region; nothing else is, because + * package-manager and task-runner variations measure the client. + * + * The default region is published exactly as before, WITHOUT a suffix: + * `next-registry-clean.json` is the North American run, as every registry file + * since 2026-02-27 has been. Any other region appends `@{region}` to the + * variation: `next-registry-clean@eu.json`. So the archive keeps one + * continuous series for the default region, and a reader that knows nothing of + * regions sees exactly what it saw before -- provided it ignores `@` variations + * (`apps/data`'s client projects them away unless a region is asked for). + * + * A region id is a short lowercase token. What it means -- which cloud region + * was asked for, and where the runner actually was -- is recorded per run in + * `/{date}/regions.json` ({@link RegionsFile}); this id is only the key. + */ +export type RegionId = string; + +/** The region published without a suffix: the one every registry run used before regions existed. */ +export const DEFAULT_REGION = "na"; + +/** Joins a variation and a region in a published name: `registry-clean@eu`. */ +export const REGION_SEPARATOR = "@"; + +/** What a region id may look like: `na`, `eu`, `apac`. */ +export const REGION_PATTERN = /^[a-z]{2,8}$/; + +export const isRegionId = (value: unknown): value is RegionId => + typeof value === "string" && REGION_PATTERN.test(value); + +/** + * Split a published variation into the measured variation and its region. + * + * `registry-clean@eu` is `{ variation: "registry-clean", region: "eu" }`; + * anything without a well-formed suffix -- every variation published before + * regions, and every non-registry variation -- is in {@link DEFAULT_REGION}. + */ +export const splitRegion = (published: string): { variation: string; region: RegionId } => { + const at = published.lastIndexOf(REGION_SEPARATOR); + if (at <= 0) return { variation: published, region: DEFAULT_REGION }; + const region = published.slice(at + 1); + if (!isRegionId(region)) return { variation: published, region: DEFAULT_REGION }; + return { variation: published.slice(0, at), region }; +}; + +/** The published name of a variation run from a region. The default region adds nothing. */ +export const regionalVariation = (variation: string, region: RegionId): string => + region === DEFAULT_REGION ? variation : `${variation}${REGION_SEPARATOR}${region}`; + +// --------------------------------------------------------------------------- +// /{date}/regions.json +// --------------------------------------------------------------------------- + +/** + * One registry benchmark job: where it asked to run, where it found itself, + * and how far each registry was from there. + * + * Every field is optional. The record is gathered best-effort on the runner + * (cloud metadata, a Cloudflare trace, one timed request per registry) and a + * field the runner could not learn is left out, never guessed. No IP address + * is recorded. + */ +export interface RegionRun { + fixture?: string; + /** The measured variation, without a region suffix. */ + variation?: string; + /** The workflow's description of the runner it asked for, e.g. `AWS eu-central-1 (Frankfurt)`. */ + requested?: string; + /** `runner.arch` / `runner.os` as the Actions runner reported them. */ + arch?: string; + os?: string; + cpus?: number; + memoryMb?: number; + /** From the cloud's instance metadata service, where one answered. */ + cloud?: { + provider?: string; + region?: string; + zone?: string; + instanceType?: string; + }; + /** The Cloudflare data centre that answered the runner, from `/cdn-cgi/trace`. */ + edge?: { + colo?: string; + country?: string; + }; + /** + * One request to each registry's base URL, taken after the benchmark so it + * cannot warm anything the benchmark measures. Seconds, from curl. + */ + registries?: { + [registry: string]: + | { + status?: number; + connect?: number; + tls?: number; + ttfb?: number; + total?: number; + /** The CDN point of presence, where a response header names one. */ + pop?: string; + } + | undefined; + }; +} + +/** Everything one region's jobs reported on one date. */ +export interface RegionRuns { + runs: RegionRun[]; +} + +/** + * `/{date}/regions.json`: region id to its jobs. + * + * Absent on every date before regions were introduced, where every registry + * run came from a GitHub-hosted runner whose location was not recorded. Treat + * it as optional on any date. + */ +export type RegionsFile = { [region: string]: RegionRuns | undefined }; + // --------------------------------------------------------------------------- // /{date}/{fixture}-{variation}.json -- hyperfine output // --------------------------------------------------------------------------- diff --git a/packages/types/test/guards.test.ts b/packages/types/test/guards.test.ts index 5a3c04d825..4e42290b89 100644 --- a/packages/types/test/guards.test.ts +++ b/packages/types/test/guards.test.ts @@ -2,10 +2,14 @@ import { describe, expect, it } from "vitest"; import { benchmarkFileStem, DATE_KEY_PATTERN, + DEFAULT_REGION, FIXTURES, isDateKey, isFixture, + isRegionId, isVariation, + regionalVariation, + splitRegion, VARIATIONS, } from "../src/index.ts"; @@ -76,3 +80,39 @@ describe("benchmarkFileStem", () => { ); }); }); + +describe("regions", () => { + it("reads an unsuffixed variation as the default region, as every file before regions was", () => { + expect(splitRegion("registry-clean")).toEqual({ variation: "registry-clean", region: "na" }); + expect(splitRegion("cache+lockfile")).toEqual({ variation: "cache+lockfile", region: "na" }); + expect(DEFAULT_REGION).toBe("na"); + }); + + it("splits a region suffix off a registry variation", () => { + expect(splitRegion("registry-clean@eu")).toEqual({ variation: "registry-clean", region: "eu" }); + expect(splitRegion("registry-lockfile@apac")).toEqual({ + variation: "registry-lockfile", + region: "apac", + }); + }); + + it("leaves a malformed suffix alone rather than guessing a region", () => { + expect(splitRegion("registry-clean@EU").region).toBe("na"); + expect(splitRegion("registry-clean@").variation).toBe("registry-clean@"); + expect(splitRegion("@eu").variation).toBe("@eu"); + }); + + it("publishes the default region without a suffix and round-trips the rest", () => { + expect(regionalVariation("registry-clean", "na")).toBe("registry-clean"); + expect(regionalVariation("registry-clean", "eu")).toBe("registry-clean@eu"); + expect(splitRegion(regionalVariation("registry-lockfile", "eu"))).toEqual({ + variation: "registry-lockfile", + region: "eu", + }); + }); + + it("accepts short lowercase ids only", () => { + expect(["na", "eu", "apac"].every(isRegionId)).toBe(true); + expect(["", "e", "EU", "eu-central-1", "toolongregion", 1].some(isRegionId)).toBe(false); + }); +}); diff --git a/suite/bench b/suite/bench index 8c7f91fcdd..f14c1b0afa 100755 --- a/suite/bench +++ b/suite/bench @@ -62,7 +62,7 @@ AVAILABLE_REGISTRIES=( usage() { cat <<'EOF' Usage: - ./bench run [--fixtures=] [--pms=] [--variation=] [--runs=] [--warmup=] [--chart] [--process] [--date=] [--clean] + ./bench run [--fixtures=] [--pms=] [--variation=] [--region=] [--runs=] [--warmup=] [--chart] [--process] [--date=] [--clean] ./bench chart [--fixtures=] [--variation=] [--date=] [--clean] ./bench process [--dry-run] ./bench list @@ -72,6 +72,9 @@ Options: --pms Comma or space-separated package managers (default: all) --registries Comma-separated registries for registry-* variations (default: npm,vlt,aws,cloudsmith,github,jfrog) --variation Comma or space-separated benchmark variations (default: clean) + --region Region id recorded for registry-* variations (default: na). Any other + region writes @/ and is published as such; it says + where the results are FILED, it does not move the machine. Same as BENCH_REGION. --runs Hyperfine runs (default: scripts/variations/common.sh default) --warmup Hyperfine warmup runs (default: scripts/variations/common.sh default) --timeout Per-command timeout in seconds (default: 300) @@ -91,6 +94,7 @@ Examples: ./bench run --fixtures=next --chart --process --runs=3 ./bench run --variation=registry-clean --fixtures=next ./bench run --variation=registry-lockfile --registries=npm,vlt + ./bench run --variation=registry-clean --fixtures=next --registries=npm,vlt --region=eu CODEARTIFACT_AUTH_TOKEN= ./bench run --variation=registry-clean --fixtures=next --registries=aws CLOUDSMITH_REGISTRY= CLOUDSMITH_TOKEN= ./bench run --variation=registry-clean --fixtures=next --registries=cloudsmith GH_REGISTRY= GH_AUTH_TOKEN= ./bench run --variation=registry-clean --fixtures=next --registries=github @@ -315,6 +319,18 @@ clean_benchmarks_file() { fi } +# The results folder (and published name) of a variation: registry-* runs from a +# region other than the default are filed as @. Mirrors +# scripts/registry/region.sh, which is what actually names them. +results_folder() { + local variation="$1" + if [[ "$variation" == registry-* && -n "${BENCH_REGION:-}" && "${BENCH_REGION}" != "na" ]]; then + echo "$variation@$BENCH_REGION" + else + echo "$variation" + fi +} + generate_chart_data() { local variation="$1" local date="$2" @@ -327,17 +343,19 @@ generate_chart_data() { local copied=0 local fixture for fixture in "${fixtures[@]}"; do - local src="$ROOT/results/$fixture/$variation/benchmarks.json" + local folder + folder="$(results_folder "$variation")" + local src="$ROOT/results/$fixture/$folder/benchmarks.json" if [[ -f "$src" ]]; then - cp "$src" "$results_dir/${fixture}-${variation}.json" + cp "$src" "$results_dir/${fixture}-${folder}.json" copied=1 else - echo "Warning: Missing results for $fixture/$variation" + echo "Warning: Missing results for $fixture/$folder" fi - local count_src="$ROOT/results/$fixture/$variation/package-count.json" + local count_src="$ROOT/results/$fixture/$folder/package-count.json" if [[ -f "$count_src" ]]; then - cp "$count_src" "$results_dir/${fixture}-${variation}-package-count.json" + cp "$count_src" "$results_dir/${fixture}-${folder}-package-count.json" fi done @@ -519,7 +537,7 @@ run_bench() { fi if [[ "$clean_results" -eq 1 ]]; then - clean_benchmarks_file "$ROOT/results/$fixture/$variation/benchmarks.json" + clean_benchmarks_file "$ROOT/results/$fixture/$(results_folder "$variation")/benchmarks.json" fi done done @@ -636,7 +654,7 @@ case "$command" in if [[ "$CLEAN_RESULTS" -eq 1 ]]; then for fixture in "${fixtures[@]}"; do - clean_benchmarks_file "$ROOT/results/$fixture/$variation/benchmarks.json" + clean_benchmarks_file "$ROOT/results/$fixture/$(results_folder "$variation")/benchmarks.json" done fi @@ -683,6 +701,14 @@ case "$command" in REGISTRIES_INPUT="${1#*=}" shift ;; + --region) + export BENCH_REGION="${2:-}" + shift 2 + ;; + --region=*) + export BENCH_REGION="${1#*=}" + shift + ;; --variation|--variations) VARIATION_INPUT="${2:-}" shift 2 diff --git a/suite/scripts/collect-regions.js b/suite/scripts/collect-regions.js new file mode 100644 index 0000000000..e9763d50e8 --- /dev/null +++ b/suite/scripts/collect-regions.js @@ -0,0 +1,113 @@ +// Gather every registry job's runner.json (written by registry/runner-info.sh) +// into one regions.json for the date: region id -> { runs: [...] }. +// +// node collect-regions.js +// +// is searched the way process-results.sh resolves results: +// downloaded artifact folders (results--[@region]/) and +// local run folders (/[@region]/). The region comes from +// the folder name, the same rule that names the published files, so the two +// cannot disagree; a runner.json's own `region` field is only a fallback. +// +// Writes nothing when no job left a runner.json, so a date without regions +// stays a date without regions.json rather than one with an empty file. +const fs = require("node:fs"); +const path = require("node:path"); + +const DEFAULT_REGION = "na"; +const REGION = /^[a-z]{2,8}$/; +const FIXTURES = ["astro", "babylon", "large", "next", "run", "svelte", "vue"]; + +/** `registry-clean@eu` -> { variation: "registry-clean", region: "eu" }. */ +const splitRegion = (published) => { + const at = published.lastIndexOf("@"); + if (at <= 0) return { variation: published, region: DEFAULT_REGION }; + const region = published.slice(at + 1); + if (!REGION.test(region)) return { variation: published, region: DEFAULT_REGION }; + return { variation: published.slice(0, at), region }; +}; + +/** Every runner.json under the results tree, with the fixture and published variation it belongs to. */ +const findRunnerFiles = (resultsDir) => { + const found = []; + if (!fs.existsSync(resultsDir)) return found; + for (const entry of fs.readdirSync(resultsDir, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + const dir = path.join(resultsDir, entry.name); + + // results--[@region]/runner.json (CI artifacts) + const artifact = /^results-([a-z]+)-(registry-.+)$/.exec(entry.name); + if (artifact) { + const file = path.join(dir, "runner.json"); + if (fs.existsSync(file)) found.push({ file, fixture: artifact[1], published: artifact[2] }); + continue; + } + + // /[@region]/runner.json (local runs) + if (!FIXTURES.includes(entry.name)) continue; + for (const sub of fs.readdirSync(dir, { withFileTypes: true })) { + if (!sub.isDirectory() || !sub.name.startsWith("registry-")) continue; + const file = path.join(dir, sub.name, "runner.json"); + if (fs.existsSync(file)) found.push({ file, fixture: entry.name, published: sub.name }); + } + } + return found; +}; + +const collectRegions = (resultsDir) => { + const regions = {}; + const seen = new Set(); + for (const { file, fixture, published } of findRunnerFiles(resultsDir)) { + // An artifact folder and a local folder for the same job are one job. + const key = `${fixture}/${published}`; + if (seen.has(key)) continue; + seen.add(key); + + let run; + try { + run = JSON.parse(fs.readFileSync(file, "utf8")); + } catch (error) { + console.warn(`Warning: skipping unreadable ${file}: ${error.message}`); + continue; + } + if (typeof run !== "object" || run === null || Array.isArray(run)) continue; + + const { variation, region } = splitRegion(published); + const { region: _ignored, ...rest } = run; + (regions[region] ??= { runs: [] }).runs.push({ ...rest, fixture, variation }); + } + for (const value of Object.values(regions)) { + value.runs.sort( + (a, b) => a.variation.localeCompare(b.variation) || a.fixture.localeCompare(b.fixture), + ); + } + return regions; +}; + +module.exports = { collectRegions, splitRegion }; + +if (require.main === module) { + const [resultsDir, outputFile] = process.argv.slice(2); + if (!resultsDir || !outputFile) { + console.error("Usage: node collect-regions.js "); + process.exit(1); + } + const regions = collectRegions(resultsDir); + const count = Object.values(regions).reduce((n, r) => n + r.runs.length, 0); + if (count === 0) { + console.log("No runner.json files found; not writing regions.json"); + process.exit(0); + } + fs.mkdirSync(path.dirname(outputFile), { recursive: true }); + fs.writeFileSync(outputFile, `${JSON.stringify(regions, null, 2)}\n`); + for (const [region, { runs }] of Object.entries(regions)) { + const where = [ + ...new Set( + runs.map((r) => + r.cloud ? `${r.cloud.provider ?? "?"} ${r.cloud.region ?? "?"}` : "unknown location", + ), + ), + ]; + console.log(`regions.json: ${region}: ${runs.length} jobs (${where.join(", ")})`); + } +} diff --git a/suite/scripts/collect-regions.test.js b/suite/scripts/collect-regions.test.js new file mode 100644 index 0000000000..b191ae5706 --- /dev/null +++ b/suite/scripts/collect-regions.test.js @@ -0,0 +1,71 @@ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { execFileSync } = require("node:child_process"); +const test = require("node:test"); + +const { collectRegions, splitRegion } = require("./collect-regions.js"); + +const tree = (t, files) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "collect-regions-")); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + for (const [file, content] of Object.entries(files)) { + const full = path.join(root, file); + fs.mkdirSync(path.dirname(full), { recursive: true }); + fs.writeFileSync(full, typeof content === "string" ? content : JSON.stringify(content)); + } + return root; +}; + +test("splits a region suffix the way packages/types does", () => { + assert.deepEqual(splitRegion("registry-clean"), { variation: "registry-clean", region: "na" }); + assert.deepEqual(splitRegion("registry-clean@eu"), { variation: "registry-clean", region: "eu" }); + assert.deepEqual(splitRegion("registry-clean@EU"), { + variation: "registry-clean@EU", + region: "na", + }); +}); + +test("groups artifact runner files by the region in the folder name", (t) => { + const root = tree(t, { + "results-next-registry-clean/runner.json": { region: "na", cloud: { provider: "azure" } }, + "results-next-registry-clean@eu/runner.json": { region: "na", cloud: { provider: "aws" } }, + "results-astro-registry-lockfile@eu/runner.json": { cloud: { provider: "aws" } }, + "results-next-clean/runner.json": { ignored: true }, + "results-next-registry-clean/benchmarks.json": { results: [] }, + }); + const regions = collectRegions(root); + assert.deepEqual(Object.keys(regions).sort(), ["eu", "na"]); + assert.deepEqual(regions.na.runs, [ + { cloud: { provider: "azure" }, fixture: "next", variation: "registry-clean" }, + ]); + // The folder says eu; the file's own (wrong) region field is not trusted. + assert.deepEqual( + regions.eu.runs.map((r) => `${r.fixture} ${r.variation}`), + ["next registry-clean", "astro registry-lockfile"], + ); +}); + +test("reads local run folders and counts a job once when both layouts hold it", (t) => { + const root = tree(t, { + "next/registry-clean@eu/runner.json": { arch: "ARM64" }, + "results-next-registry-clean@eu/runner.json": { arch: "ARM64" }, + "next/clean/runner.json": { arch: "ignored" }, + }); + const regions = collectRegions(root); + assert.equal(regions.eu.runs.length, 1); + assert.equal(regions.na, undefined); +}); + +test("skips a runner file that does not parse", (t) => { + const root = tree(t, { "results-vue-registry-clean@eu/runner.json": "{not json" }); + assert.deepEqual(collectRegions(root), {}); +}); + +test("writes no file when no job recorded where it ran", (t) => { + const root = tree(t, { "results-next-registry-clean/benchmarks.json": { results: [] } }); + const out = path.join(root, "out", "regions.json"); + execFileSync(process.execPath, [path.join(__dirname, "collect-regions.js"), root, out]); + assert.equal(fs.existsSync(out), false); +}); diff --git a/suite/scripts/plan-jobs.js b/suite/scripts/plan-jobs.js new file mode 100644 index 0000000000..9e0419585c --- /dev/null +++ b/suite/scripts/plan-jobs.js @@ -0,0 +1,177 @@ +// Split a benchmark run into its two kinds of job, for .github/workflows/benchmark.yaml. +// +// Package-manager and task-runner variations measure the client, so they run +// once, on the suite's usual runner. Registry variations measure the network +// between a runner and each registry, so they run once per REGION, each on a +// runner pinned to that region. This turns the run's inputs into both job +// lists. +// +// Inputs (environment, all JSON): +// BENCH_FIXTURES fixtures to run, e.g. ["next", "astro"] +// BENCH_VARIATIONS variations to run, registry-* and the rest mixed +// BENCH_REGIONS regions to run registry variations from, e.g. ["na", "eu"] +// REGISTRY_RUNNERS the REGISTRY_RUNNERS repository variable: region id -> +// { "runs-on": , "label": }. +// `{run_id}` anywhere in a runs-on value is replaced with +// RUN_ID (RunsOn wants it; a variable cannot hold an +// expression). Unset or empty means DEFAULT_RUNNERS. +// RUN_ID github.run_id +// +// Outputs (to GITHUB_OUTPUT when set, else printed): +// pm_variations the variations that are not registry-* +// registry_matrix {"include": [{fixture, variation, region, name, runner, label}]} +// registry_jobs how many registry jobs that is +// registry_regions the regions that will actually run, in order +const fs = require("node:fs"); + +const DEFAULT_REGION = "na"; +const REGION = /^[a-z]{2,8}$/; + +/** + * What runs when REGISTRY_RUNNERS is not set: the default region only, on the + * runner every registry benchmark used before regions existed. Its location + * is GitHub's choice, not ours, and the job records where it landed. + */ +const DEFAULT_RUNNERS = { + [DEFAULT_REGION]: { + "runs-on": "ubuntu-24.04-arm", + label: "GitHub-hosted ubuntu-24.04-arm (location chosen by GitHub)", + }, +}; + +const isRegistry = (variation) => variation.startsWith("registry-"); + +const published = (variation, region) => + region === DEFAULT_REGION ? variation : `${variation}@${region}`; + +const parseJson = (name, text, fallback) => { + if (text === undefined || text.trim() === "") return fallback; + try { + return JSON.parse(text); + } catch (error) { + throw new Error(`${name} is not valid JSON: ${error.message}`); + } +}; + +const isStringArray = (value) => + Array.isArray(value) && value.length > 0 && value.every((v) => typeof v === "string" && v); + +/** A `runs-on` value GitHub accepts: a label, a list of labels, or {group, labels}. */ +const isRunsOn = (value) => { + if (typeof value === "string") return value.length > 0; + if (Array.isArray(value)) return isStringArray(value); + if (typeof value !== "object" || value === null) return false; + const { group, labels, ...rest } = value; + if (Object.keys(rest).length > 0) return false; + if (group !== undefined && (typeof group !== "string" || group === "")) return false; + if (labels !== undefined && !(typeof labels === "string" ? labels : isStringArray(labels))) { + return false; + } + return group !== undefined || labels !== undefined; +}; + +const substitute = (value, runId) => { + if (typeof value === "string") return value.split("{run_id}").join(runId); + if (Array.isArray(value)) return value.map((v) => substitute(v, runId)); + if (typeof value === "object" && value !== null) { + return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, substitute(v, runId)])); + } + return value; +}; + +/** + * Plan the run. Returns the outputs and the warnings worth surfacing; throws + * only on inputs the workflow itself wrote wrong (fixtures, variations, + * regions). A broken REGISTRY_RUNNERS is a warning and falls back to the + * default, so one bad variable cannot cost a night's package-manager results. + */ +const planJobs = ({ fixtures, variations, regions, runners, runId = "" }) => { + const warnings = []; + const fixtureList = parseJson("BENCH_FIXTURES", fixtures, null); + const variationList = parseJson("BENCH_VARIATIONS", variations, null); + const regionList = parseJson("BENCH_REGIONS", regions, [DEFAULT_REGION]); + if (!isStringArray(fixtureList)) throw new Error("BENCH_FIXTURES must be a non-empty JSON array"); + if (!isStringArray(variationList)) { + throw new Error("BENCH_VARIATIONS must be a non-empty JSON array"); + } + if (!isStringArray(regionList) || !regionList.every((r) => REGION.test(r))) { + throw new Error("BENCH_REGIONS must be a non-empty JSON array of 2-8 lowercase letters each"); + } + + let config; + try { + config = parseJson("REGISTRY_RUNNERS", runners, DEFAULT_RUNNERS); + if (typeof config !== "object" || config === null || Array.isArray(config)) { + throw new Error("REGISTRY_RUNNERS must be a JSON object keyed by region id"); + } + for (const [region, entry] of Object.entries(config)) { + if (!REGION.test(region)) throw new Error(`REGISTRY_RUNNERS: bad region id '${region}'`); + if (typeof entry !== "object" || entry === null || !isRunsOn(entry["runs-on"])) { + throw new Error(`REGISTRY_RUNNERS.${region} needs a valid "runs-on"`); + } + } + } catch (error) { + warnings.push(`${error.message}. Falling back to the default runner for '${DEFAULT_REGION}' only.`); + config = DEFAULT_RUNNERS; + } + + const pmVariations = variationList.filter((v) => !isRegistry(v)); + const registryVariations = variationList.filter(isRegistry); + + const planned = []; + for (const region of [...new Set(regionList)]) { + if (config[region] === undefined) { + warnings.push( + `Region '${region}' has no runner in REGISTRY_RUNNERS; its registry benchmarks are skipped.`, + ); + continue; + } + planned.push(region); + } + + const include = []; + if (registryVariations.length > 0) { + for (const region of planned) { + const { label } = config[region]; + const runner = substitute(config[region]["runs-on"], String(runId)); + for (const variation of registryVariations) { + for (const fixture of fixtureList) { + include.push({ + fixture, + variation, + region, + name: published(variation, region), + runner, + label: typeof label === "string" && label ? label : `${region} registry runner`, + }); + } + } + } + } + + return { + outputs: { + pm_variations: JSON.stringify(pmVariations), + registry_matrix: JSON.stringify({ include }), + registry_jobs: String(include.length), + registry_regions: JSON.stringify(registryVariations.length > 0 ? planned : []), + }, + warnings, + }; +}; + +module.exports = { DEFAULT_RUNNERS, planJobs }; + +if (require.main === module) { + const { outputs, warnings } = planJobs({ + fixtures: process.env.BENCH_FIXTURES, + variations: process.env.BENCH_VARIATIONS, + regions: process.env.BENCH_REGIONS, + runners: process.env.REGISTRY_RUNNERS, + runId: process.env.RUN_ID, + }); + for (const warning of warnings) console.log(`::warning::${warning}`); + const lines = Object.entries(outputs).map(([key, value]) => `${key}=${value}`); + if (process.env.GITHUB_OUTPUT) fs.appendFileSync(process.env.GITHUB_OUTPUT, `${lines.join("\n")}\n`); + console.log(lines.join("\n")); +} diff --git a/suite/scripts/plan-jobs.test.js b/suite/scripts/plan-jobs.test.js new file mode 100644 index 0000000000..d36db07b55 --- /dev/null +++ b/suite/scripts/plan-jobs.test.js @@ -0,0 +1,86 @@ +const assert = require("node:assert/strict"); +const test = require("node:test"); + +const { planJobs } = require("./plan-jobs.js"); + +const FIXTURES = JSON.stringify(["next", "vue"]); +const VARIATIONS = JSON.stringify(["clean", "registry-clean", "registry-lockfile", "ci+setup"]); +const RUNNERS = JSON.stringify({ + na: { "runs-on": "runs-on={run_id}/region=us-east-1", label: "AWS us-east-1" }, + eu: { "runs-on": { group: "benchmarks-eu", labels: ["linux-4core"] }, label: "Azure Frankfurt" }, +}); + +const plan = (overrides = {}) => + planJobs({ + fixtures: FIXTURES, + variations: VARIATIONS, + regions: JSON.stringify(["na", "eu"]), + runners: RUNNERS, + runId: "42", + ...overrides, + }); + +test("keeps package-manager variations out of the registry jobs and vice versa", () => { + const { outputs } = plan(); + assert.deepEqual(JSON.parse(outputs.pm_variations), ["clean", "ci+setup"]); + const { include } = JSON.parse(outputs.registry_matrix); + assert.ok(include.every((job) => job.variation.startsWith("registry-"))); +}); + +test("plans every registry variation and fixture once per region", () => { + const { outputs, warnings } = plan(); + const { include } = JSON.parse(outputs.registry_matrix); + assert.equal(outputs.registry_jobs, "8"); + assert.equal(include.length, 8); + assert.deepEqual(JSON.parse(outputs.registry_regions), ["na", "eu"]); + assert.deepEqual(warnings, []); + assert.deepEqual( + include.map((job) => job.name), + [ + "registry-clean", + "registry-clean", + "registry-lockfile", + "registry-lockfile", + "registry-clean@eu", + "registry-clean@eu", + "registry-lockfile@eu", + "registry-lockfile@eu", + ], + ); +}); + +test("fills {run_id} into the runner label and passes group runners through", () => { + const { include } = JSON.parse(plan().outputs.registry_matrix); + assert.equal(include[0].runner, "runs-on=42/region=us-east-1"); + assert.equal(include[0].label, "AWS us-east-1"); + assert.deepEqual(include.at(-1).runner, { group: "benchmarks-eu", labels: ["linux-4core"] }); +}); + +test("runs the default region on the default runner when nothing is configured", () => { + const { outputs, warnings } = plan({ runners: "" }); + const { include } = JSON.parse(outputs.registry_matrix); + assert.deepEqual(JSON.parse(outputs.registry_regions), ["na"]); + assert.ok(include.every((job) => job.runner === "ubuntu-24.04-arm" && job.region === "na")); + assert.match(warnings.join("\n"), /'eu' has no runner/); +}); + +test("falls back to the default runner, loudly, when the variable is broken", () => { + for (const runners of ["{nope", '{"EU": {"runs-on": "x"}}', '{"eu": {"runs-on": ""}}', "[]"]) { + const { outputs, warnings } = plan({ runners }); + assert.deepEqual(JSON.parse(outputs.registry_regions), ["na"], runners); + assert.ok(warnings.some((w) => /Falling back/.test(w)), runners); + } +}); + +test("plans no registry jobs when no registry variation was asked for", () => { + const { outputs } = plan({ variations: JSON.stringify(["clean"]) }); + assert.equal(outputs.registry_jobs, "0"); + assert.deepEqual(JSON.parse(outputs.registry_matrix), { include: [] }); + assert.deepEqual(JSON.parse(outputs.registry_regions), []); +}); + +test("rejects inputs the workflow itself got wrong", () => { + assert.throws(() => plan({ fixtures: "[]" }), /BENCH_FIXTURES/); + assert.throws(() => plan({ variations: "nope" }), /BENCH_VARIATIONS/); + assert.throws(() => plan({ regions: JSON.stringify(["eu-central-1"]) }), /BENCH_REGIONS/); +}); diff --git a/suite/scripts/process-results.sh b/suite/scripts/process-results.sh index dcf6457e02..fbabce0281 100644 --- a/suite/scripts/process-results.sh +++ b/suite/scripts/process-results.sh @@ -129,9 +129,29 @@ for fixture in next astro svelte vue large babylon; do done done +# Every published name a registry variation has for this fixture: the plain +# one (the default region) plus one per region that ran it, discovered from +# the folders present -- results--registry-clean@eu/ (artifacts) or +# /registry-clean@eu/ (local). See scripts/registry/region.sh. +registry_variations() { + local fixture=$1 + local base dir name + for base in registry-clean registry-lockfile; do + echo "$base" + for dir in "results/results-$fixture-$base@"* "results/$fixture/$base@"*; do + [ -d "$dir" ] || continue + name="${dir##*/}" + name="${name#results-$fixture-}" + if [[ "$name" =~ ^$base@[a-z]{2,8}$ ]]; then + echo "$name" + fi + done + done | sort -u +} + # Process registry variation results for fixture in next astro svelte vue large babylon; do - for variation in registry-clean registry-lockfile; do + for variation in $(registry_variations "$fixture"); do if benchmark_file=$(resolve_result_path "$fixture" "$variation" "benchmarks.json"); then print_summary "$benchmark_file" "$fixture" "$variation" cp "$benchmark_file" "results/$DATE/$fixture-$variation.json" @@ -150,6 +170,12 @@ for fixture in next astro svelte vue large babylon; do done done +# Where each region's registry jobs ran (registry/runner-info.sh). Absent when +# no job recorded it, as on every date before regions. +# Dated only: latest/ is merged across runs, so a copy there could outlive the +# regions it describes. +node ./scripts/collect-regions.js ./results "results/$DATE/regions.json" + # Process run results if run_file=$(resolve_result_path "run" "run" "benchmarks.json"); then print_summary "$run_file" "run" "run" diff --git a/suite/scripts/registry/common.sh b/suite/scripts/registry/common.sh index 69c47f0d04..089d584735 100644 --- a/suite/scripts/registry/common.sh +++ b/suite/scripts/registry/common.sh @@ -50,7 +50,12 @@ BENCH_RUNS="${BENCH_RUNS:=5}" # Per-command timeout in seconds (default: 5 minutes) BENCH_TIMEOUT="${BENCH_TIMEOUT:=300}" BENCH_LOGLEVEL="${BENCH_LOGLEVEL:=http}" -BENCH_OUTPUT_FOLDER="$BENCH_RESULTS/$BENCH_FIXTURE/$BENCH_VARIATION" +# Where the runner is, for registry variations only (see registry/region.sh). +# The default region keeps the unsuffixed folder every registry run has used; +# any other region writes to @, the name it is published +# under (next-registry-clean@eu.json). +source "$BENCH_SCRIPTS/registry/region.sh" +BENCH_OUTPUT_FOLDER="$BENCH_RESULTS/$BENCH_FIXTURE/$(bench_regional_variation "$BENCH_VARIATION")" # Marks every process this run starts, vlt's detached children included, so # waiting for (or stopping) vlt's background work only reaches this run's # processes, not another checkout's on the same machine. See vlt-background.sh. @@ -67,37 +72,8 @@ fi # relying on any cached metadata, so we measure actual registry performance. BENCH_NPM_INSTALL="npm install --prefer-online --no-audit --no-fund --no-update-notifier --ignore-scripts --loglevel=$BENCH_LOGLEVEL $FORCE_FLAG" -# Only the selected registries need their variables (checked below). With -# `set -u`, the `${VAR#//}` expansions below abort on an unset one, so give the -# optional registry URLs an empty default first: `--registries=npm` must run -# without CLOUDSMITH_REGISTRY, GH_REGISTRY and JFROG_REGISTRY. -CLOUDSMITH_REGISTRY="${CLOUDSMITH_REGISTRY:-}" -GH_REGISTRY="${GH_REGISTRY:-}" -JFROG_REGISTRY="${JFROG_REGISTRY:-}" - -# Registry definitions -BENCH_REGISTRY_NPM_URL="https://registry.npmjs.org/" -BENCH_REGISTRY_VLT_URL="https://registry.vlt.io/vlt-benchmarks/npm/" -BENCH_REGISTRY_VLT_URL_NPMRC_KEY="${BENCH_REGISTRY_VLT_URL#http*://}" -BENCH_REGISTRY_AWS_URL="https://vlt-451504312483.d.codeartifact.us-east-1.amazonaws.com/npm/code-artifact-benchmark-test/" -BENCH_REGISTRY_AWS_NPMRC_KEY="${BENCH_REGISTRY_AWS_URL#http*://}" -# Cloudsmith registry URL is injected without the protocol prefix -# (e.g. "//example.com/..."), so we prepend "https:" for the registry config. -# The auth .npmrc key uses the URL as-is (without protocol). -BENCH_REGISTRY_CLOUDSMITH_URL="https:${CLOUDSMITH_REGISTRY:-}" -BENCH_REGISTRY_CLOUDSMITH_NPMRC_KEY="${CLOUDSMITH_REGISTRY#//}" - -# GitHub registry URL is injected without the protocol prefix -# (e.g. "//npm.pkg.github.com/..."), so we prepend "https:" for the registry config. -# The auth .npmrc key uses the URL as-is (without protocol). -BENCH_REGISTRY_GITHUB_URL="https:${GH_REGISTRY:-}" -BENCH_REGISTRY_GITHUB_NPMRC_KEY="${GH_REGISTRY#//}" - -# JFrog registry URL is injected without the protocol prefix -# (e.g. "//example.jfrog.io/..."), so we prepend "https:" for the registry config. -# The auth .npmrc key uses the URL as-is (without protocol). -BENCH_REGISTRY_JFROG_URL="https:${JFROG_REGISTRY:-}" -BENCH_REGISTRY_JFROG_NPMRC_KEY="${JFROG_REGISTRY#//}" +# Registry URLs and their .npmrc keys, shared with registry/runner-info.sh. +source "$BENCH_SCRIPTS/registry/urls.sh" # Registry setup commands run in hyperfine --prepare (untimed, before each run). # Auth token is written as a literal placeholder so npm resolves it from env. diff --git a/suite/scripts/registry/region.sh b/suite/scripts/registry/region.sh new file mode 100644 index 0000000000..f32c072317 --- /dev/null +++ b/suite/scripts/registry/region.sh @@ -0,0 +1,26 @@ +# Sourced by registry/common.sh, and by anything else that needs to name a +# registry variation's results the way they are published. +# +# Registry benchmarks measure the network between the runner and each +# registry, so they can be run from more than one region (BENCH_REGION). The +# default region, `na`, is published without a suffix -- next-registry-clean.json, +# exactly as before regions existed -- and every other region appends +# @: next-registry-clean@eu.json. packages/types documents the same +# rule for the readers. + +BENCH_DEFAULT_REGION="na" +BENCH_REGION="${BENCH_REGION:-$BENCH_DEFAULT_REGION}" + +if ! [[ "$BENCH_REGION" =~ ^[a-z]{2,8}$ ]]; then + echo "Error: BENCH_REGION must be 2-8 lowercase letters (got '$BENCH_REGION')" + exit 1 +fi + +# The folder/published name of a variation run from BENCH_REGION. +bench_regional_variation() { + if [ "$BENCH_REGION" = "$BENCH_DEFAULT_REGION" ]; then + echo "$1" + else + echo "$1@$BENCH_REGION" + fi +} diff --git a/suite/scripts/registry/runner-info.sh b/suite/scripts/registry/runner-info.sh new file mode 100644 index 0000000000..b816db5936 --- /dev/null +++ b/suite/scripts/registry/runner-info.sh @@ -0,0 +1,171 @@ +#!/bin/bash +# Record where a registry benchmark job actually ran, and how far each +# registry was from there, as runner.json beside the job's benchmarks.json. +# +# bash runner-info.sh +# +# Run AFTER the benchmark, never before: the requests below reach every +# registry, and a request before the timed installs could warm something they +# measure. +# +# Best-effort by design. Every probe has a short timeout, a probe that fails +# leaves its field out, and the script always exits 0 -- a missing location +# must not cost a night's results. No IP address is written: the Cloudflare +# trace and the cloud metadata services both return one, and only the +# location fields are kept. +# +# Environment (all optional): +# BENCH_REGION region id this job was asked to run in (default na) +# BENCH_REGION_LABEL human description of the runner asked for +# BENCH_FIXTURE fixture, for the record +# BENCH_VARIATION variation, without a region suffix +# BENCH_INCLUDE_REGISTRY registries to probe (default: all six) +# RUNNER_ARCH, RUNNER_OS as the Actions runner sets them +# plus the registry URL/token variables registry/common.sh reads. + +set -uo pipefail + +if [ -z "${1:-}" ] || [ -z "${2:-}" ]; then + echo "Usage: runner-info.sh " + exit 0 +fi +BENCH_SCRIPTS="$1" +OUT="$2" + +# shellcheck source=/dev/null +source "$BENCH_SCRIPTS/registry/urls.sh" + +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT + +# --- the machine -------------------------------------------------------------- + +cpus="$(nproc 2>/dev/null || echo "")" +memory_mb="$(awk '/^MemTotal:/ { printf "%d", $2 / 1024 }' /proc/meminfo 2>/dev/null || echo "")" + +# --- the cloud, from whichever instance metadata service answers --------------- +# +# GitHub-hosted Linux runners may land on Azure or AWS (GitHub schedules eligible +# jobs across both), so neither can be assumed. --noproxy because IMDS must be +# reached directly. + +cloud="{}" + +azure="$(curl -s -m 2 --noproxy '*' -H 'Metadata: true' \ + 'http://169.254.169.254/metadata/instance/compute?api-version=2021-02-01' 2>/dev/null || true)" +if echo "$azure" | jq -e '.location' >/dev/null 2>&1; then + cloud="$(echo "$azure" | jq -c '{provider: "azure", region: .location, zone: .zone, instanceType: .vmSize} | with_entries(select(.value != null and .value != ""))' || echo "{}")" +else + token="$(curl -s -m 2 --noproxy '*' -X PUT -H 'X-aws-ec2-metadata-token-ttl-seconds: 60' \ + 'http://169.254.169.254/latest/api/token' 2>/dev/null || true)" + if [ -n "$token" ]; then + aws="$(curl -s -m 2 --noproxy '*' -H "X-aws-ec2-metadata-token: $token" \ + 'http://169.254.169.254/latest/dynamic/instance-identity/document' 2>/dev/null || true)" + if echo "$aws" | jq -e '.region' >/dev/null 2>&1; then + cloud="$(echo "$aws" | jq -c '{provider: "aws", region: .region, zone: .availabilityZone, instanceType: .instanceType} | with_entries(select(.value != null and .value != ""))' || echo "{}")" + fi + fi + if [ "$cloud" = "{}" ]; then + zone="$(curl -s -m 2 --noproxy '*' -H 'Metadata-Flavor: Google' \ + 'http://metadata.google.internal/computeMetadata/v1/instance/zone' 2>/dev/null || true)" + if [[ "$zone" == projects/*/zones/* ]]; then + zone="${zone##*/}" + cloud="$(jq -nc --arg zone "$zone" '{provider: "gcp", region: ($zone | sub("-[a-z]$"; "")), zone: $zone}' || echo "{}")" + fi + fi +fi + +# --- the edge: which Cloudflare data centre answered this runner --------------- + +trace="$(curl -s -m 5 'https://www.cloudflare.com/cdn-cgi/trace' 2>/dev/null || true)" +colo="$(echo "$trace" | sed -n 's/^colo=//p' | head -1)" +loc="$(echo "$trace" | sed -n 's/^loc=//p' | head -1)" +edge="$(jq -nc --arg colo "$colo" --arg loc "$loc" \ + '{colo: $colo, country: $loc} | with_entries(select(.value != ""))' || echo "{}")" + +# --- each registry: one request to its base URL, three times, median kept ----- + +# The CDN point of presence a response came through, where a header says. +pop_of() { + local headers="$1" value + value="$(grep -i '^cf-ray:' "$headers" | tail -1 | tr -d '\r' | sed -E 's/.*-([A-Z]{3})$/\1/')" + if [ -n "$value" ]; then echo "cloudflare:$value"; return; fi + value="$(grep -i '^x-amz-cf-pop:' "$headers" | tail -1 | tr -d '\r' | awk '{print $2}')" + if [ -n "$value" ]; then echo "cloudfront:$value"; return; fi + value="$(grep -i '^x-served-by:' "$headers" | tail -1 | tr -d '\r' | grep -oE '[A-Z]{3}$' || true)" + if [ -n "$value" ]; then echo "fastly:$value"; return; fi + echo "" +} + +probe() { + local name="$1" url="$2" token="${3:-}" i headers samples pop + headers="$TMP/$name.headers" + samples="$TMP/$name.samples" + : > "$samples" + for i in 1 2 3; do + local auth=() + [ -n "$token" ] && auth=(-H "Authorization: Bearer $token") + # Only timings and the status are written out: never the URL, which can + # carry an account name, and never the remote address. + curl -s -o /dev/null -D "$headers" -m 15 "${auth[@]}" \ + -w '{"status":%{http_code},"connect":%{time_connect},"tls":%{time_appconnect},"ttfb":%{time_starttransfer},"total":%{time_total}}\n' \ + "$url" >> "$samples" 2>/dev/null || true + done + pop="$(pop_of "$headers")" + jq -sc --arg pop "$pop" \ + 'map(select(.status > 0)) | sort_by(.total) | if length == 0 then null else .[(length - 1) / 2 | floor] + ({pop: $pop} | with_entries(select(.value != ""))) end' \ + "$samples" 2>/dev/null || echo "null" +} + +registries="{}" +add() { + local result + result="$(probe "$1" "$2" "${3:-}")" + if [ -n "$result" ] && [ "$result" != "null" ]; then + registries="$(echo "$registries" | jq -c --arg name "$1" --argjson result "$result" '. + {($name): $result}')" + fi +} + +for entry in $(echo "${BENCH_INCLUDE_REGISTRY:-npm,vlt,aws,cloudsmith,github,jfrog}" | tr ',' '\n'); do + case "$entry" in + npm) add npm "$BENCH_REGISTRY_NPM_URL" ;; + vlt) add vlt "$BENCH_REGISTRY_VLT_URL" "${VLT_TOKEN:-}" ;; + aws) add aws "$BENCH_REGISTRY_AWS_URL" "${CODEARTIFACT_AUTH_TOKEN:-}" ;; + cloudsmith) [ -n "$CLOUDSMITH_REGISTRY" ] && add cloudsmith "$BENCH_REGISTRY_CLOUDSMITH_URL" "${CLOUDSMITH_TOKEN:-}" ;; + github) [ -n "$GH_REGISTRY" ] && add github "$BENCH_REGISTRY_GITHUB_URL" "${GH_AUTH_TOKEN:-}" ;; + jfrog) [ -n "$JFROG_REGISTRY" ] && add jfrog "$BENCH_REGISTRY_JFROG_URL" "${JFROG_TOKEN:-}" ;; + esac +done + +# --- write it ------------------------------------------------------------------- + +mkdir -p "$(dirname "$OUT")" +jq -n \ + --arg region "${BENCH_REGION:-na}" \ + --arg requested "${BENCH_REGION_LABEL:-}" \ + --arg fixture "${BENCH_FIXTURE:-}" \ + --arg variation "${BENCH_VARIATION:-}" \ + --arg arch "${RUNNER_ARCH:-$(uname -m)}" \ + --arg os "${RUNNER_OS:-$(uname -s)}" \ + --arg cpus "$cpus" \ + --arg memory "$memory_mb" \ + --argjson cloud "$cloud" \ + --argjson edge "$edge" \ + --argjson registries "$registries" \ + '{ + region: $region, + requested: $requested, + fixture: $fixture, + variation: $variation, + arch: $arch, + os: $os, + cpus: ($cpus | tonumber? // null), + memoryMb: ($memory | tonumber? // null), + cloud: $cloud, + edge: $edge, + registries: $registries + } | with_entries(select(.value != null and .value != "" and .value != {}))' > "$OUT" || echo "{\"region\":\"${BENCH_REGION:-na}\"}" > "$OUT" + +echo "Runner info written to $OUT:" +cat "$OUT" +exit 0 diff --git a/suite/scripts/registry/urls.sh b/suite/scripts/registry/urls.sh new file mode 100644 index 0000000000..1232ce91fd --- /dev/null +++ b/suite/scripts/registry/urls.sh @@ -0,0 +1,35 @@ +# Sourced by registry/common.sh and registry/runner-info.sh: where each +# registry under test is. One definition, so the benchmark and the probe that +# records how far each registry was from the runner cannot disagree. +# +# Only the selected registries need their variables (common.sh checks). With +# `set -u`, the `${VAR#//}` expansions below abort on an unset one, so give the +# optional registry URLs an empty default first: `--registries=npm` must run +# without CLOUDSMITH_REGISTRY, GH_REGISTRY and JFROG_REGISTRY. +CLOUDSMITH_REGISTRY="${CLOUDSMITH_REGISTRY:-}" +GH_REGISTRY="${GH_REGISTRY:-}" +JFROG_REGISTRY="${JFROG_REGISTRY:-}" + +# Registry definitions +BENCH_REGISTRY_NPM_URL="https://registry.npmjs.org/" +BENCH_REGISTRY_VLT_URL="https://registry.vlt.io/vlt-benchmarks/npm/" +BENCH_REGISTRY_VLT_URL_NPMRC_KEY="${BENCH_REGISTRY_VLT_URL#http*://}" +BENCH_REGISTRY_AWS_URL="https://vlt-451504312483.d.codeartifact.us-east-1.amazonaws.com/npm/code-artifact-benchmark-test/" +BENCH_REGISTRY_AWS_NPMRC_KEY="${BENCH_REGISTRY_AWS_URL#http*://}" +# Cloudsmith registry URL is injected without the protocol prefix +# (e.g. "//example.com/..."), so we prepend "https:" for the registry config. +# The auth .npmrc key uses the URL as-is (without protocol). +BENCH_REGISTRY_CLOUDSMITH_URL="https:${CLOUDSMITH_REGISTRY:-}" +BENCH_REGISTRY_CLOUDSMITH_NPMRC_KEY="${CLOUDSMITH_REGISTRY#//}" + +# GitHub registry URL is injected without the protocol prefix +# (e.g. "//npm.pkg.github.com/..."), so we prepend "https:" for the registry config. +# The auth .npmrc key uses the URL as-is (without protocol). +BENCH_REGISTRY_GITHUB_URL="https:${GH_REGISTRY:-}" +BENCH_REGISTRY_GITHUB_NPMRC_KEY="${GH_REGISTRY#//}" + +# JFrog registry URL is injected without the protocol prefix +# (e.g. "//example.jfrog.io/..."), so we prepend "https:" for the registry config. +# The auth .npmrc key uses the URL as-is (without protocol). +BENCH_REGISTRY_JFROG_URL="https:${JFROG_REGISTRY:-}" +BENCH_REGISTRY_JFROG_NPMRC_KEY="${JFROG_REGISTRY#//}"