AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(ci): nightly benchmark cron with regression alerts + HyperDX dashboard (#15723)
Amr Elmohamady7a4f0ec14666
diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.ymlindex d4009a078bc..3caf0603faa 100644--- a/.github/workflows/benchmark.yml+++ b/.github/workflows/benchmark.yml@@ -4,123 +4,237 @@ on:workflow_dispatch:inputs:total_requests:- description: 'Total number of requests for hey'+ description: 'Total number of requests for the benchmark'required: false- default: '500'+ default: '2000'+ schedule:+ - cron: '0 3 * * *'+jobs:benchmark:- runs-on: depot-ubuntu-24.04-16+ runs-on: depot-ubuntu-24.04-32timeout-minutes: 30env:AP_FILE_STORAGE_LOCATION: ${{ secrets.AP_FILE_STORAGE_LOCATION }}- AP_EXECUTION_MODE: SANDBOX_CODE_ONLY+ AP_EXECUTION_MODE: SANDBOX_PROCESSAP_S3_BUCKET: ${{ secrets.AP_S3_BUCKET }}AP_S3_ACCESS_KEY_ID: ${{ secrets.AP_S3_ACCESS_KEY_ID }}AP_S3_SECRET_ACCESS_KEY: ${{ secrets.AP_S3_SECRET_ACCESS_KEY }}AP_S3_ENDPOINT: ${{ secrets.AP_S3_ENDPOINT }}AP_S3_REGION: ${{ secrets.AP_S3_REGION }}AP_S3_USE_SIGNED_URLS: ${{ secrets.AP_S3_USE_SIGNED_URLS }}+ TOTAL_REQUESTS: ${{ inputs.total_requests || '2000' }}strategy:+ fail-fast: falsematrix:include:- - apps: 1- workers: 2- label: "1app-2workers"- - apps: 2- workers: 4- label: "2app-4workers"- - apps: 3- workers: 6- label: "3app-6workers"- - apps: 1- workers: 4- label: "1app-4workers"- - apps: 2- workers: 8- label: "2app-8workers"- - apps: 3- workers: 12- label: "3app-12workers"+ # Both cells: 28 × 0.5cpu / 1 GB / 1 slot / heap 768M — mirrors the+ # per-host density Kamal deploys on prod 16-vCPU worker boxes.+ # Only AP_REUSE_SANDBOX differs, so any per-cell delta isolates+ # the reuse variable.+ - label: "shared"+ apps: 1+ workers: 28+ worker_cpus: '0.5'+ worker_memory: '1G'+ worker_concurrency: '1'+ worker_heap_mb: '768'+ reuse: 'false'+ total_slots: 28+ - label: "dedicated"+ apps: 1+ workers: 28+ worker_cpus: '0.5'+ worker_memory: '1G'+ worker_concurrency: '1'+ worker_heap_mb: '768'+ reuse: 'true'+ total_slots: 28steps:- name: Checkoutuses: actions/checkout@v5+ - name: Setup Bun+ uses: oven-sh/setup-bun@v2+ with:+ bun-version: latest++ - name: Install monorepo deps (for CLI)+ run: bun install --frozen-lockfile+- name: Build Docker imagerun: docker build -t activepieces-benchmark:local .+ - name: Export cell env (compose reads these on every invocation)+ run: |+ {+ echo "APP_REPLICAS=${{ matrix.apps }}"+ echo "WORKER_REPLICAS=${{ matrix.workers }}"+ echo "WORKER_CPUS=${{ matrix.worker_cpus }}"+ echo "WORKER_MEMORY=${{ matrix.worker_memory }}"+ echo "WORKER_HEAP_MB=${{ matrix.worker_heap_mb }}"+ echo "AP_WORKER_CONCURRENCY=${{ matrix.worker_concurrency }}"+ echo "AP_REUSE_SANDBOX=${{ matrix.reuse }}"+ } >> "$GITHUB_ENV"+- name: Start benchmark stackrun: |- APP_REPLICAS=${{ matrix.apps }} \- WORKER_REPLICAS=${{ matrix.workers }} \- docker compose -f benchmark/docker-compose.yml up -d+ docker compose -f benchmark/docker-compose.yml -f benchmark/docker-compose.ci.yml up -decho "Waiting for containers to start..."sleep 5- docker compose -f benchmark/docker-compose.yml ps+ docker compose -f benchmark/docker-compose.yml -f benchmark/docker-compose.ci.yml ps- - name: Setup flow and wait for app+ - name: Verify container caps (proves the per-cell shape, cpuset partitioned)+ run: |+ echo "=== Container CPU / memory / cpuset (as Docker actually applied) ==="+ for c in $(docker compose -f benchmark/docker-compose.yml -f benchmark/docker-compose.ci.yml ps -q); do+ docker inspect "$c" --format '{{.Name}} quota={{.HostConfig.CpuQuota}} period={{.HostConfig.CpuPeriod}} cpuset={{if .HostConfig.CpusetCpus}}{{.HostConfig.CpusetCpus}}{{else}}(any){{end}} memBytes={{.HostConfig.Memory}}'+ done+ echo+ echo "Effective vCPU = quota / period. Expected this cell:"+ echo " app → 2.00 vCPU (200000/100000) cpuset 16-17"+ echo " worker → ${{ matrix.worker_cpus }} vCPU cpuset 0-15 (${{ matrix.workers }} replica(s))"++ - name: Setup flow, platform API key, and wait for appid: setuprun: |- chmod +x benchmark/setup.sh- FLOW_ID=$(benchmark/setup.sh)+ FLOW_ID=$(BENCH_API_KEY_FILE=/tmp/bench-api-key BENCH_PROJECT_ID_FILE=/tmp/bench-project-id bun run benchmark/setup.ts)echo "flow_id=$FLOW_ID" >> "$GITHUB_OUTPUT"echo "Flow ID: $FLOW_ID"+ test -f /tmp/bench-api-key || { echo "ERROR: /tmp/bench-api-key missing"; exit 1; }+ test -f /tmp/bench-project-id || { echo "ERROR: /tmp/bench-project-id missing"; exit 1; }+ PROJECT_ID=$(cat /tmp/bench-project-id)+ echo "project_id=$PROJECT_ID" >> "$GITHUB_OUTPUT"+ echo "Project ID: $PROJECT_ID"- - name: Setup Go- uses: actions/setup-go@v6- with:- go-version: '1.22'- cache: false+ - name: Load bench API key (masked)+ run: |+ set -euo pipefail+ KEY=$(cat /tmp/bench-api-key)+ echo "::add-mask::$KEY"+ echo "AP_API_KEY=$KEY" >> "$GITHUB_ENV"- - name: Install hey- run: go install github.com/rakyll/hey@latest+ - name: Start docker stats capture+ run: |+ rm -f /tmp/stats.jsonl+ touch /tmp/bench-running+ (+ while [ -f /tmp/bench-running ]; do+ docker stats --no-stream --format '{{json .}}' \+ >> /tmp/stats.jsonl 2>/dev/null || true+ sleep 2+ done+ ) &+ echo "STATS_PID=$!" >> "$GITHUB_ENV"- - name: Warmup+ - name: Run benchmark (activepieces CLI)run: |- echo "Running warmup: 500 requests, ${{ matrix.workers }} concurrency"- hey -n 500 -c ${{ matrix.workers }} -t 60 \- -m POST \- -H "Content-Type: application/json" \- -d '{"test":true}' \- "http://localhost:8080/api/v1/webhooks/${{ steps.setup.outputs.flow_id }}/sync" \- | tail -5- echo "Warmup complete"-- - name: Run benchmark+ set -o pipefail+ bun run packages/cli/src/benchmark-only.ts \+ --url http://localhost:8080 \+ --requests "${TOTAL_REQUESTS}" \+ --concurrency ${{ matrix.total_slots }} \+ --project-id "${{ steps.setup.outputs.project_id }}" \+ --flow-id "${{ steps.setup.outputs.flow_id }}" \+ --json > /tmp/report.json+ echo "--- run summary ---"+ jq '.runs[0].summary, .runs[0].timeline' /tmp/report.json++ - name: Stop docker stats capture+ if: always()run: |- echo "Running benchmark: ${{ inputs.total_requests }} requests, ${{ matrix.workers }} concurrency (= workers), ${{ matrix.apps }} apps"- echo "---"- hey -n ${{ inputs.total_requests }} \- -c ${{ matrix.workers }} \- -t 60 \- -m POST \- -H "Content-Type: application/json" \- -d '{"test":true}' \- "http://localhost:8080/api/v1/webhooks/${{ steps.setup.outputs.flow_id }}/sync" \- | tee /tmp/hey-output.txt-- - name: Parse results+ rm -f /tmp/bench-running+ if [[ "${STATS_PID:-}" =~ ^[1-9][0-9]*$ ]]; then+ for _ in 1 2 3; do+ if ! kill -0 "$STATS_PID" 2>/dev/null; then break; fi+ sleep 1+ done+ kill "$STATS_PID" 2>/dev/null || true+ fi+ wc -l /tmp/stats.jsonl 2>/dev/null || true++ - name: Combine results+ if: '!cancelled()'+ run: |+ node benchmark/aggregate-stats.mjs /tmp/stats.jsonl > /tmp/stats.json+ node benchmark/combine-results.mjs \+ --report /tmp/report.json \+ --stats /tmp/stats.json \+ --sha "${{ github.sha }}" \+ --label "${{ matrix.label }}" \+ --runId "${{ github.run_id }}" \+ --out /tmp/result.json+ cat /tmp/result.json++ - name: Detect regression against trailing 14 runs (scheduled runs only)+ if: '!cancelled() && github.event_name == ''schedule'''+ env:+ CH_HOST: ${{ secrets.CLICKHOUSE_CI_HOST }}+ CH_USER: ${{ secrets.CLICKHOUSE_CI_USER }}+ CH_PASS: ${{ secrets.CLICKHOUSE_CI_PASSWORD }}+ BETTERSTACK_WEBHOOK_URL: ${{ secrets.BETTERSTACK_WEBHOOK_URL }}+ run: |+ node benchmark/detect-regression.mjs \+ --current /tmp/result.json \+ --label "${{ matrix.label }}" \+ --runUrl "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"++ - name: Insert result into ClickHouse (scheduled runs only)+ if: '!cancelled() && github.event_name == ''schedule'''+ env:+ CH_HOST: ${{ secrets.CLICKHOUSE_CI_HOST }}+ CH_USER: ${{ secrets.CLICKHOUSE_CI_USER }}+ CH_PASS: ${{ secrets.CLICKHOUSE_CI_PASSWORD }}run: |- chmod +x benchmark/parse.sh- benchmark/parse.sh /tmp/hey-output.txt /tmp/results.json+ set -o pipefail+ ROW=$(jq -c '{+ ts: (.meta.ts | sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601),+ sha: .meta.sha,+ label: .meta.label,+ run_id: (.meta.runId | tonumber),+ p50_ms: .latency.p50Ms,+ p90_ms: .latency.p90Ms,+ p99_ms: .latency.p99Ms,+ mean_ms: .latency.meanMs,+ req_sec: .throughput.reqSec,+ queue_p90_ms: .timeline.queueWaitP90Ms,+ service_p90_ms: .timeline.serviceP90Ms,+ provision_p50_ms: .timeline.provisionP50Ms,+ boot_p50_ms: .timeline.bootP50Ms,+ app_cpu_p95: (.resources.app.cpuPct.p95 // 0),+ app_mem_max_mb: (.resources.app.memMb.max // 0),+ worker_cpu_p95: (.resources.worker.cpuPct.p95 // 0),+ worker_mem_max_mb: (.resources.worker.memMb.max // 0),+ raw: tojson+ }' /tmp/result.json)+ echo "Row (raw omitted):"+ echo "$ROW" | jq 'del(.raw)'+ printf '%s\n' "$ROW" | curl -sS --fail-with-body \+ --user "$CH_USER:$CH_PASS" \+ --data-binary @- \+ "https://$CH_HOST:8443/?query=INSERT+INTO+bench.results+FORMAT+JSONEachRow"+ echo "ClickHouse insert OK"- - name: Upload results+ - name: Upload artifact (always)if: always()uses: actions/upload-artifact@v6with:name: benchmark-results-${{ matrix.label }}path: |- /tmp/hey-output.txt- /tmp/results.json+ /tmp/report.json+ /tmp/stats.json+ /tmp/stats.jsonl+ /tmp/result.json- name: Show container logs on failureif: failure()run: |- docker compose -f benchmark/docker-compose.yml logs --tail=100+ docker compose -f benchmark/docker-compose.yml -f benchmark/docker-compose.ci.yml logs --tail=100- name: Teardownif: always()- run: docker compose -f benchmark/docker-compose.yml down -v+ run: docker compose -f benchmark/docker-compose.yml -f benchmark/docker-compose.ci.yml down -vsummary:runs-on: ubuntu-latest@@ -137,26 +251,29 @@ jobs:run: |echo "## Benchmark Results Comparison" >> "$GITHUB_STEP_SUMMARY"echo "" >> "$GITHUB_STEP_SUMMARY"- echo "| Configuration | Throughput (req/s) | Mean Latency | P50 | P99 | Fastest | Slowest | 200 OK |" >> "$GITHUB_STEP_SUMMARY"- echo "|---|---|---|---|---|---|---|---|" >> "$GITHUB_STEP_SUMMARY"+ echo "| Config | Throughput | Client p90 | Client p99 | Queue p90 | Service p90 | Worker mem | Worker cpu p95 | App mem |" >> "$GITHUB_STEP_SUMMARY"+ echo "|---|---|---|---|---|---|---|---|---|" >> "$GITHUB_STEP_SUMMARY"for dir in /tmp/results/benchmark-results-*/; dolabel=$(basename "$dir" | sed 's/benchmark-results-//')- json="$dir/results.json"+ json="$dir/result.json"if [ -f "$json" ]; then- throughput=$(jq -r '.throughput' "$json")- mean=$(jq -r '.mean_latency' "$json")- p50=$(jq -r '.p50' "$json")- p99=$(jq -r '.p99' "$json")- fastest=$(jq -r '.fastest' "$json")- slowest=$(jq -r '.slowest' "$json")- ok=$(jq -r '.ok_count' "$json")- echo "| $label | $throughput | ${mean}s | ${p50}s | ${p99}s | ${fastest}s | ${slowest}s | $ok |" >> "$GITHUB_STEP_SUMMARY"+ throughput=$(jq -r '.throughput.reqSec // 0' "$json")+ p90=$(jq -r '.latency.p90Ms // 0' "$json")+ p99=$(jq -r '.latency.p99Ms // 0' "$json")+ qp90=$(jq -r '.timeline.queueWaitP90Ms // 0' "$json")+ sp90=$(jq -r '.timeline.serviceP90Ms // 0' "$json")+ wmem=$(jq -r '.resources.worker.memMb.max // 0' "$json")+ wcpu=$(jq -r '.resources.worker.cpuPct.p95 // 0' "$json")+ amem=$(jq -r '.resources.app.memMb.max // 0' "$json")+ printf "| %s | %s req/s | %s ms | %s ms | %s ms | %s ms | %s MB | %s%% | %s MB |\n" \+ "$label" "$throughput" "$p90" "$p99" "$qp90" "$sp90" "$wmem" "$wcpu" "$amem" \+ >> "$GITHUB_STEP_SUMMARY"else- echo "| $label | N/A | N/A | N/A | N/A | N/A | N/A | N/A |" >> "$GITHUB_STEP_SUMMARY"+ echo "| $label | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A |" >> "$GITHUB_STEP_SUMMARY"fidoneecho "" >> "$GITHUB_STEP_SUMMARY"- echo "**Total requests per config**: ${{ inputs.total_requests || '500' }}" >> "$GITHUB_STEP_SUMMARY"+ echo "**Total requests per config**: ${{ inputs.total_requests || '2000' }}" >> "$GITHUB_STEP_SUMMARY"cat "$GITHUB_STEP_SUMMARY"diff --git a/.github/workflows/dast.yml b/.github/workflows/dast.ymlindex df0e3550eec..9a0ab49b014 100644--- a/.github/workflows/dast.yml+++ b/.github/workflows/dast.yml@@ -46,7 +46,7 @@ jobs:# Sign in with the throwaway account. On cloud, an already-onboarded account# returns a USER token with a projectId; a fresh account returns an ONBOARDING# token (projectId null) which we complete by creating a platform. Mirrors- # benchmark/setup.sh.+ # benchmark/setup.ts.SIGNIN=$(curl -s "${BASE_URL}/authentication/sign-in" \-H "Content-Type: application/json" \-d "{\"email\":\"${DAST_STG_EMAIL}\",\"password\":\"${DAST_STG_PASSWORD}\"}")diff --git a/.github/workflows/smoke-test.yml b/.github/workflows/smoke-test.ymlindex 943f868b681..f738d05ac51 100644--- a/.github/workflows/smoke-test.yml+++ b/.github/workflows/smoke-test.yml@@ -36,6 +36,11 @@ jobs:- name: Checkoutuses: actions/checkout@v5+ - name: Setup Bun (for benchmark/setup.ts)+ uses: oven-sh/setup-bun@v2+ with:+ bun-version: latest+- name: Build Docker imagerun: docker build -t activepieces-benchmark:local .@@ -51,8 +56,7 @@ jobs:- name: Setup flowid: setuprun: |- chmod +x benchmark/setup.sh- FLOW_ID=$(benchmark/setup.sh)+ FLOW_ID=$(bun run benchmark/setup.ts)echo "flow_id=$FLOW_ID" >> "$GITHUB_OUTPUT"echo "Flow ID: $FLOW_ID"@@ -87,7 +91,7 @@ jobs:if: matrix.executionMode == 'SANDBOX_CODE_ONLY'id: setup-oomrun: |- FLOW_ID=$(CODE_BODY_FILE=benchmark/oom-code.js benchmark/setup.sh)+ FLOW_ID=$(CODE_BODY_FILE=benchmark/oom-code.js bun run benchmark/setup.ts)echo "flow_id=$FLOW_ID" >> "$GITHUB_OUTPUT"echo "Flow ID: $FLOW_ID"@@ -120,8 +124,8 @@ jobs:if: matrix.executionMode == 'SANDBOX_CODE_ONLY'id: setup-s3run: |- chmod +x benchmark/setup.sh- FLOW_ID=$(benchmark/setup.sh)++ FLOW_ID=$(bun run benchmark/setup.ts)echo "flow_id=$FLOW_ID" >> "$GITHUB_OUTPUT"echo "Flow ID: $FLOW_ID"@@ -155,8 +159,8 @@ jobs:if: matrix.executionMode == 'SANDBOX_CODE_ONLY'id: setup-s3-signedrun: |- chmod +x benchmark/setup.sh- FLOW_ID=$(benchmark/setup.sh)++ FLOW_ID=$(bun run benchmark/setup.ts)echo "flow_id=$FLOW_ID" >> "$GITHUB_OUTPUT"echo "Flow ID: $FLOW_ID"@@ -172,7 +176,7 @@ jobs:# the bottleneck, not our code), permanently below the 40 req/s threshold, so it would fail# every release. It is not measuring a code regression. Run it on controlled hardware:# docker compose -f benchmark/docker-compose.yml -f benchmark/docker-compose.perf.yml up -d- # benchmark/setup.sh && smoke-test/verify-perf.sh <flow-id>+ # bun run benchmark/setup.ts && smoke-test/verify-perf.sh <flow-id># (both verify-perf.sh and docker-compose.perf.yml are kept in the repo for that.)# All overlays are listed so logs + teardown resolve regardless of which stackdiff --git a/benchmark/aggregate-stats.mjs b/benchmark/aggregate-stats.mjsnew file mode 100644index 00000000000..a79396919c8--- /dev/null+++ b/benchmark/aggregate-stats.mjs@@ -0,0 +1,75 @@+#!/usr/bin/env node+import { readFileSync } from 'node:fs'++const INPUT = process.argv[2]+if (!INPUT) {+ console.error('usage: aggregate-stats.mjs <stats.jsonl>')+ process.exit(2)+}++const raw = readFileSync(INPUT, 'utf8').split('\n').filter(Boolean)+const samples = []+for (const line of raw) {+ try {+ samples.push(JSON.parse(line))+ }+ catch {+ // skip malformed lines (docker stats occasionally interleaves)+ }+}++function parseMemUsageMB(memUsage) {+ const first = memUsage.split('/')[0].trim()+ const match = first.match(/^([0-9.]+)\s*(GiB|MiB|KiB|B)$/)+ if (!match) return 0+ const value = Number(match[1])+ switch (match[2]) {+ case 'GiB': return value * 1024+ case 'MiB': return value+ case 'KiB': return value / 1024+ case 'B': return value / (1024 * 1024)+ default: return 0+ }+}++function parseCpuPct(cpuPerc) {+ return Number(cpuPerc.replace('%', '')) || 0+}++function classify(name) {+ if (name.includes('-worker-') || name.endsWith('-worker')) return 'worker'+ if (name.includes('-app-') || name.endsWith('-app')) return 'app'+ return 'other'+}++function quantile(sorted, q) {+ if (sorted.length === 0) return 0+ const idx = Math.max(0, Math.min(sorted.length - 1, Math.floor(q * (sorted.length - 1))))+ return sorted[idx]+}++const buckets = { app: { cpu: [], mem: [] }, worker: { cpu: [], mem: [] } }+for (const s of samples) {+ const role = classify(s.Name || '')+ if (role === 'other') continue+ buckets[role].cpu.push(parseCpuPct(s.CPUPerc || '0%'))+ buckets[role].mem.push(parseMemUsageMB(s.MemUsage || '0MiB'))+}++function summarize(values) {+ if (values.length === 0) return { samples: 0, max: 0, p95: 0, p50: 0 }+ const sorted = [...values].sort((a, b) => a - b)+ return {+ samples: sorted.length,+ max: sorted[sorted.length - 1],+ p95: quantile(sorted, 0.95),+ p50: quantile(sorted, 0.5),+ }+}++const summary = {+ app: { cpuPct: summarize(buckets.app.cpu), memMb: summarize(buckets.app.mem) },+ worker: { cpuPct: summarize(buckets.worker.cpu), memMb: summarize(buckets.worker.mem) },+}++process.stdout.write(JSON.stringify(summary, null, 2) + '\n')diff --git a/benchmark/combine-results.mjs b/benchmark/combine-results.mjsnew file mode 100644index 00000000000..d51cc3a9496--- /dev/null+++ b/benchmark/combine-results.mjs@@ -0,0 +1,69 @@+#!/usr/bin/env node+import { readFileSync, writeFileSync } from 'node:fs'++const args = Object.fromEntries(+ process.argv.slice(2).reduce((acc, curr, i, arr) => {+ if (curr.startsWith('--')) acc.push([curr.slice(2), arr[i + 1]])+ return acc+ }, []),+)++const required = ['report', 'stats', 'sha', 'label', 'runId', 'out']+for (const key of required) {+ if (!args[key]) {+ console.error(`missing --${key}`)+ process.exit(2)+ }+}++const report = JSON.parse(readFileSync(args.report, 'utf8'))+const stats = JSON.parse(readFileSync(args.stats, 'utf8'))++const run = report.runs?.[0]+if (!run) {+ console.error('report.runs[0] missing — CLI produced no phase results')+ process.exit(1)+}++const s = run.summary ?? {}+const t = run.timeline ?? {}++const result = {+ schemaVersion: 2,+ meta: {+ ts: new Date().toISOString(),+ sha: args.sha,+ label: args.label,+ runId: args.runId,+ loader: 'activepieces-cli',+ cliTarget: report.meta?.target,+ flowId: report.flowId,+ connections: run.connections,+ requests: run.requests,+ },+ latency: {+ p50Ms: s.p50Ms ?? 0,+ p90Ms: s.p90Ms ?? 0,+ p99Ms: s.p99Ms ?? 0,+ meanMs: s.latencyMeanMs ?? 0,+ minMs: s.minMs ?? 0,+ maxMs: s.maxMs ?? 0,+ },+ throughput: { reqSec: s.throughputReqSec ?? 0 },+ counts: { ok2xx: s.ok2xx ?? 0, failed: s.failed ?? 0, errors: s.errors ?? 0, timeouts: s.timeouts ?? 0 },+ timeline: {+ sampleCount: t.sampleCount ?? 0,+ queueWaitP50Ms: t.queueWaitP50 ?? 0,+ queueWaitP90Ms: t.queueWaitP90 ?? 0,+ serviceP50Ms: t.serviceP50 ?? 0,+ serviceP90Ms: t.serviceP90 ?? 0,+ queueMaxMs: t.queueMax ?? 0,+ provisionP50Ms: t.provisionP50 ?? 0,+ bootP50Ms: t.bootP50 ?? 0,+ rateLimitedRuns: t.rateLimitedRunsCount ?? 0,+ },+ resources: stats,+}++writeFileSync(args.out, JSON.stringify(result, null, 2) + '\n')+console.error(`Wrote ${args.out}`)diff --git a/benchmark/detect-regression.mjs b/benchmark/detect-regression.mjsnew file mode 100644index 00000000000..678c6983e8a--- /dev/null+++ b/benchmark/detect-regression.mjs@@ -0,0 +1,173 @@+#!/usr/bin/env node+import { readFileSync } from 'node:fs'++const args = Object.fromEntries(+ process.argv.slice(2).reduce((acc, curr, i, arr) => {+ if (curr.startsWith('--')) acc.push([curr.slice(2), arr[i + 1]])+ return acc+ }, []),+)++const required = ['current', 'label', 'runUrl']+for (const key of required) {+ if (!args[key]) {+ console.error(`missing --${key}`)+ process.exit(2)+ }+}++if (!/^[a-z0-9-]+$/i.test(args.label)) {+ console.error(`--label must match /^[a-z0-9-]+$/i, got ${args.label}`)+ process.exit(2)+}++const THRESHOLD_PCT = Number(args.threshold ?? 5)+const CONSECUTIVE = Number(args.consecutive ?? 2)+const WEBHOOK_URL = process.env.BETTERSTACK_WEBHOOK_URL+const CH_HOST = process.env.CH_HOST+const CH_USER = process.env.CH_USER+const CH_PASS = process.env.CH_PASS++if (!CH_HOST || !CH_USER || !CH_PASS) {+ console.error('CH_HOST / CH_USER / CH_PASS env vars are required')+ process.exit(2)+}++const DIMENSIONS = [+ { name: 'client p90', unit: 'ms', get: (r) => r.latency?.p90Ms ?? 0 },+ { name: 'client p99', unit: 'ms', get: (r) => r.latency?.p99Ms ?? 0 },+ { name: 'throughput', unit: 'req/s', get: (r) => r.throughput?.reqSec ?? 0, invert: true },+ { name: 'queue wait p90', unit: 'ms', get: (r) => r.timeline?.queueWaitP90Ms ?? 0 },+ { name: 'service p90', unit: 'ms', get: (r) => r.timeline?.serviceP90Ms ?? 0 },+ { name: 'provision p50', unit: 'ms', get: (r) => r.timeline?.provisionP50Ms ?? 0 },+ { name: 'boot p50', unit: 'ms', get: (r) => r.timeline?.bootP50Ms ?? 0 },+ { name: 'worker cpu p95', unit: '%', get: (r) => r.resources?.worker?.cpuPct?.p95 ?? 0 },+ { name: 'worker mem max', unit: 'MB', get: (r) => r.resources?.worker?.memMb?.max ?? 0 },+ { name: 'app cpu p95', unit: '%', get: (r) => r.resources?.app?.cpuPct?.p95 ?? 0 },+ { name: 'app mem max', unit: 'MB', get: (r) => r.resources?.app?.memMb?.max ?? 0 },+]++const current = JSON.parse(readFileSync(args.current, 'utf8'))+const history = (await fetchHistory({ label: args.label })).reverse()++console.error(`Loaded ${history.length} trailing rows for label=${args.label}`)++const results = []+for (const dim of DIMENSIONS) {+ const currentValue = dim.get(current)+ const historyValues = history.map(dim.get)+ const baseline = median(historyValues)+ const pct = shiftPct({ current: currentValue, baseline, invert: dim.invert })++ const priorNeeded = Math.max(0, CONSECUTIVE - 1)+ const recentValues = priorNeeded > 0 ? history.slice(-priorNeeded).map(dim.get) : []+ const recentShifts = recentValues.map((v) => shiftPct({ current: v, baseline, invert: dim.invert }))+ const consecutiveBreach = pct > THRESHOLD_PCT+ && recentShifts.length >= priorNeeded+ && recentShifts.every((s) => s > THRESHOLD_PCT)++ results.push({ name: dim.name, unit: dim.unit, currentValue, baseline, pct, breach: consecutiveBreach })+}++const breaches = results.filter((r) => r.breach)+const summary = {+ label: args.label,+ threshold: THRESHOLD_PCT,+ consecutive: CONSECUTIVE,+ historyCount: history.length,+ dimensions: results,+ breachCount: breaches.length,+}+process.stdout.write(JSON.stringify(summary, null, 2) + '\n')++const MIN_HISTORY = Math.max(3, CONSECUTIVE)+if (history.length < MIN_HISTORY) {+ console.error(`History has ${history.length} entries (< ${MIN_HISTORY}); need more baselines before firing.`)+ process.exit(0)+}++const ALERT_ID = `bench-regression-${args.label}`++if (breaches.length === 0) {+ console.error(`No regressions on ${args.label}.`)+ if (!WEBHOOK_URL) process.exit(0)+ await postToBetterstack({+ name: `Bench regression: ${args.label}`,+ cause: `No regressions on \`${args.label}\` (${results.length} dimensions all within ${THRESHOLD_PCT}% of trailing-14 median).\n\n[Run details →](${args.runUrl})`,+ alertId: ALERT_ID,+ state: 'ok',+ })+ process.exit(0)+}++if (!WEBHOOK_URL) {+ console.error(`BREACH on ${args.label} but BETTERSTACK_WEBHOOK_URL unset — skipping alert.`)+ process.exit(0)+}++const lines = breaches.map((b) => `- **${b.name}**: ${b.currentValue.toFixed(2)} ${b.unit} (baseline ${b.baseline.toFixed(2)}, +${b.pct.toFixed(1)}%)`)+const cause = `Benchmark regression on \`${args.label}\` — ${breaches.length} dimension(s) above ${THRESHOLD_PCT}% for ${CONSECUTIVE} consecutive runs:\n\n${lines.join('\n')}\n\n[Run details →](${args.runUrl})\n\nSHA: \`${current.meta.sha}\``++await postToBetterstack({+ name: `Bench regression: ${args.label}`,+ cause,+ alertId: ALERT_ID,+ state: 'alert',+})+console.error(`Alerted Betterstack on ${breaches.length} dimension(s).`)++async function postToBetterstack(payload) {+ const res = await fetch(WEBHOOK_URL, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json; charset=utf-8' },+ body: JSON.stringify(payload),+ })+ if (!res.ok) {+ console.error(`Betterstack webhook responded ${res.status}: ${await res.text().catch(() => '')}`)+ process.exit(1)+ }+}++async function fetchHistory({ label }) {+ const sql = `SELECT p50_ms, p90_ms, p99_ms, mean_ms, req_sec, queue_p90_ms, service_p90_ms, provision_p50_ms, boot_p50_ms, app_cpu_p95, app_mem_max_mb, worker_cpu_p95, worker_mem_max_mb FROM bench.results WHERE label = '${label}' ORDER BY ts DESC LIMIT 14 FORMAT JSONEachRow`+ const url = `https://${CH_HOST}:8443/?query=${encodeURIComponent(sql)}`+ const auth = Buffer.from(`${CH_USER}:${CH_PASS}`).toString('base64')+ const res = await fetch(url, { headers: { Authorization: `Basic ${auth}` } })+ if (!res.ok) {+ const body = await res.text().catch(() => '')+ throw new Error(`ClickHouse history query failed (${res.status}): ${body}`)+ }+ const body = (await res.text()).trim()+ if (!body) return []+ return body.split('\n').map((line) => JSON.parse(line)).map(toResultShape)+}++function toResultShape(row) {+ return {+ latency: { p50Ms: row.p50_ms, p90Ms: row.p90_ms, p99Ms: row.p99_ms, meanMs: row.mean_ms },+ throughput: { reqSec: row.req_sec },+ timeline: {+ queueWaitP90Ms: row.queue_p90_ms,+ serviceP90Ms: row.service_p90_ms,+ provisionP50Ms: row.provision_p50_ms,+ bootP50Ms: row.boot_p50_ms,+ },+ resources: {+ app: { cpuPct: { p95: row.app_cpu_p95 }, memMb: { max: row.app_mem_max_mb } },+ worker: { cpuPct: { p95: row.worker_cpu_p95 }, memMb: { max: row.worker_mem_max_mb } },+ },+ }+}++function median(values) {+ const sorted = [...values].filter((v) => Number.isFinite(v)).sort((a, b) => a - b)+ if (sorted.length === 0) return 0+ const mid = Math.floor(sorted.length / 2)+ return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid]+}++function shiftPct({ current, baseline, invert }) {+ if (baseline === 0) return 0+ const raw = ((current - baseline) / baseline) * 100+ return invert ? -raw : raw+}diff --git a/benchmark/docker-compose.ci.yml b/benchmark/docker-compose.ci.ymlnew file mode 100644index 00000000000..cef74fafb2b--- /dev/null+++ b/benchmark/docker-compose.ci.yml@@ -0,0 +1,53 @@+# CI-only override layered on top of docker-compose.yml.+#+# Keeps bench-specific config out of the base file so smoke-test.yml and dev+# `docker compose up` keep running with CE defaults (base is unchanged from+# the pre-SRE-229 shape).+#+# Adds, as a group, everything the nightly benchmark needs that the smoke+# test does NOT want:+# - cpuset pinning (requires ≥18 cores — breaks smaller dev hosts; fine+# on the 32-vCPU CI runner).+# - AP_EDITION=ee (smoke-test runs CE by design, since most self-hosters+# are on CE; shouldn't be forced to EE just because the bench stack is).+# - AP_NETWORK_MODE=UNRESTRICTED / AP_PROJECT_WORKER: prod-parity env+# (matches Kamal shared tag). Note: prod's Kamal also sets+# AP_PRE_WARM_CACHE=true, but that is dead config — the server does+# not read it (removed), the current prewarm toggle is+# AP_PREWARM_CACHE_ON_STARTUP. We don't set either so cold-boot+# behavior matches real prod.+# - NODE_OPTIONS heap: sized to WORKER_HEAP_MB from the matrix.+# - AP_EXECUTION_MODE=SANDBOX_PROCESS: prod mode. Smoke-test keeps the+# SANDBOX_CODE_ONLY base default.+# - AP_REUSE_SANDBOX: required explicitly via ${:?} so you can't forget+# to pass it per matrix cell. Smoke-test needs the mode-aware default+# from canReuseSandbox() (its verify-memory.sh measures warm reuse).+# - cpus / memory / replicas: overridden per cell by matrix env vars.+#+# Layer usage (CI and run-local, not smoke-test):+# docker compose -f benchmark/docker-compose.yml -f benchmark/docker-compose.ci.yml up -d++services:+ app:+ cpuset: "16-17"+ environment:+ AP_EDITION: ee+ AP_NETWORK_MODE: UNRESTRICTED+ AP_EXECUTION_MODE: ${AP_EXECUTION_MODE:-SANDBOX_PROCESS}++ worker:+ cpuset: "0-15"+ environment:+ AP_EDITION: ee+ AP_NETWORK_MODE: UNRESTRICTED+ AP_PROJECT_WORKER: 'false'+ AP_EXECUTION_MODE: ${AP_EXECUTION_MODE:-SANDBOX_PROCESS}+ AP_REUSE_SANDBOX: ${AP_REUSE_SANDBOX:?AP_REUSE_SANDBOX must be set (true|false) when using docker-compose.ci.yml}+ AP_WORKER_CONCURRENCY: ${AP_WORKER_CONCURRENCY:-1}+ NODE_OPTIONS: --max-old-space-size=${WORKER_HEAP_MB:-768}+ deploy:+ replicas: ${WORKER_REPLICAS:-4}+ resources:+ limits:+ cpus: ${WORKER_CPUS:-0.5}+ memory: ${WORKER_MEMORY:-1G}diff --git a/benchmark/parse.sh b/benchmark/parse.shdeleted file mode 100755index bb8c8812858..00000000000--- a/benchmark/parse.sh+++ /dev/null@@ -1,78 +0,0 @@-#!/usr/bin/env bash-set -euo pipefail--INPUT_FILE="${1:-/tmp/hey-output.txt}"-JSON_FILE="${2:-}"--if [ ! -f "$INPUT_FILE" ]; then- echo "ERROR: hey output file not found: $INPUT_FILE"- exit 1-fi--echo ""-echo "========================================="-echo " BENCHMARK RESULTS"-echo "========================================="-echo ""--# Extract throughput (requests/sec)-THROUGHPUT=$(grep "Requests/sec:" "$INPUT_FILE" | awk '{print $2}')-echo "Throughput: $THROUGHPUT req/s"--# Extract average latency-AVG_LATENCY=$(grep "Average:" "$INPUT_FILE" | head -1 | awk '{print $2}')-echo "Mean latency: ${AVG_LATENCY}s"--# Extract fastest-FASTEST=$(grep "Fastest:" "$INPUT_FILE" | awk '{print $2}')-echo "Fastest: ${FASTEST}s"--# Extract slowest-SLOWEST=$(grep "Slowest:" "$INPUT_FILE" | awk '{print $2}')-echo "Slowest: ${SLOWEST}s"--# Extract status code distribution-echo ""-echo "Status codes:"-sed -n '/Status code distribution/,/^$/p' "$INPUT_FILE" | grep -v "Status code distribution" | sed 's/^/ /'--# Extract latency distribution (includes p50, p99 etc)-echo ""-echo "Latency distribution:"-sed -n '/Latency distribution/,/^$/p' "$INPUT_FILE" | grep -v "Latency distribution" | sed 's/^/ /'--# Calculate success rate-TOTAL=$(grep '\[200\].*responses' "$INPUT_FILE" | awk '{print $2}' || echo "0")-TOTAL_REQUESTS=$(grep "^ Total:" "$INPUT_FILE" | head -1 | awk '{print $2}' || echo "0")--if [ -n "$TOTAL" ] && [ "$TOTAL" != "0" ]; then- echo ""- echo "200 OK count: $TOTAL"-fi--echo ""-echo "========================================="--# Write JSON output if a second argument was provided-if [ -n "$JSON_FILE" ]; then- # Extract latency distribution percentiles- P50=$(sed -n '/Latency distribution/,/^$/p' "$INPUT_FILE" | grep "50%" | awk '{print $3}')- P75=$(sed -n '/Latency distribution/,/^$/p' "$INPUT_FILE" | grep "75%" | awk '{print $3}')- P90=$(sed -n '/Latency distribution/,/^$/p' "$INPUT_FILE" | grep "90%" | awk '{print $3}')- P99=$(sed -n '/Latency distribution/,/^$/p' "$INPUT_FILE" | grep "99%" | awk '{print $3}')-- cat > "$JSON_FILE" <<JSONEOF-{- "throughput": "$THROUGHPUT",- "mean_latency": "$AVG_LATENCY",- "fastest": "$FASTEST",- "slowest": "$SLOWEST",- "ok_count": "$TOTAL",- "p50": "$P50",- "p75": "$P75",- "p90": "$P90",- "p99": "$P99"-}-JSONEOF- echo "JSON results written to $JSON_FILE"-fidiff --git a/benchmark/run-gke.sh b/benchmark/run-gke.shindex 5b1c81261e5..4bf8f619bf5 100755--- a/benchmark/run-gke.sh+++ b/benchmark/run-gke.sh@@ -94,7 +94,7 @@ elsefiecho "=== Setting up flow ==="-FLOW_ID=$(BASE_URL="$BASE_URL" FLOW_ENABLE_TIMEOUT=60 "$ROOT/benchmark/setup.sh")+FLOW_ID=$(BASE_URL="$BASE_URL" FLOW_ENABLE_TIMEOUT=60 bun run "$ROOT/benchmark/setup.ts")echo "Flow ID: $FLOW_ID"# Load is generated INSIDE the cluster, against the app Service — not from the operator's laptop over the# public LoadBalancer. Driving 120+ concurrent sync webhooks from a workstation exhausts its ephemeraldiff --git a/benchmark/run-local.sh b/benchmark/run-local.shindex 85291425d97..4a3edbc9a70 100755--- a/benchmark/run-local.sh+++ b/benchmark/run-local.sh@@ -1,24 +1,53 @@#!/usr/bin/env bashset -euo pipefail-# Local benchmark runner with SANDBOXED mode support-# Usage: ./benchmark/run-local.sh [execution_mode] [total_requests]-# execution_mode: SANDBOXED | SANDBOX_CODE_ONLY (default: SANDBOXED)-# total_requests: number of requests for hey (default: 500)+# Local benchmark runner — reproduces one nightly matrix cell on a dev machine.+# Layers docker-compose.ci.yml on top of the base file, matching CI exactly.+#+# Usage: ./benchmark/run-local.sh [cell] [total_requests]+# cell: shared | dedicated (default: dedicated)+# total_requests: number of requests for the CLI (default: 500)+#+# Env overrides (any subset): EXECUTION_MODE, APP_REPLICAS, WORKER_REPLICAS,+# WORKER_CPUS, WORKER_MEMORY, WORKER_HEAP_MB, AP_WORKER_CONCURRENCY, AP_REUSE_SANDBOX.+#+# Heads-up: docker-compose.ci.yml pins app→cpuset "16-17" and worker→cpuset+# "0-15", so this needs a host with ≥18 CPUs. If you don't have that, drop+# the `-f docker-compose.ci.yml` override below (loses cpuset partitioning+# and requires setting AP_REUSE_SANDBOX explicitly elsewhere).-EXECUTION_MODE=${1:-SANDBOX_CODE_AND_PROCESS}+CELL=${1:-dedicated}TOTAL_REQUESTS=${2:-500}-APP_REPLICAS=${APP_REPLICAS:-1}-WORKER_REPLICAS=${WORKER_REPLICAS:-2}-# SANDBOXED mode needs more time for sandbox initialization-if [ "$EXECUTION_MODE" = "SANDBOXED" ]; then- export FLOW_ENABLE_TIMEOUT=120-else- export FLOW_ENABLE_TIMEOUT=30-fi+case "$CELL" in+ shared|dedicated)+ : "${APP_REPLICAS:=1}"+ : "${WORKER_REPLICAS:=28}"+ : "${WORKER_CPUS:=0.5}"+ : "${WORKER_MEMORY:=1G}"+ : "${WORKER_HEAP_MB:=768}"+ : "${AP_WORKER_CONCURRENCY:=1}"+ ;;+ *)+ echo "ERROR: unknown cell '$CELL' (expected: shared | dedicated)" >&2+ exit 2+ ;;+esac-COMPOSE="docker compose -f $(dirname "$0")/docker-compose.yml"+case "$CELL" in+ shared) : "${AP_REUSE_SANDBOX:=false}" ;;+ dedicated) : "${AP_REUSE_SANDBOX:=true}" ;;+esac++: "${EXECUTION_MODE:=SANDBOX_PROCESS}"+: "${FLOW_ENABLE_TIMEOUT:=120}"+export APP_REPLICAS WORKER_REPLICAS WORKER_CPUS WORKER_MEMORY WORKER_HEAP_MB \+ AP_WORKER_CONCURRENCY AP_REUSE_SANDBOX AP_EXECUTION_MODE FLOW_ENABLE_TIMEOUT+export AP_EXECUTION_MODE=$EXECUTION_MODE++TOTAL_SLOTS=$((WORKER_REPLICAS * AP_WORKER_CONCURRENCY))++COMPOSE="docker compose -f $(dirname "$0")/docker-compose.yml -f $(dirname "$0")/docker-compose.ci.yml"cleanup() {echo "Tearing down..."@@ -29,39 +58,36 @@ trap cleanup EXITecho "=== Building image ==="docker build -t activepieces-benchmark:local .-echo "=== Starting stack (mode=$EXECUTION_MODE, apps=$APP_REPLICAS, workers=$WORKER_REPLICAS) ==="-AP_EXECUTION_MODE=$EXECUTION_MODE \-APP_REPLICAS=$APP_REPLICAS \-WORKER_REPLICAS=$WORKER_REPLICAS \- $COMPOSE up -d+echo "=== Starting stack (cell=$CELL mode=$EXECUTION_MODE apps=$APP_REPLICAS workers=$WORKER_REPLICAS×${WORKER_CPUS}cpu conc=$AP_WORKER_CONCURRENCY total_slots=$TOTAL_SLOTS reuse=$AP_REUSE_SANDBOX) ==="+$COMPOSE up -decho "Waiting for containers to settle..."sleep 5$COMPOSE ps-echo "=== Setting up flow ==="-FLOW_ID=$(FLOW_ENABLE_TIMEOUT=$FLOW_ENABLE_TIMEOUT benchmark/setup.sh)-echo "Flow ID: $FLOW_ID"--echo "=== Warmup ==="-hey -n 500 -c "$WORKER_REPLICAS" -t 60 \- -m POST \- -H "Content-Type: application/json" \- -d '{"test":true}' \- "http://localhost:8080/api/v1/webhooks/$FLOW_ID/sync" \- | tail -5+echo "=== Setting up flow + API key ==="+FLOW_ID=$(FLOW_ENABLE_TIMEOUT=$FLOW_ENABLE_TIMEOUT \+ BENCH_API_KEY_FILE=/tmp/bench-api-key \+ BENCH_PROJECT_ID_FILE=/tmp/bench-project-id \+ bun run benchmark/setup.ts)+PROJECT_ID=$(cat /tmp/bench-project-id)+AP_API_KEY=$(cat /tmp/bench-api-key)+export AP_API_KEY+echo "Flow ID: $FLOW_ID Project ID: $PROJECT_ID"-echo "=== Benchmark ($TOTAL_REQUESTS requests, $WORKER_REPLICAS concurrency) ==="-hey -n "$TOTAL_REQUESTS" \- -c "$WORKER_REPLICAS" \- -t 60 \- -m POST \- -H "Content-Type: application/json" \- -d '{"test":true}' \- "http://localhost:8080/api/v1/webhooks/$FLOW_ID/sync" \- | tee /tmp/hey-output.txt+echo "=== Benchmark ($TOTAL_REQUESTS requests, $TOTAL_SLOTS concurrency = $WORKER_REPLICAS workers × $AP_WORKER_CONCURRENCY slots) ==="+set +e+bun run packages/cli/src/benchmark-only.ts \+ --url http://localhost:8080 \+ --requests "$TOTAL_REQUESTS" \+ --concurrency "$TOTAL_SLOTS" \+ --project-id "$PROJECT_ID" \+ --flow-id "$FLOW_ID" \+ --json > /tmp/report.json+RC=$?+set -e-echo "=== Parsing results ==="-benchmark/parse.sh /tmp/hey-output.txt /tmp/results.json-echo "Results saved to /tmp/results.json"-cat /tmp/results.json+echo "=== Summary ==="+jq '.runs[0].summary, .runs[0].timeline' /tmp/report.json 2>/dev/null || echo "(no valid report at /tmp/report.json)"+echo "Full report saved to /tmp/report.json"+exit $RCdiff --git a/benchmark/run-workerpool.sh b/benchmark/run-workerpool.shindex 3901e5c77d8..66986714cc0 100755--- a/benchmark/run-workerpool.sh+++ b/benchmark/run-workerpool.sh@@ -44,7 +44,7 @@ sleep 8$COMPOSE psecho "=== Setting up flow ==="-FLOW_ID=$(FLOW_ENABLE_TIMEOUT=30 "$ROOT/benchmark/setup.sh")+FLOW_ID=$(FLOW_ENABLE_TIMEOUT=30 bun run "$ROOT/benchmark/setup.ts")echo "Flow ID: $FLOW_ID"WEBHOOK="http://localhost:8080/api/v1/webhooks/$FLOW_ID/sync"diff --git a/benchmark/setup.sh b/benchmark/setup.shdeleted file mode 100755index 39ec4ca9cee..00000000000--- a/benchmark/setup.sh+++ /dev/null@@ -1,271 +0,0 @@-#!/usr/bin/env bash-set -euo pipefail--BASE_URL="${BASE_URL:-http://localhost:8080/api/v1}"-MAX_RETRIES=60-RETRY_INTERVAL=5--# Wait for app to be ready-echo "Waiting for app to be ready..." >&2-for i in $(seq 1 $MAX_RETRIES); do- if curl -sf "$BASE_URL/flags" > /dev/null 2>&1; then- echo "App is ready after $((i * RETRY_INTERVAL))s" >&2- break- fi- if [ "$i" -eq "$MAX_RETRIES" ]; then- echo "ERROR: App did not become ready in time" >&2- exit 1- fi- sleep $RETRY_INTERVAL-done--# Sign up-echo "Authenticating..." >&2-BENCH_EMAIL="${BENCH_EMAIL:[email protected]}"-# Try sign-up (first run creates the platform). On repeat runs public sign-up is disabled once a-# platform exists, so fall back to sign-in with the same fixed credentials. No --fail-with-body here:-# under `set -e` a rejected sign-up would abort the script before we can fall back.-SIGNUP_RESPONSE=$(curl -s "$BASE_URL/authentication/sign-up" \- -H "Content-Type: application/json" \- -d "{\"email\":\"${BENCH_EMAIL}\",\"password\":\"BenchmarkPass1\",\"firstName\":\"Bench\",\"lastName\":\"Mark\",\"trackEvents\":false,\"newsLetter\":false}")-TOKEN=$(echo "$SIGNUP_RESPONSE" | jq -r '.token // empty')-PROJECT_ID=$(echo "$SIGNUP_RESPONSE" | jq -r '.projectId // empty')--if [ -z "$TOKEN" ]; then- echo "Sign-up unavailable (platform exists); signing in..." >&2- SIGNIN_RESPONSE=$(curl -s "$BASE_URL/authentication/sign-in" \- -H "Content-Type: application/json" \- -d "{\"email\":\"${BENCH_EMAIL}\",\"password\":\"BenchmarkPass1\"}")- TOKEN=$(echo "$SIGNIN_RESPONSE" | jq -r '.token // empty')- PROJECT_ID=$(echo "$SIGNIN_RESPONSE" | jq -r '.projectId // empty')-fi--if [ -z "$TOKEN" ]; then- echo "ERROR: could not authenticate (sign-up and sign-in both failed)" >&2- echo "$SIGNUP_RESPONSE" >&2- exit 1-fi--# Cloud edition returns an ONBOARDING token with projectId=null.-# Complete onboarding by creating a platform + project, which returns a fresh USER token.-if [ "$PROJECT_ID" = "null" ] || [ -z "$PROJECT_ID" ]; then- echo "Completing onboarding (creating platform + project)..." >&2- PLATFORM_RESPONSE=$(curl -s --fail-with-body "$BASE_URL/platforms" \- -H "Content-Type: application/json" \- -H "Authorization: Bearer $TOKEN" \- -d '{"name":"Benchmark"}')- TOKEN=$(echo "$PLATFORM_RESPONSE" | jq -r '.token')- PROJECT_ID=$(echo "$PLATFORM_RESPONSE" | jq -r '.projectId')- if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ] || [ -z "$PROJECT_ID" ] || [ "$PROJECT_ID" = "null" ]; then- echo "ERROR: Failed to complete onboarding" >&2- echo "$PLATFORM_RESPONSE" >&2- exit 1- fi-fi-echo "Signed up. Project: $PROJECT_ID" >&2--AUTH="Authorization: Bearer $TOKEN"--WEBHOOK_VERSION="${WEBHOOK_VERSION:-~0.1.36}"-MATH_VERSION="${MATH_VERSION:-~0.0.24}"--wait_for_piece() {- local name="$1" version="$2"- echo "Waiting for $name@$version to be available..." >&2- for i in $(seq 1 600); do- if curl -sf -G "$BASE_URL/pieces/$name" --data-urlencode "version=$version" -H "$AUTH" > /dev/null 2>&1; then- echo "$name@$version is available (took ${i}s)" >&2- return 0- fi- sleep 1- done- echo "ERROR: $name@$version not available after 600s" >&2- exit 1-}-wait_for_piece "@activepieces/piece-webhook" "$WEBHOOK_VERSION"-wait_for_piece "@activepieces/piece-math-helper" "$MATH_VERSION"--# Create flow-echo "Creating flow..." >&2-FLOW_RESPONSE=$(curl -s --fail-with-body "$BASE_URL/flows" \- -H "Content-Type: application/json" \- -H "$AUTH" \- -d "{\"displayName\":\"Benchmark Flow\",\"projectId\":\"$PROJECT_ID\"}")--FLOW_ID=$(echo "$FLOW_RESPONSE" | jq -r '.id')-echo "Flow created: $FLOW_ID" >&2--# Resolve the CODE step body and Return Response body (parameterizable for isolation smoke).-if [ -n "${CODE_BODY_FILE:-}" ]; then- if [ ! -f "$CODE_BODY_FILE" ]; then- echo "ERROR: CODE_BODY_FILE=$CODE_BODY_FILE not found" >&2- exit 1- fi- CODE_STEP_SRC=$(cat "$CODE_BODY_FILE")-else- CODE_STEP_SRC=$'export const code = async (inputs) => {\n return { result: Number(inputs.sum) + 1 };\n};\n'-fi--# CODE step input (parameterizable for the memory-limit smoke: a `{{ ... }}` expression here is-# evaluated inside the engine process in UNSANDBOXED mode, so it can exhaust the sandbox memory).-if [ -z "${CODE_INPUT_SUM:-}" ]; then- CODE_INPUT_SUM='{{step_3}}'-fi--if [ -z "${RESPONSE_BODY:-}" ]; then- RESPONSE_BODY_JSON='{"hello":"world"}'-elif [ "$RESPONSE_BODY" = "{{step_2}}" ]; then- RESPONSE_BODY_JSON='"{{step_2}}"'-else- RESPONSE_BODY_JSON="$RESPONSE_BODY"-fi--# Flow: webhook (latest) -> math-helper addition (latest) -> small CODE step -> return response (latest).-IMPORT_PAYLOAD=$(jq -n \- --arg code "$CODE_STEP_SRC" \- --arg webhookV "$WEBHOOK_VERSION" \- --arg mathV "$MATH_VERSION" \- --arg sumInput "$CODE_INPUT_SUM" \- --argjson body "$RESPONSE_BODY_JSON" \- '{- type: "IMPORT_FLOW",- request: {- displayName: "Benchmark Flow",- schemaVersion: "17",- notes: [],- trigger: {- name: "trigger",- valid: true,- displayName: "Catch Webhook",- type: "PIECE_TRIGGER",- settings: {- pieceName: "@activepieces/piece-webhook",- pieceVersion: $webhookV,- triggerName: "catch_webhook",- input: { authType: "none", authFields: {} },- propertySettings: {- authType: { type: "MANUAL" },- authFields: { type: "MANUAL", schema: {} },- liveMarkdown: { type: "MANUAL" },- syncMarkdown: { type: "MANUAL" },- testMarkdown: { type: "MANUAL" }- },- sampleData: {}- },- nextAction: {- name: "step_3",- skip: false,- type: "PIECE",- valid: true,- settings: {- input: { first_number: 2, second_number: 3 },- pieceName: "@activepieces/piece-math-helper",- actionName: "addition_math",- pieceVersion: $mathV,- sampleData: {},- propertySettings: {- first_number: { type: "MANUAL" },- second_number: { type: "MANUAL" }- },- errorHandlingOptions: {- retryOnFailure: { value: false },- continueOnFailure: { value: false }- }- },- displayName: "Add",- nextAction: {- name: "step_2",- skip: false,- type: "CODE",- valid: true,- settings: {- input: { sum: $sumInput },- sampleData: {},- sourceCode: { code: $code, packageJson: "{}" },- errorHandlingOptions: {- retryOnFailure: { value: false },- continueOnFailure: { value: false }- }- },- displayName: "Code",- nextAction: {- name: "step_1",- skip: false,- type: "PIECE",- valid: true,- settings: {- input: {- fields: { body: $body, status: 200, headers: {} },- respond: "stop",- responseType: "json"- },- pieceName: "@activepieces/piece-webhook",- actionName: "return_response",- sampleData: {},- pieceVersion: $webhookV,- propertySettings: {- fields: {- type: "MANUAL",- schema: {- body: { type: "JSON", required: true, displayName: "JSON Body" },- status: { type: "NUMBER", required: false, displayName: "Status", defaultValue: 200 },- headers: { type: "OBJECT", required: false, displayName: "Headers" }- }- },- respond: { type: "MANUAL" },- responseType: { type: "MANUAL" }- },- errorHandlingOptions: {- retryOnFailure: { value: false },- continueOnFailure: { value: false }- }- },- displayName: "Return Response"- }- }- }- }- }- }')--# Import full flow via IMPORT_FLOW operation-echo "Importing flow definition..." >&2-curl -s --fail-with-body "$BASE_URL/flows/$FLOW_ID" \- -H "Content-Type: application/json" \- -H "$AUTH" \- --data-binary "$IMPORT_PAYLOAD" > /dev/null--# Publish flow-echo "Publishing flow..." >&2-curl -s --fail-with-body "$BASE_URL/flows/$FLOW_ID" \- -H "Content-Type: application/json" \- -H "$AUTH" \- -d '{"type":"LOCK_AND_PUBLISH","request":{}}' > /dev/null--# Enable flow-echo "Enabling flow..." >&2-curl -s --fail-with-body "$BASE_URL/flows/$FLOW_ID" \- -H "Content-Type: application/json" \- -H "$AUTH" \- -d '{"type":"CHANGE_STATUS","request":{"status":"ENABLED"}}' > /dev/null--# Wait for flow to become ENABLED (enabling is async; SANDBOXED mode needs longer)-FLOW_ENABLE_TIMEOUT=${FLOW_ENABLE_TIMEOUT:-30}-echo "Waiting for flow to become ENABLED (timeout: ${FLOW_ENABLE_TIMEOUT}s)..." >&2-for i in $(seq 1 "$FLOW_ENABLE_TIMEOUT"); do- STATUS=$(curl -s "$BASE_URL/flows/$FLOW_ID" \- -H "$AUTH" | jq -r '.status')- if [ "$STATUS" = "ENABLED" ]; then- echo "Flow is ENABLED" >&2- break- fi- if [ "$i" -eq "$FLOW_ENABLE_TIMEOUT" ]; then- echo "WARNING: Flow status is '$STATUS' after ${FLOW_ENABLE_TIMEOUT}s, proceeding anyway" >&2- fi- sleep 1-done--echo "Setup complete. Flow ID: $FLOW_ID" >&2--# Output only the flow ID to stdout-echo "$FLOW_ID"diff --git a/benchmark/setup.ts b/benchmark/setup.tsnew file mode 100644index 00000000000..81ab1da11d2--- /dev/null+++ b/benchmark/setup.ts@@ -0,0 +1,357 @@+#!/usr/bin/env bun+// Idempotent benchmark bootstrap. Replaces setup.sh.+//+// Entry contract (same as the old shell version):+// stdout → FLOW_ID (one line)+// stderr → progress log+// exit 0 → success, non-zero → fatal+//+// Env (all optional):+// BASE_URL default http://localhost:8080/api/v1+// BENCH_EMAIL default [email protected]+// WEBHOOK_VERSION default: resolved from /pieces at runtime+// MATH_VERSION default: resolved from /pieces at runtime+// BENCH_API_KEY_FILE opt-in. When set, mint an API key and write it mode 600.+// Smoke-test leaves it unset; /v1/api-keys is EE-only.+// BENCH_PROJECT_ID_FILE opt-in. When set, write the project id for downstream steps.+// CODE_BODY_FILE optional. Path to a custom CODE step body.+// CODE_INPUT_SUM default "{{step_3}}" — the add-step's output reference.+// RESPONSE_BODY default {"hello":"world"}. "{{step_2}}" is passed through+// as a template reference, anything else is parsed as JSON.+// FLOW_ENABLE_TIMEOUT default 120 seconds.++import { chmodSync, readFileSync, writeFileSync } from 'node:fs'++const BASE_URL = process.env.BASE_URL ?? 'http://localhost:8080/api/v1'+const BENCH_EMAIL = process.env.BENCH_EMAIL ?? '[email protected]'+const BENCH_PASSWORD = 'BenchmarkPass1'+const FLOW_ENABLE_TIMEOUT_S = Number(process.env.FLOW_ENABLE_TIMEOUT ?? 120)++main().catch((err) => {+ log(`ERROR: ${err instanceof Error ? err.message : String(err)}`)+ process.exit(1)+})++async function main(): Promise<void> {+ await waitForApp()+ const auth = await authenticate()+ log(`Signed up. Project: ${auth.projectId}`)++ const versions = await resolvePieceVersions({ auth })+ await verifyPieceAvailable({ auth, name: '@activepieces/piece-webhook', version: versions.webhook })+ await verifyPieceAvailable({ auth, name: '@activepieces/piece-math-helper', version: versions.math })++ await maybeCreateApiKey({ auth })+ const flowId = await createEmptyFlow({ auth })+ log(`Flow created: ${flowId}`)++ await importFlow({ auth, flowId, versions })+ await publish({ auth, flowId })+ await enable({ auth, flowId })+ await waitForEnabled({ auth, flowId })++ maybeWriteProjectIdFile({ auth })++ log(`Setup complete. Flow ID: ${flowId} Project ID: ${auth.projectId}`)+ process.stdout.write(`${flowId}\n`)+}++async function waitForApp(): Promise<void> {+ log('Waiting for app to be ready...')+ await retry({ attempts: 60, delayMs: 5000, name: 'wait-for-app /flags' }, async () => {+ const res = await safeFetch(`${BASE_URL}/flags`)+ return res?.ok ? true : undefined+ })+ log('App is ready')+}++async function authenticate(): Promise<Auth> {+ log('Authenticating...')+ const credentials = { email: BENCH_EMAIL, password: BENCH_PASSWORD }+ const signupBody = { ...credentials, firstName: 'Bench', lastName: 'Mark', trackEvents: false, newsLetter: false }++ // Sign-up is only valid for the first run (creates the platform). On repeat runs public+ // sign-up is disabled → fall back to sign-in with the same fixed credentials.+ const session = (await tryJsonPost<SessionResponse>({ path: '/authentication/sign-up', body: signupBody }))+ ?? (await tryJsonPost<SessionResponse>({ path: '/authentication/sign-in', body: credentials }))+ if (!session?.token) throw new Error('could not authenticate (sign-up and sign-in both failed)')++ let { token, projectId } = session++ // Cloud onboarding tokens return projectId=null; create a platform to get a USER token with one.+ if (!projectId) {+ log('Completing onboarding (creating platform + project)...')+ const platform = await jsonPost<SessionResponse>({ path: '/platforms', body: { name: 'Benchmark' }, auth: { token, projectId: '' } })+ token = platform.token+ projectId = platform.projectId+ if (!token || !projectId) throw new Error('platform create returned incomplete payload')+ }++ return { token, projectId }+}++async function resolvePieceVersions({ auth }: { auth: Auth }): Promise<PieceVersions> {+ let webhook = process.env.WEBHOOK_VERSION+ let math = process.env.MATH_VERSION+ if (webhook && math) return { webhook, math }++ log('Resolving piece versions from registry (polling /pieces up to 600s)...')+ await retry({ attempts: 600, delayMs: 1000, name: 'resolve piece versions' }, async () => {+ const pieces = (await jsonGet<PieceMeta[]>({ path: '/pieces', auth })) ?? []+ webhook = webhook ?? pieces.find((p) => p.name === '@activepieces/piece-webhook')?.version+ math = math ?? pieces.find((p) => p.name === '@activepieces/piece-math-helper')?.version+ return webhook && math ? true : undefined+ })+ log(`Resolved piece versions: webhook=${webhook} math-helper=${math}`)+ return { webhook: webhook!, math: math! }+}++async function verifyPieceAvailable({ auth, name, version }: { auth: Auth; name: string; version: string }): Promise<void> {+ log(`Waiting for ${name}@${version} to be available...`)+ await retry({ attempts: 600, delayMs: 1000, name: `wait ${name}@${version}` }, async () => {+ const path = `/pieces/${encodeURIComponent(name)}?version=${encodeURIComponent(version)}`+ const res = await safeFetch(`${BASE_URL}${path}`, { headers: authHeader(auth) })+ return res?.ok ? true : undefined+ })+}++async function maybeCreateApiKey({ auth }: { auth: Auth }): Promise<void> {+ const file = process.env.BENCH_API_KEY_FILE+ if (!file) return+ log('Creating platform API key for benchmark CLI...')+ const key = await jsonPost<{ value: string }>({ path: '/api-keys', body: { displayName: 'benchmark-cli' }, auth })+ if (!key?.value) throw new Error('API key creation returned empty value')+ writeFileSync(file, key.value, { mode: 0o600 })+ chmodSync(file, 0o600)+ log(`API key written to ${file} (mode 600)`)+}++function maybeWriteProjectIdFile({ auth }: { auth: Auth }): void {+ const file = process.env.BENCH_PROJECT_ID_FILE+ if (!file) return+ writeFileSync(file, auth.projectId)+ log(`Project ID written to ${file}`)+}++async function createEmptyFlow({ auth }: { auth: Auth }): Promise<string> {+ log('Creating flow...')+ const flow = await jsonPost<{ id: string }>({ path: '/flows', body: { displayName: 'Benchmark Flow', projectId: auth.projectId }, auth })+ return flow.id+}++async function importFlow({ auth, flowId, versions }: { auth: Auth; flowId: string; versions: PieceVersions }): Promise<void> {+ log('Importing flow definition...')+ await jsonPost<unknown>({+ path: `/flows/${flowId}`,+ body: buildImportRequest({+ versions,+ codeSrc: readCodeStepSrc(),+ sumInput: process.env.CODE_INPUT_SUM ?? '{{step_3}}',+ responseBody: resolveResponseBody(),+ }),+ auth,+ })+}++async function publish({ auth, flowId }: { auth: Auth; flowId: string }): Promise<void> {+ log('Publishing flow...')+ await jsonPost<unknown>({ path: `/flows/${flowId}`, body: { type: 'LOCK_AND_PUBLISH', request: {} }, auth })+}++async function enable({ auth, flowId }: { auth: Auth; flowId: string }): Promise<void> {+ log('Enabling flow...')+ await jsonPost<unknown>({ path: `/flows/${flowId}`, body: { type: 'CHANGE_STATUS', request: { status: 'ENABLED' } }, auth })+}++async function waitForEnabled({ auth, flowId }: { auth: Auth; flowId: string }): Promise<void> {+ log(`Waiting for flow to become ENABLED (timeout: ${FLOW_ENABLE_TIMEOUT_S}s)...`)+ for (let i = 1; i <= FLOW_ENABLE_TIMEOUT_S; i++) {+ const flow = await jsonGet<{ status: string }>({ path: `/flows/${flowId}`, auth })+ if (flow?.status === 'ENABLED') { log('Flow is ENABLED'); return }+ await delay(1000)+ }+ log(`WARNING: Flow still not ENABLED after ${FLOW_ENABLE_TIMEOUT_S}s, proceeding anyway`)+}++async function retry<T>({ attempts, delayMs, name }: { attempts: number; delayMs: number; name: string }, fn: () => Promise<T | undefined>): Promise<T> {+ for (let i = 1; i <= attempts; i++) {+ const result = await fn()+ if (result !== undefined) return result+ if (i === attempts) throw new Error(`${name}: no result after ${attempts} attempts`)+ await delay(delayMs)+ }+ throw new Error('unreachable')+}++async function safeFetch(url: string, init?: RequestInit): Promise<Response | null> {+ try { return await fetch(url, init) } catch { return null }+}++async function jsonGet<T>({ path, auth }: { path: string; auth: Auth }): Promise<T | undefined> {+ const res = await safeFetch(`${BASE_URL}${path}`, { headers: authHeader(auth) })+ if (!res?.ok) return undefined+ return (await res.json()) as T+}++async function jsonPost<T>({ path, body, auth }: { path: string; body: unknown; auth?: Auth }): Promise<T> {+ const res = await fetch(`${BASE_URL}${path}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', ...(auth ? authHeader(auth) : {}) },+ body: JSON.stringify(body),+ })+ if (!res.ok) throw new Error(`POST ${path} failed (${res.status}): ${await res.text().catch(() => '')}`)+ return (await res.json()) as T+}++async function tryJsonPost<T>(args: { path: string; body: unknown; auth?: Auth }): Promise<T | undefined> {+ try { return await jsonPost<T>(args) } catch { return undefined }+}++function authHeader({ token }: Auth): Record<string, string> {+ return { authorization: `Bearer ${token}` }+}++function delay(ms: number): Promise<void> {+ return new Promise((r) => setTimeout(r, ms))+}++function log(msg: string): void {+ process.stderr.write(`${msg}\n`)+}++function readCodeStepSrc(): string {+ const codeBodyFile = process.env.CODE_BODY_FILE+ if (!codeBodyFile) {+ return 'export const code = async (inputs) => {\n return { result: Number(inputs.sum) + 1 };\n};\n'+ }+ try { return readFileSync(codeBodyFile, 'utf8') }+ catch { throw new Error(`CODE_BODY_FILE=${codeBodyFile} not found`) }+}++function resolveResponseBody(): unknown {+ const raw = process.env.RESPONSE_BODY+ if (!raw) return { hello: 'world' }+ if (raw === '{{step_2}}') return '{{step_2}}'+ return JSON.parse(raw)+}++function buildImportRequest({ versions, codeSrc, sumInput, responseBody }: BuildImportOpts): object {+ return {+ type: 'IMPORT_FLOW',+ request: {+ displayName: 'Benchmark Flow',+ schemaVersion: '17',+ notes: [],+ trigger: {+ name: 'trigger',+ valid: true,+ displayName: 'Catch Webhook',+ type: 'PIECE_TRIGGER',+ settings: {+ pieceName: '@activepieces/piece-webhook',+ pieceVersion: versions.webhook,+ triggerName: 'catch_webhook',+ input: { authType: 'none', authFields: {} },+ propertySettings: {+ authType: { type: 'MANUAL' },+ authFields: { type: 'MANUAL', schema: {} },+ liveMarkdown: { type: 'MANUAL' },+ syncMarkdown: { type: 'MANUAL' },+ testMarkdown: { type: 'MANUAL' },+ },+ sampleData: {},+ },+ nextAction: buildMathStep({+ mathVersion: versions.math,+ nextAction: buildCodeStep({+ codeSrc,+ sumInput,+ nextAction: buildReturnResponseStep({ webhookVersion: versions.webhook, responseBody }),+ }),+ }),+ },+ },+ }+}++function buildMathStep({ mathVersion, nextAction }: { mathVersion: string; nextAction: object }): object {+ return {+ name: 'step_3',+ skip: false,+ type: 'PIECE',+ valid: true,+ displayName: 'Add',+ settings: {+ input: { first_number: 2, second_number: 3 },+ pieceName: '@activepieces/piece-math-helper',+ actionName: 'addition_math',+ pieceVersion: mathVersion,+ sampleData: {},+ propertySettings: {+ first_number: { type: 'MANUAL' },+ second_number: { type: 'MANUAL' },+ },+ errorHandlingOptions: NO_RETRY,+ },+ nextAction,+ }+}++function buildCodeStep({ codeSrc, sumInput, nextAction }: { codeSrc: string; sumInput: string; nextAction: object }): object {+ return {+ name: 'step_2',+ skip: false,+ type: 'CODE',+ valid: true,+ displayName: 'Code',+ settings: {+ input: { sum: sumInput },+ sampleData: {},+ sourceCode: { code: codeSrc, packageJson: '{}' },+ errorHandlingOptions: NO_RETRY,+ },+ nextAction,+ }+}++function buildReturnResponseStep({ webhookVersion, responseBody }: { webhookVersion: string; responseBody: unknown }): object {+ return {+ name: 'step_1',+ skip: false,+ type: 'PIECE',+ valid: true,+ displayName: 'Return Response',+ settings: {+ input: {+ fields: { body: responseBody, status: 200, headers: {} },+ respond: 'stop',+ responseType: 'json',+ },+ pieceName: '@activepieces/piece-webhook',+ actionName: 'return_response',+ sampleData: {},+ pieceVersion: webhookVersion,+ propertySettings: {+ fields: {+ type: 'MANUAL',+ schema: {+ body: { type: 'JSON', required: true, displayName: 'JSON Body' },+ status: { type: 'NUMBER', required: false, displayName: 'Status', defaultValue: 200 },+ headers: { type: 'OBJECT', required: false, displayName: 'Headers' },+ },+ },+ respond: { type: 'MANUAL' },+ responseType: { type: 'MANUAL' },+ },+ errorHandlingOptions: NO_RETRY,+ },+ }+}++const NO_RETRY = { retryOnFailure: { value: false }, continueOnFailure: { value: false } }++type Auth = { token: string; projectId: string }+type SessionResponse = { token: string; projectId: string }+type PieceMeta = { name: string; version: string }+type PieceVersions = { webhook: string; math: string }+type BuildImportOpts = { versions: PieceVersions; codeSrc: string; sumInput: string; responseBody: unknown }diff --git a/packages/cli/src/benchmark-only.ts b/packages/cli/src/benchmark-only.tsnew file mode 100644index 00000000000..950b52a6df9--- /dev/null+++ b/packages/cli/src/benchmark-only.ts@@ -0,0 +1,12 @@+import { Command } from 'commander';+import { benchmarkCommand } from './lib/commands/benchmark';++const program = new Command()+ .name('activepieces-benchmark')+ .description('Standalone entry that only loads the benchmark command, avoiding the transitive imports of the full CLI.');++program.addCommand(benchmarkCommand);+program.parseAsync(['node', 'benchmark-only', 'benchmark', ...process.argv.slice(2)]).catch((err) => {+ console.error(err);+ process.exit(1);+});diff --git a/packages/cli/src/lib/commands/benchmark.ts b/packages/cli/src/lib/commands/benchmark.tsindex 2d84a38611b..85aa75f5366 100644--- a/packages/cli/src/lib/commands/benchmark.ts+++ b/packages/cli/src/lib/commands/benchmark.ts@@ -3,7 +3,7 @@ import autocannon from 'autocannon';import axios, { AxiosInstance, AxiosError } from 'axios';import chalk from 'chalk';import { Command } from 'commander';-import { Project } from '@activepieces/shared';+import type { Project } from '@activepieces/shared';const BENCHMARK_DOC = 'Load-test a deployment\'s sync-webhook path, auto-discover its shape, and attribute latency (queue-wait vs service-time) against the recommended setup.';@@ -13,6 +13,8 @@ export const benchmarkCommand = new Command('benchmark').option('--requests <n>', 'Total requests to fire (default: 40 x concurrency)').option('--concurrency <c>', 'Concurrent connections (default: auto = sum of worker execution slots)').option('--api-key <key>', 'Platform API key (Bearer). Or set AP_API_KEY.')+ .option('--project-id <id>', 'Reuse an existing project ID (skip throwaway provision + teardown). Useful in CI where the platform plan does not allow team-project creation.')+ .option('--flow-id <id>', 'Reuse an existing sync-webhook flow ID (skip flow creation). Requires --project-id.').option('--body <json>', 'JSON request body sent to the webhook', '{"test":true}').option('--json', 'Emit machine-readable JSON output').action(async (opts) => {@@ -35,12 +37,15 @@ export const benchmarkCommand = new Command('benchmark')measureNetwork(authed),]);- const project = await provisionProject({ client: authed });- log(config, `Provisioned throwaway project ${project.id}`);+ const reusedProjectId = config.projectId;+ const project = reusedProjectId+ ? { id: reusedProjectId }+ : await provisionProject({ client: authed });+ log(config, reusedProjectId ? `Reusing project ${project.id}` : `Provisioned throwaway project ${project.id}`);const runsFailed = await (async () => {const projectLimits = await collectProjectLimits({ client: authed, projectId: project.id, rateLimiterEnabled: flags['PROJECT_RATE_LIMITER_ENABLED'] === true });- const flowId = await createBenchmarkFlow({ client: authed, projectId: project.id });- log(config, `Flow ready: ${flowId}`);+ const flowId = config.flowId ?? await createBenchmarkFlow({ client: authed, projectId: project.id });+ log(config, config.flowId ? `Reusing flow ${flowId}` : `Flow ready: ${flowId}`);const slots = setup.executionSlots;const phases = benchmarkUtils.resolvePhases({ concurrency: config.concurrency, slots });@@ -83,8 +88,10 @@ export const benchmarkCommand = new Command('benchmark')}return runs.some((r) => r.summary.failed > 0);})().finally(async () => {- log(config, `Deleting throwaway project ${project.id}`);- await deleteProject({ client: authed, id: project.id });+ if (!reusedProjectId) {+ log(config, `Deleting throwaway project ${project.id}`);+ await deleteProject({ client: authed, id: project.id });+ }});process.exit(runsFailed ? 1 : 0);} catch (e) {@@ -108,11 +115,18 @@ function normalizeOptions(opts: Record<string, string | boolean | undefined>): Bthrow new Error(`--body must be valid JSON, got "${opts.body}"`);}const url = String(opts.url);+ const projectId = typeof opts.projectId === 'string' ? opts.projectId : undefined;+ const flowId = typeof opts.flowId === 'string' ? opts.flowId : undefined;+ if (Boolean(projectId) !== Boolean(flowId)) {+ throw new Error('--project-id and --flow-id must be provided together, or both omitted (letting the CLI provision and delete its own throwaway project + flow).');+ }return {url: url.endsWith('/') ? url.slice(0, -1) : url,requests,concurrency,apiKey: typeof opts.apiKey === 'string' ? opts.apiKey : undefined,+ projectId,+ flowId,body,json: opts.json === true,};@@ -941,6 +955,8 @@ const DIAGNOSTIC_FLAGS = [export const benchmarkUtils = { normalizeOptions, toSummary, resolvePhases, validateSetup, aggregateTimeline, percentile, aggregateOutsideRuns };type BenchmarkConfig = {+ projectId?: string;+ flowId?: string;url: string;requests?: number;concurrency?: number;diff --git a/smoke-test/verify-delay.sh b/smoke-test/verify-delay.shindex bfbc27b0758..bae668a98e4 100755--- a/smoke-test/verify-delay.sh+++ b/smoke-test/verify-delay.sh@@ -10,7 +10,7 @@ echo "Base URL: $BASE_URL"echo "Poll Timeout: ${POLL_TIMEOUT}s"echo ""-# Sign in with existing benchmark user (created by benchmark/setup.sh)+# Sign in with existing benchmark user (created by benchmark/setup.ts)echo "--- Signing in ---"SIGNIN_RESPONSE=$(curl -s --fail-with-body "$API_URL/authentication/sign-in" \-H "Content-Type: application/json" \diff --git a/smoke-test/verify-memory-limit.sh b/smoke-test/verify-memory-limit.shindex a6319ab597b..a3bc02b2233 100755--- a/smoke-test/verify-memory-limit.sh+++ b/smoke-test/verify-memory-limit.sh@@ -2,7 +2,7 @@set -euo pipefail# Verifies that a flow that exhausts the sandbox memory reliably ends with flow run status-# MEMORY_LIMIT_EXCEEDED. Expects a flow created by benchmark/setup.sh with+# MEMORY_LIMIT_EXCEEDED. Expects a flow created by benchmark/setup.ts with# CODE_BODY_FILE=benchmark/oom-code.js on a stack running# AP_EXECUTION_MODE=SANDBOX_CODE_ONLY. The code step builds ~50MB inside the 128MB v8# isolate (an array of refs to one big string), and the engine's outRef.copy() then@@ -23,7 +23,7 @@ echo "Base URL: $BASE_URL"echo "Runs: $NUM_RUNS"echo ""-# Sign in with the fixed benchmark credentials created by benchmark/setup.sh+# Sign in with the fixed benchmark credentials created by benchmark/setup.tsSIGNIN_RESPONSE=$(curl -s "$API/authentication/sign-in" \-H "Content-Type: application/json" \-d "{\"email\":\"${BENCH_EMAIL}\",\"password\":\"BenchmarkPass1\"}")diff --git a/smoke-test/verify-s3.sh b/smoke-test/verify-s3.shindex bb5f7064484..f78469eefe6 100755--- a/smoke-test/verify-s3.sh+++ b/smoke-test/verify-s3.sh@@ -23,7 +23,7 @@ echo "Base URL: $BASE_URL"echo "Requests: $NUM_REQUESTS"echo ""-# Sign in with the existing benchmark user (created by benchmark/setup.sh).+# Sign in with the existing benchmark user (created by benchmark/setup.ts).echo "--- Signing in ---"SIGNIN_RESPONSE=$(curl -s --fail-with-body "$API_URL/authentication/sign-in" \-H "Content-Type: application/json" \