Kaynağa Gözat

Big-project performance gate: synthetic projects, perfbench gate metrics, perf-gate script, CI step

Community slice B12. core/PerfProjects.h generates the gate's projects
deterministically (synth100, inserts50, stream, and new big200: 200
channels, 120 inserts with LYNX's own effects, 2,000 clips, 200
automation clips; automation: 400 dense automation clips + tempo).
perfbench gains big200 / automation / calibrate and --gate (CPU,
instructions, import / build / rebuild time, peak memory, hash).
LYNX --perfgen writes them as .lynx + WAVs with save / load times;
--paintbench reports the open time and memory. scripts/perf-gate.sh
measures, compares with tests/perf/baseline-<profile>.json and fails
on a regression (cells measured again first). Render-ahead counts the
probes kept on by favourFewerOverruns alone; --rtstress shows the probes.
Ka1-S 2 hafta önce
ebeveyn
işleme
ed83da86ab

+ 25 - 1
.github/workflows/tests.yml

@@ -129,7 +129,7 @@ jobs:
           cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_JUCE="$RUNNER_TEMP/juce" \
             -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_OBJC_COMPILER_LAUNCHER=ccache -DCMAKE_OBJCXX_COMPILER_LAUNCHER=ccache \
             -DLYNX_LTO=OFF
-          cmake --build build --target LYNX lynx_remote_project_tests -- -k 0
+          cmake --build build --target LYNX lynx_remote_project_tests perfbench -- -k 0
           ccache --show-stats || true
 
       - name: Remote project document regressions
@@ -153,6 +153,30 @@ jobs:
           cat selftest.txt
           grep -q '^result=OK' selftest.txt
 
+      # Round perfgate190id (community slice B12): the big-project performance gate on the synthetic projects
+      # (core/PerfProjects.h): audio CPU per block size, load / rebuild time, memory, .lynx save / load, open time and
+      # paint per frame of every view, against tests/perf/baseline-ci-ubuntu.json (scripts/perf-gate.sh; times are
+      # divided by a fixed calibration run, failing cells are measured again before the gate fails).
+      - name: Performance gate (big projects)
+        if: runner.os == 'Linux'
+        shell: bash
+        run: |
+          sudo sysctl -w kernel.perf_event_paranoid=1 > /dev/null 2>&1 || true # (the CPU's instruction counter, where the VM has one)
+          PROFILE=ci-ubuntu PERFBENCH=build/perfbench LYNX_APP=build/LYNX_artefacts/Release/LYNX \
+            scripts/perf-gate.sh compare "$PWD/perfgate"
+
+      - name: Upload the performance gate results
+        if: always() && runner.os == 'Linux'
+        uses: actions/upload-artifact@v4
+        with:
+          name: perfgate-results
+          path: |
+            perfgate/*.txt
+            perfgate/*.json
+            perfgate/*.md
+          retention-days: 30
+          if-no-files-found: ignore
+
       # Issue #85: no LV2 child while nothing changed, one when something did; a child that fails changes nothing
       - name: LV2 scan
         if: runner.os == 'Linux'

+ 150 - 0
scripts/perf-gate.sh

@@ -0,0 +1,150 @@
+#!/usr/bin/env bash
+# perf-gate.sh: the big-project performance gate (round perfgate190id, community slice B12; docs/PERFORMANCE-GATE.md).
+#
+# Measures, headless, on heavy projects: the audio engine's CPU per block size (64 / 128 / 256, one thread; also the
+# instructions retired where the CPU counters can be read), the project's import / first build / rebuild (an edit's
+# new snapshot) and the peak memory (tools/perfbench); with the app: .lynx save and load times (--perfgen), the open
+# time and memory and the paint cost per frame of every main view (--paintbench, off screen), and optionally the full
+# start-up with the project (--opentime, a window: Xvfb). Then compares with a stored baseline (tests/perf/) and fails
+# on any regression past its threshold (scripts/perf_gate.py; cells that fail are measured once more first, and the
+# best run counts).
+#
+# Projects: the synthetic ones of core/PerfProjects.h (synth100, inserts50, stream, big200, automation; generated, the
+# same bytes every time) and, with FL=1, FL Studio's demo songs Thief and Exoplanet plus Live's Patience from the
+# local installs (never committed). CI runs the synthetic ones (.github/workflows/tests.yml, profile ci-ubuntu).
+#
+# usage: scripts/perf-gate.sh [compare|update|measure] [results dir]
+#   compare (default)  measure, then compare with tests/perf/baseline-$PROFILE.json; exit 1 on a regression
+#   update             measure twice and write the baseline (after a reviewed, intended change: commit it with a reason)
+#   measure            measure only (results.json)
+# env:
+#   PROFILE=local         baseline name (local = this machine; ci-ubuntu = GitHub's ubuntu-24.04 runners)
+#   PERFBENCH=path        tools/perfbench build (default: build-linux/perfbench, then build/perfbench)
+#   LYNX_APP=path         the app (default: build-linux/LYNX_artefacts/Release/LYNX, then build/...); APP=0: skip it
+#   OPENTIME=1            also --opentime (opens a window: needs DISPLAY, xvfb-run, or XVFB=<Xvfb binary>)
+#   FL=1                  also FL's Thief / Exoplanet and Live's Patience (FL_ROOT, LIVE_DEMO)
+#   BLOCKS="64 128 256"   SCENARIOS="synth100 inserts50 stream big200 automation"   SECONDS_AUDIO=8   REPS=3
+#   CORES=7-11            pin the measurements (taskset); LOAD_MAX=6 / LOAD_WAIT=1800: wait for a quiet machine (local)
+set -u
+cd "$(dirname "$0")/.."
+ROOT=$PWD
+mode=${1:-compare}
+OUT=${2:-$ROOT/build-perfgate/$(date +%Y%m%d-%H%M%S)}
+PROFILE=${PROFILE:-local}
+BASELINE=${BASELINE:-$ROOT/tests/perf/baseline-$PROFILE.json}
+BLOCKS=${BLOCKS:-"64 128 256"}
+SCENARIOS=${SCENARIOS:-"synth100 inserts50 stream big200 automation"}
+SECONDS_AUDIO=${SECONDS_AUDIO:-8}
+REPS=${REPS:-3}
+LOAD_MAX=${LOAD_MAX:-}
+LOAD_WAIT=${LOAD_WAIT:-1800}
+FL_ROOT=${FL_ROOT:-"/mnt/c/Program Files/Image-Line/FL Studio 2026"}
+LIVE_DEMO=${LIVE_DEMO:-"/mnt/c/ProgramData/Ableton/Live 12 Trial/Resources/Core Library/Lessons/Demo Songs/Chuck Sutton - Patience (Live 12 Suite Demo).als"}
+first () { for f in "$@"; do [ -x "$f" ] && { echo "$f"; return; }; done; }
+PERFBENCH=${PERFBENCH:-$(first build-linux/perfbench build/perfbench)}
+[ -n "$PERFBENCH" ] && [ -x "$PERFBENCH" ] || { echo "perf-gate: no perfbench (build the 'perfbench' target, or set PERFBENCH)" >&2; exit 2; }
+if [ "${APP:-1}" != 0 ]; then LYNX_APP=${LYNX_APP:-$(first build-linux/LYNX_artefacts/Release/LYNX build/LYNX_artefacts/Release/LYNX)}; else LYNX_APP=; fi
+mkdir -p "$OUT"
+PIN=(); [ -n "${CORES:-}" ] && PIN=(taskset -c "$CORES")
+
+# FL demo songs (local only, never committed)
+declare -A FLP=([thief]="$FL_ROOT/Data/Demo projects/Demo songs/Ookay - Thief.flp" [exoplanet]="$FL_ROOT/Data/Demo projects/Demo songs/Eric Kauffmann & NrgMind - Exoplanet.flp")
+EXTRA=()
+if [ "${FL:-0}" = 1 ]; then
+  for k in thief exoplanet; do [ -f "${FLP[$k]}" ] && EXTRA+=("$k") || echo "perf-gate: FL demo $k not found, skipped" >&2; done
+  [ -f "$LIVE_DEMO" ] && EXTRA+=(patience) || echo "perf-gate: Live demo not found, skipped" >&2
+fi
+scenario_arg () { case $1 in thief|exoplanet) echo "flp:${FLP[$1]}";; patience) echo "als:$LIVE_DEMO";; *) echo "$1";; esac; }
+project_file () { case $1 in thief|exoplanet) echo "${FLP[$1]}";; patience) echo "$LIVE_DEMO";; *) echo "$OUT/projects/$1.lynx";; esac; }
+
+quiet () { # wait for a quiet machine (local runs: other jobs skew the numbers); logs the load
+  [ -z "$LOAD_MAX" ] && return 0
+  local t=0
+  while awk "BEGIN{exit !($(cut -d' ' -f1 /proc/loadavg) >= $LOAD_MAX)}"; do
+    [ $t -ge "$LOAD_WAIT" ] && { echo "perf-gate: load still $(cut -d' ' -f1 /proc/loadavg) after ${LOAD_WAIT}s, measuring anyway" >&2; return 0; }
+    sleep 15; t=$((t + 15))
+  done
+}
+
+# the app's commands: a private Xvfb when there is no display and XVFB names one; else xvfb-run
+XPID=
+app_env=(env LYNX_TEST_MODE=1 LYNX_PROFILE_DIR="$OUT/profile" XDG_CONFIG_HOME="$OUT/xdg")
+app_run () { # report-producing app command (timeout 15 min)
+  if [ -n "${DISPLAY:-}" ]; then timeout 900 "${app_env[@]}" "${PIN[@]}" "$LYNX_APP" "$@"
+  elif command -v xvfb-run > /dev/null; then timeout 900 "${app_env[@]}" xvfb-run -a "${PIN[@]}" "$LYNX_APP" "$@"
+  else timeout 900 "${app_env[@]}" "${PIN[@]}" "$LYNX_APP" "$@"; fi
+}
+if [ -n "$LYNX_APP" ] && [ -z "${DISPLAY:-}" ] && [ -n "${XVFB:-}" ]; then
+  d=$((90 + RANDOM % 9)); "$XVFB" ":$d" -screen 0 1920x1080x24 -nolisten tcp > "$OUT/xvfb.log" 2>&1 & XPID=$!
+  export DISPLAY=":$d"; sleep 2
+fi
+cleanup () { [ -n "$XPID" ] && kill "$XPID" 2> /dev/null; [ -n "${GITHUB_STEP_SUMMARY:-}" ] && [ -f "$OUT/summary.md" ] && cat "$OUT/summary.md" >> "$GITHUB_STEP_SUMMARY"; return 0; }
+trap cleanup EXIT
+
+{ echo "$(uname -sm), $(grep -m1 'model name' /proc/cpuinfo 2> /dev/null | cut -d: -f2 | sed 's/^ //'), $(nproc) threads, $(git rev-parse --short HEAD 2> /dev/null)"; } > "$OUT/machine.txt"
+
+calibrate () { "${PIN[@]}" "$PERFBENCH" calibrate > "$OUT/calib-$1.txt" 2>&1; }
+bench () { # cell (scenario@block) run
+  local s=${1%@*} b=${1#*@} extra=()
+  quiet
+  echo "load $(cut -d' ' -f1 /proc/loadavg)" > "$OUT/bench-$1-$2.txt"
+  timeout 1200 "${PIN[@]}" "$PERFBENCH" "$(scenario_arg "$s")" --block "$b" --seconds "$SECONDS_AUDIO" --reps "$REPS" --gate "${extra[@]}" >> "$OUT/bench-$1-$2.txt" 2>&1 \
+    || echo "perf-gate: perfbench $1 failed (exit $?)" | tee -a "$OUT/errors.txt" >&2
+}
+paint () { # project run
+  quiet
+  LYNX_PAINTBENCH_FRAMES=${PAINT_FRAMES:-20} app_run --paintbench "$(project_file "$1")" "$OUT/paint-$1-$2.txt" > "$OUT/paint-$1-$2.log" 2>&1
+  grep -q '^result=OK' "$OUT/paint-$1-$2.txt" 2> /dev/null || echo "perf-gate: paintbench $1 failed" | tee -a "$OUT/errors.txt" >&2
+}
+opentime () { # project run (a window)
+  quiet
+  app_run --opentime "$(project_file "$1")" "$OUT/open-$1-$2.txt" 3 > "$OUT/open-$1-$2.log" 2>&1
+  grep -q '^result=OK' "$OUT/open-$1-$2.txt" 2> /dev/null || echo "perf-gate: opentime $1 failed" | tee -a "$OUT/errors.txt" >&2
+}
+projects () { local p; for p in $SCENARIOS; do echo "$p"; done; for p in "${EXTRA[@]}"; do echo "$p"; done; }
+
+measure_all () { # run number
+  local n=$1 s b p
+  calibrate "$n-a"
+  for s in $(projects); do for b in $BLOCKS; do echo "== bench $s@$b #$n"; bench "$s@$b" "$n"; done; done
+  if [ -n "$LYNX_APP" ]; then
+    [ -f "$OUT/perfgen.txt" ] || { echo "== perfgen"; app_run --perfgen "$OUT/projects" "$OUT/perfgen.txt" "$(echo $SCENARIOS | tr ' ' ,)" > "$OUT/perfgen.log" 2>&1; grep -q '^result=OK' "$OUT/perfgen.txt" 2> /dev/null || echo "perf-gate: perfgen failed" | tee -a "$OUT/errors.txt" >&2; }
+    for p in $(projects); do echo "== paint $p #$n"; paint "$p" "$n"; done
+    if [ "${OPENTIME:-0}" = 1 ]; then for p in $(projects); do echo "== opentime $p #$n"; opentime "$p" "$n"; done; fi
+  fi
+  calibrate "$n-b"
+}
+
+retry_cells () { # run number; the cells perf_gate.py listed
+  local n=$1 c
+  calibrate "$n-a"
+  while read -r c; do
+    case $c in
+      bench:*) echo "== retry bench ${c#bench:}"; bench "${c#bench:}" "$n" ;;
+      paint:*) echo "== retry paint ${c#paint:}"; paint "${c#paint:}" "$n" ;;
+      open:*) echo "== retry opentime ${c#open:}"; opentime "${c#open:}" "$n" ;;
+    esac
+  done < "$OUT/retry.txt"
+  calibrate "$n-b"
+}
+
+echo "perf-gate: $mode, profile $PROFILE, results in $OUT; perfbench $PERFBENCH; app ${LYNX_APP:-none}; extra: ${EXTRA[*]:-none}"
+case $mode in
+  measure) measure_all 1; python3 scripts/perf_gate.py collect "$OUT" > /dev/null; echo "perf-gate: $OUT/results.json" ;;
+  update) measure_all 1; measure_all 2; mkdir -p "$(dirname "$BASELINE")"; python3 scripts/perf_gate.py update "$OUT" "$BASELINE" ;;
+  compare)
+    if [ ! -f "$BASELINE" ]; then # (a new profile: nothing to compare with; the run becomes a candidate baseline)
+      measure_all 1; python3 scripts/perf_gate.py update "$OUT" "$OUT/baseline-candidate.json" > /dev/null
+      echo "::warning::perf-gate: no baseline $BASELINE: nothing compared; candidate in $OUT/baseline-candidate.json (commit it as the baseline after a review)"
+      exit 0
+    fi
+    measure_all 1
+    python3 scripts/perf_gate.py compare "$OUT" "$BASELINE" > /dev/null && { cat "$OUT/summary.md"; exit 0; }
+    for n in $(seq 2 $((1 + ${RETRIES:-2}))); do # (failing cells again: a busy moment on a shared runner is not a regression)
+      echo "perf-gate: measuring again: $(tr '\n' ' ' < "$OUT/retry.txt")"
+      retry_cells "$n"
+      python3 scripts/perf_gate.py compare "$OUT" "$BASELINE" > /dev/null && { cat "$OUT/summary.md"; exit 0; }
+    done
+    cat "$OUT/summary.md"; exit 1 ;;
+  *) echo "usage: $0 [compare|update|measure] [results dir]" >&2; exit 2 ;;
+esac

+ 226 - 0
scripts/perf_gate.py

@@ -0,0 +1,226 @@
+#!/usr/bin/env python3
+"""Big-project performance gate: collect, compare, update (round perfgate190id, community slice B12).
+
+scripts/perf-gate.sh runs the measurements into a results folder; this script reads it.
+
+  perf_gate.py collect <results dir>                      -> <dir>/results.json (every metric, best of the runs)
+  perf_gate.py compare <results dir> <baseline.json>      -> <dir>/summary.md; exit 1 on a regression, and the
+                                                             cells to measure again in <dir>/retry.txt
+  perf_gate.py update  <results dir> <baseline.json>      -> writes the baseline from these results (keeps its
+                                                             thresholds)
+
+Files in the results folder (written by perf-gate.sh):
+  calib-<n>.txt              perfbench calibrate (GATE scenario=calibrate calib_ms=...)
+  bench-<cell>-<n>.txt       perfbench <scenario> --gate (one GATE line); <cell> = <scenario>@<block>
+  paint-<project>-<n>.txt    LYNX --paintbench report (open line, "<view>, whole frame: median X ms ...")
+  open-<project>-<n>.txt     LYNX --opentime report (key=value lines)
+  perfgen.txt                LYNX --perfgen report (save_ms / load_ms per project)
+
+Metrics are "lower is better". With several runs of a cell the best (lowest) value counts: noise on a shared machine
+only ever adds time. Times are divided by the run's calibration (a fixed piece of work, perfbench calibrate), so a
+faster or slower machine moves both alike; memory and instruction counts are compared as they are.
+
+A metric regresses when it is worse than the baseline by more than its relative threshold AND by more than its
+absolute floor (small values are noisy in absolute terms). Missing metrics that the baseline has fail too (a step
+that stopped working). Metrics without a baseline are reported as new and never fail.
+"""
+import json
+import os
+import re
+import sys
+from collections import defaultdict
+
+# default thresholds: (relative, absolute floor in the metric's own unit after normalisation)
+DEFAULT_THRESHOLDS = {
+    "instr_per_sample": [0.04, 50.0],
+    "cpu_norm": [0.20, 0.0],          # CPU % of a core / calibration ms
+    "build_norm": [0.30, 0.02],
+    "rebuild_norm": [0.30, 0.02],
+    "import_norm": [0.30, 0.02],
+    "rss_mb": [0.10, 12.0],
+    "paint_norm": [0.30, 0.004],
+    "open_norm": [0.30, 0.2],
+    "open_rss_mb": [0.10, 24.0],
+    "save_norm": [0.30, 0.05],
+    "load_norm": [0.30, 0.05],
+    "opentime_load_norm": [0.30, 0.5],
+    "opentime_rss_mb": [0.12, 32.0],
+    "idle_cpu_pct": [0.50, 1.5],
+}
+
+NUM = r"(-?[0-9.]+)"
+
+
+def kv(line):
+    return dict(re.findall(r"(\w+)=(\S+)", line))
+
+
+def calibration(d):
+    vals = []
+    for f in sorted(os.listdir(d)):
+        if f.startswith("calib-"):
+            for line in open(os.path.join(d, f), errors="replace"):
+                if line.startswith("GATE "):
+                    vals.append(float(kv(line)["calib_ms"]))
+    if not vals:
+        sys.exit("perf_gate: no calibration in " + d)
+    vals.sort()
+    return vals[len(vals) // 2], vals
+
+
+def collect(d):
+    calib, calibs = calibration(d)
+    runs = defaultdict(list)  # metric -> values
+    info = {}
+
+    def add(key, value):
+        if value is not None and value == value and value >= 0:
+            runs[key].append(value)
+
+    for f in sorted(os.listdir(d)):
+        p = os.path.join(d, f)
+        m = re.match(r"bench-(.+)-\d+\.txt$", f)
+        if m:
+            cell = m.group(1)
+            for line in open(p, errors="replace"):
+                if not line.startswith("GATE "):
+                    continue
+                g = kv(line)
+                base = "bench/" + cell + "/"
+                add(base + "cpu_norm", float(g["cpu_pct"]) / calib)
+                if float(g["instr_per_sample"]) > 0:
+                    add(base + "instr_per_sample", float(g["instr_per_sample"]))
+                if cell.endswith("@256"):  # (the project's load: once per scenario is enough)
+                    add(base + "build_norm", float(g["build_ms"]) / calib)
+                    add(base + "rebuild_norm", float(g["rebuild_ms"]) / calib)
+                    add(base + "import_norm", float(g["import_ms"]) / calib)
+                    add(base + "rss_mb", float(g["rss_mb"]))
+                info["hash/" + cell] = g["hash"]
+            continue
+        m = re.match(r"paint-(.+)-\d+\.txt$", f)
+        if m:
+            proj = m.group(1)
+            text = open(p, errors="replace").read()
+            if "result=OK" not in text:
+                continue
+            om = re.search(r"^open: " + NUM + r" ms wall, " + NUM + r" ms message thread CPU, working set " + NUM + " MB", text, re.M)
+            if om:
+                add("app/" + proj + "/open_norm", float(om.group(1)) / calib)
+                add("app/" + proj + "/open_rss_mb", float(om.group(3)))
+            for vm in re.finditer(r"^([a-z ]+), whole frame: median " + NUM + r" ms", text, re.M):
+                add("paint/" + proj + "/" + vm.group(1).replace(" ", "_") + "/paint_norm", float(vm.group(2)) / calib)
+            continue
+        m = re.match(r"open-(.+)-\d+\.txt$", f)
+        if m:
+            proj = m.group(1)
+            g = dict(line.strip().split("=", 1) for line in open(p, errors="replace") if "=" in line)
+            if g.get("result") != "OK":
+                continue
+            loaded, window = float(g["loaded_s"]), float(g["window_s"])
+            add("opentime/" + proj + "/opentime_load_norm", 1000.0 * max(0.0, loaded - window) / calib)
+            add("opentime/" + proj + "/opentime_rss_mb", float(g["working_set_mb"]))
+            add("opentime/" + proj + "/idle_cpu_pct", float(g["idle_cpu_pct"]))
+            continue
+        if f == "perfgen.txt":
+            for line in open(p, errors="replace"):
+                pm = re.match(r"(\w+): (.*)", line)
+                if pm and "save_ms=" in line:
+                    g = kv(pm.group(2))
+                    add("project/" + pm.group(1) + "/save_norm", float(g["save_ms"]) / calib)
+                    add("project/" + pm.group(1) + "/load_norm", float(g["load_ms"]) / calib)
+                    info["lynx_hash/" + pm.group(1)] = g.get("text_hash", "")
+    metrics = {k: min(v) for k, v in runs.items()}
+    return {"calib_ms": calib, "calib_runs": calibs, "metrics": metrics, "runs": dict(runs), "info": info,
+            "machine": open(os.path.join(d, "machine.txt")).read().strip() if os.path.exists(os.path.join(d, "machine.txt")) else ""}
+
+
+def threshold_for(key, thresholds):
+    name = key.rsplit("/", 1)[1]
+    # a baseline may override per metric name or per full key
+    return thresholds.get(key) or thresholds.get(name) or DEFAULT_THRESHOLDS.get(name, [0.25, 0.0])
+
+
+def cell_of(key):
+    parts = key.split("/")
+    if parts[0] == "bench":
+        return "bench:" + parts[1]
+    if parts[0] in ("paint", "app"):
+        return "paint:" + parts[1]
+    if parts[0] == "opentime":
+        return "open:" + parts[1]
+    return "perfgen"
+
+
+def fmt(v):
+    return ("%.4g" % v) if abs(v) < 1000 else "%.0f" % v
+
+
+def compare(d, baseline_path):
+    res = collect(d)
+    json.dump(res, open(os.path.join(d, "results.json"), "w"), indent=1, sort_keys=True)
+    base = json.load(open(baseline_path))
+    thresholds = dict(DEFAULT_THRESHOLDS)
+    thresholds.update(base.get("thresholds", {}))
+    bm, cm = base.get("metrics", {}), res["metrics"]
+    rows, failed, retry = [], [], set()
+    for key in sorted(set(bm) | set(cm)):
+        rel, floor = threshold_for(key, thresholds)
+        if key not in cm:
+            rows.append((key, fmt(bm[key]), "missing", "", "FAIL (missing)"))
+            failed.append(key)
+            retry.add(cell_of(key))
+            continue
+        if key not in bm:
+            rows.append((key, "", fmt(cm[key]), "", "new"))
+            continue
+        b, c = bm[key], cm[key]
+        delta = (c - b) / b if b > 0 else 0.0
+        worse = c > b * (1.0 + rel) and c - b > floor
+        verdict = "FAIL" if worse else ("better" if c < b * (1.0 - rel) and b - c > floor else "ok")
+        if worse:
+            failed.append(key)
+            retry.add(cell_of(key))
+        rows.append((key, fmt(b), fmt(c), "%+.1f%%" % (100.0 * delta), verdict + " (limit +%.0f%%)" % (100 * rel)))
+    out = ["# Performance gate: %s" % ("FAILED" if failed else "passed"), "",
+           "Baseline `%s` (%s, calibration %.2f ms); this run: %s, calibration %.2f ms (runs %s)." % (
+               os.path.basename(baseline_path), base.get("machine", "?"), base.get("calib_ms", 0), res["machine"], res["calib_ms"],
+               ", ".join("%.2f" % x for x in res["calib_runs"])), "",
+           "Times are divided by the calibration (\\_norm); lower is better; best of the runs.", "",
+           "| metric | baseline | now | change | verdict |", "|---|---|---|---|---|"]
+    out += ["| %s |" % " | ".join(r) for r in rows]
+    if failed:
+        out += ["", "**Regressed:** " + ", ".join(failed)]
+    changed = [k for k, v in res["info"].items() if k.startswith("hash/") and base.get("info", {}).get(k) not in (None, v)]
+    if changed:
+        out += ["", "Output hash changed (not a performance failure; a sound change must be intended): " + ", ".join(changed)]
+    text = "\n".join(out) + "\n"
+    open(os.path.join(d, "summary.md"), "w").write(text)
+    open(os.path.join(d, "retry.txt"), "w").write("\n".join(sorted(retry)) + ("\n" if retry else ""))
+    print(text)
+    return 1 if failed else 0
+
+
+def update(d, baseline_path):
+    res = collect(d)
+    json.dump(res, open(os.path.join(d, "results.json"), "w"), indent=1, sort_keys=True)
+    old = json.load(open(baseline_path)) if os.path.exists(baseline_path) else {}
+    new = {"profile": old.get("profile", os.path.splitext(os.path.basename(baseline_path))[0]),
+           "machine": res["machine"], "calib_ms": res["calib_ms"], "metrics": res["metrics"], "info": res["info"],
+           "thresholds": old.get("thresholds", {})}
+    if old.get("note"):
+        new["note"] = old["note"]
+    json.dump(new, open(baseline_path, "w"), indent=1, sort_keys=True)
+    open(baseline_path, "a").write("\n")
+    print("perf_gate: wrote %s (%d metrics)" % (baseline_path, len(res["metrics"])))
+    return 0
+
+
+if __name__ == "__main__":
+    if len(sys.argv) < 3 or sys.argv[1] not in ("collect", "compare", "update"):
+        sys.exit(__doc__)
+    if sys.argv[1] == "collect":
+        r = collect(sys.argv[2])
+        json.dump(r, open(os.path.join(sys.argv[2], "results.json"), "w"), indent=1, sort_keys=True)
+        print(json.dumps(r["metrics"], indent=1, sort_keys=True))
+        sys.exit(0)
+    sys.exit((compare if sys.argv[1] == "compare" else update)(sys.argv[2], sys.argv[3]))

+ 99 - 0
src/Main.cpp

@@ -59,6 +59,7 @@
 #include "flp/Flp.h"
 #include "core/DemoSongs.h"
 #include "core/FirstSongTour.h"
+#include "core/PerfProjects.h"
 #include "core/ShowcaseSong.h"
 #include "core/RenderAhead.h"
 #include "core/SynthPresets.h"
@@ -687,6 +688,17 @@ public:
             return;
         }
 
+        if (args.contains ("--perfgen"))
+        {
+            // round perfgate190id: the big-project performance gate's synthetic projects (core/PerfProjects.h) as .lynx
+            // files with their WAVs: --perfgen <folder> [report.txt] [name,name...]; the save and load times in the report
+            const auto i = args.indexOf ("--perfgen");
+            const auto report = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
+            const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
+            runPerfGen (args[i + 1].unquoted(), report, only);
+            return;
+        }
+
         if (args.contains ("--sandboxtest"))
         {
             const auto i = args.indexOf ("--sandboxtest");
@@ -10371,6 +10383,87 @@ private:
         quit();
     }
 
+    // --perfgen (round perfgate190id): each synthetic project of the performance gate written as <folder>/<name>.lynx, its
+    // audio as 16-bit WAVs in <folder>/<name>/ (written once: the same code makes the same audio). The report gives, per
+    // project, the .lynx size, the time to write it (ProjectFile::save, which reads it back) and to read it
+    // (ProjectFile::load), the medians of 5, and a hash of its text.
+    void runPerfGen (const juce::String& folderPath, const juce::String& reportPath, const juce::String& only)
+    {
+        const juce::File folder (folderPath);
+        folder.createDirectory();
+        const auto wanted = juce::StringArray::fromTokens (only, ",", "");
+        juce::String report;
+        bool ok = true;
+        auto median = [] (std::vector<double> v) {
+            std::sort (v.begin(), v.end());
+            return v[v.size() / 2];
+        };
+        for (const auto& name : lynx::perfprojects::names())
+        {
+            if (! wanted.isEmpty() && ! wanted.contains (juce::String (name)))
+                continue;
+            lynx::Song song;
+            lynx::perfprojects::Samples samples;
+            const auto audioFolder = folder.getChildFile (juce::String (name));
+            lynx::perfprojects::make (name, song, samples, audioFolder.getFullPathName().toStdString());
+            for (const auto& [path, data] : samples)
+            {
+                const juce::File wav (juce::String (path));
+                if (wav.existsAsFile())
+                    continue;
+                wav.getParentDirectory().createDirectory();
+                const auto frames = (int) data->frames();
+                juce::AudioBuffer<float> audio (2, frames);
+                audio.copyFrom (0, 0, data->leftData(), frames);
+                audio.copyFrom (1, 0, data->rightData(), frames);
+                juce::WavAudioFormat format;
+                std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
+                if (auto* w = out != nullptr ? format.createWriterFor (out.get(), data->sampleRate, 2, 16, {}, 0) : nullptr)
+                {
+                    out.release();
+                    std::unique_ptr<juce::AudioFormatWriter> writer (w);
+                    ok = writer->writeFromAudioSampleBuffer (audio, 0, frames) && ok;
+                }
+                else
+                    ok = false;
+            }
+            const auto file = folder.getChildFile (juce::String (name) + ".lynx");
+            std::vector<double> saveMs, loadMs;
+            juce::String error;
+            bool loadedOk = true;
+            for (int rep = 0; rep < 5; ++rep)
+            {
+                const auto t0 = juce::Time::getMillisecondCounterHiRes();
+                ok = lynx::ProjectFile::save (song, file, error) && ok;
+                const auto t1 = juce::Time::getMillisecondCounterHiRes();
+                const auto loaded = lynx::ProjectFile::load (file, error);
+                const auto t2 = juce::Time::getMillisecondCounterHiRes();
+                loadedOk = loadedOk && loaded.has_value() && loaded->channels.size() == song.channels.size()
+                           && loaded->playlist.size() == song.playlist.size() && loaded->automations.size() == song.automations.size();
+                saveMs.push_back (t1 - t0);
+                loadMs.push_back (t2 - t1);
+            }
+            ok = ok && loadedOk;
+            const auto text = file.loadFileAsString();
+            std::uint64_t h = 1469598103934665603ull;
+            for (auto* c = text.toRawUTF8(); *c != 0; ++c)
+                h = (h ^ (std::uint8_t) *c) * 1099511628211ull;
+            report << name << ": channels=" << (int) song.channels.size() << " inserts=" << (int) song.mixer.size() - 1
+                   << " clips=" << (int) song.playlist.size() << " automations=" << (int) song.automations.size()
+                   << " wavs=" << (int) samples.size() << " lynx_kb=" << juce::String ((double) file.getSize() / 1024.0, 1)
+                   << " save_ms=" << juce::String (median (saveMs), 2) << " load_ms=" << juce::String (median (loadMs), 2)
+                   << " roundtrip=" << (loadedOk ? "OK" : "FAILED") << " text_hash=" << juce::String::toHexString ((juce::int64) h)
+                   << (error.isNotEmpty() ? " error=" + error : juce::String()) << "\n";
+        }
+        report << "result=" << (ok ? "OK" : "FAILED") << "\n";
+        if (reportPath.isNotEmpty())
+            juce::File (reportPath).replaceWithText (report);
+        else
+            std::fputs (report.toRawUTF8(), stdout);
+        setApplicationReturnValue (ok ? 0 : 1);
+        quit();
+    }
+
     void runShowcase (const juce::String& outputPath, int currentPattern)
     {
         const auto song = lynx::makeShowcaseSong (currentPattern);
@@ -20416,8 +20509,14 @@ private:
              << ", window " << ui.getWidth() << "x" << ui.getHeight() << "\n";
         if (project.existsAsFile())
         {
+            // (round perfgate190id) the time to open it headless, and the memory after
+            const auto open0 = juce::Time::getMillisecondCounterHiRes();
+            const auto cpu0 = lynx::threadCpuSeconds();
             ui.openFile (project);
             offline.dispatchPendingMessages();
+            text << "open: " << juce::String (juce::Time::getMillisecondCounterHiRes() - open0, 1) << " ms wall, "
+                 << juce::String (1000.0 * (lynx::threadCpuSeconds() - cpu0), 1) << " ms message thread CPU, working set "
+                 << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << " MB\n";
         }
         const auto& song = offline.getSong();
         text << "channels " << (int) song.channels.size() << ", patterns " << (int) song.patterns.size() << ", playlist clips " << (int) song.playlist.size()

+ 527 - 0
src/core/PerfProjects.h

@@ -0,0 +1,527 @@
+#pragma once
+
+// The big-project performance gate's synthetic projects (round perfgate190id, community slice B12: "big projects make
+// the UI sluggish; slow load"). Deterministic: the same code makes the same song, bit for bit, so a change of a
+// measurement is a change of LYNX, never of the project. Used by tools/perfbench.cpp (audio CPU, load, memory; the
+// CI gate) and by `LYNX --perfgen <folder>` (the same songs as .lynx files + their WAVs, for --paintbench / --opentime
+// and by hand). scripts/perf-gate.sh runs the gate; baselines in tests/perf/.
+//
+//   synth100     100 built-in synth channels into 50 inserts, 3 effects each (round 190ge)
+//   inserts50    one synth through 50 inserts chained by sends, 4 effects each (round 190ge)
+//   stream       24 audio clips of 60 s on 12 inserts: long audio streaming (round 190ge)
+//   big200       200 channels (synths, drums, samplers, audio clips), 120 inserts (100 + 20 buses) with LYNX's own
+//                effects, 2,000 pattern / audio clips and 200 automation clips over 64 bars
+//   automation   32 synths, 16 inserts, 400 automation clips with a point every 16th (volume, pan, sends, effect
+//                parameters and mixes, channel levels, the tempo)
+//
+// Header only, no JUCE.
+
+#include <cmath>
+#include <cstdint>
+#include <map>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "core/Effects.h"
+#include "core/Instruments.h"
+#include "core/Song.h"
+#include "core/SynthPresets.h"
+
+namespace lynx::perfprojects
+{
+using Samples = std::map<std::string, std::shared_ptr<const SampleData>>;
+
+inline const std::vector<std::string>& names()
+{
+    static const std::vector<std::string> n { "synth100", "inserts50", "stream", "big200", "automation" };
+    return n;
+}
+
+inline SynthSettings presetAt (std::size_t k)
+{
+    static const auto presets = synthPresets();
+    return presets.empty() ? SynthSettings {} : presets[k % presets.size()].second;
+}
+
+inline Note makeNote (int channel, double beat, double beats, int key, float velocity)
+{
+    Note n;
+    n.channel = channel;
+    n.start = (std::int64_t) (beat * ppq);
+    n.length = (std::int64_t) (beats * ppq);
+    n.key = key;
+    n.velocity = velocity;
+    return n;
+}
+
+// a deterministic take: a tone at `hz` with a little noise (LCG), stereo
+inline std::shared_ptr<SampleData> makeTake (double seconds, double hz, std::uint32_t seed, float level = 0.2f)
+{
+    auto data = std::make_shared<SampleData>();
+    const auto frames = (std::size_t) (44100.0 * seconds);
+    data->left.resize (frames);
+    data->right.resize (frames);
+    double phase = 0.0;
+    for (std::size_t i = 0; i < frames; ++i)
+    {
+        seed = seed * 1664525u + 1013904223u;
+        const auto noise = (float) ((int) (seed >> 9) - (1 << 22)) / (float) (1 << 22);
+        phase += hz / 44100.0;
+        const auto tone = (float) std::sin (6.283185307179586 * phase);
+        data->left[i] = level * tone + 0.02f * noise;
+        data->right[i] = level * tone - 0.02f * noise;
+    }
+    return data;
+}
+
+// a one-shot for the sampler channels: a decaying tone with a click, 0.4 s
+inline std::shared_ptr<SampleData> makeHit (double hz, std::uint32_t seed)
+{
+    auto data = std::make_shared<SampleData>();
+    const auto frames = (std::size_t) (44100.0 * 0.4);
+    data->left.resize (frames);
+    data->right.resize (frames);
+    for (std::size_t i = 0; i < frames; ++i)
+    {
+        seed = seed * 1664525u + 1013904223u;
+        const auto t = (double) i / 44100.0;
+        const auto noise = (float) ((int) (seed >> 9) - (1 << 22)) / (float) (1 << 22);
+        const auto v = (float) (std::exp (-t * 9.0) * std::sin (6.283185307179586 * hz * t * (1.0 + 0.5 * std::exp (-t * 30.0))))
+                       + (float) std::exp (-t * 120.0) * noise * 0.5f;
+        data->left[i] = 0.6f * v;
+        data->right[i] = 0.6f * v;
+    }
+    return data;
+}
+
+// 100 synth channels, two per insert, 50 inserts with 3 effects each; every channel plays 4-bar loops (a held chord
+// on even channels, an eighth-note line on odd ones) for the whole song
+inline Song synth100 (int bars = 16)
+{
+    Song song;
+    song.bpm = 128.0;
+    song.mixer = Song::defaultMixer (50);
+    constexpr int channels = 100;
+    const EffectKind chains[][3] = {
+        { EffectKind::parametricEq, EffectKind::compressor, EffectKind::reverb },
+        { EffectKind::facetEq, EffectKind::crestCompressor, EffectKind::delay },
+        { EffectKind::eq, EffectKind::chorus, EffectKind::apexLimiter },
+        { EffectKind::filter, EffectKind::ember, EffectKind::atrium },
+        { EffectKind::ridgeStrip, EffectKind::echoform, EffectKind::limiter },
+    };
+    for (int t = 1; t <= 50; ++t)
+        for (const auto kind : chains[(std::size_t) (t % 5)])
+            song.mixer[(std::size_t) t].effects.push_back (makeEffectSlot (kind));
+    const int roots[4] = { 45, 41, 48, 43 };
+    for (int c = 0; c < channels; ++c)
+    {
+        ChannelDef ch;
+        ch.name = "Synth " + std::to_string (c + 1);
+        ch.instrument = InstrumentKind::synth;
+        ch.synth = presetAt ((std::size_t) c);
+        ch.volume = 0.3f;
+        ch.mixerTrack = 1 + c / 2;
+        song.channels.push_back (ch);
+        auto& p = song.patterns.emplace_back();
+        p.name = ch.name;
+        for (int bar = 0; bar < 4; ++bar)
+        {
+            const auto root = roots[bar] + 12 * (c % 3);
+            if (c % 2 == 0)
+                for (int k : { 0, 4, 7 })
+                    p.notes.push_back (makeNote (c, bar * 4, 3.9, root + k, 0.7f));
+            else
+                for (int e = 0; e < 8; ++e)
+                    p.notes.push_back (makeNote (c, bar * 4 + e * 0.5, 0.4, root + 12 + (e * 5) % 12, 0.8f));
+        }
+        for (int b = 0; b < bars; b += 4)
+        {
+            Clip clip;
+            clip.pattern = c;
+            clip.track = c % 100;
+            clip.start = (std::int64_t) b * 4 * ppq;
+            clip.length = p.effectiveLength (song.meter());
+            song.playlist.push_back (clip);
+        }
+    }
+    song.mode = PlayMode::song;
+    return song;
+}
+
+// one synth into insert 1; inserts 1..50 in a chain of sends (n → n+1), 4 effects each, the last to the Master
+inline Song inserts50 (int bars = 16)
+{
+    Song song;
+    song.bpm = 128.0;
+    song.mixer = Song::defaultMixer (50);
+    const EffectKind kinds[] = { EffectKind::parametricEq, EffectKind::compressor, EffectKind::distortion, EffectKind::chorus,
+                                 EffectKind::facetEq, EffectKind::ember, EffectKind::delay, EffectKind::utility };
+    for (int t = 1; t <= 50; ++t)
+    {
+        for (int k = 0; k < 4; ++k)
+        {
+            auto slot = makeEffectSlot (kinds[(std::size_t) ((t + k) % 8)]);
+            slot.mix = 0.5f;
+            song.mixer[(std::size_t) t].effects.push_back (slot);
+        }
+        if (t < 50)
+        {
+            song.mixer[(std::size_t) t].sends.clear();
+            song.mixer[(std::size_t) t].toMaster = false;
+            MixerSend s;
+            s.target = t + 1;
+            song.mixer[(std::size_t) t].sends.push_back (s);
+        }
+    }
+    ChannelDef ch;
+    ch.name = "Saw";
+    ch.instrument = InstrumentKind::synth;
+    ch.synth = presetAt (3);
+    ch.mixerTrack = 1;
+    song.channels.push_back (ch);
+    auto& p = song.patterns.emplace_back();
+    for (int e = 0; e < 16; ++e)
+        p.notes.push_back (makeNote (0, e * 1.0, 0.9, 48 + (e * 7) % 12, 0.8f));
+    for (int b = 0; b < bars; b += 4)
+    {
+        Clip clip;
+        clip.pattern = 0;
+        clip.start = (std::int64_t) b * 4 * ppq;
+        clip.length = p.effectiveLength (song.meter());
+        song.playlist.push_back (clip);
+    }
+    song.mode = PlayMode::song;
+    return song;
+}
+
+// 24 audio clips of `seconds` each, on 12 inserts, playing together. The takes go into `samples` under
+// `folder` + "/take<N>.wav" (perfbench: an in-memory folder; --perfgen writes the files there).
+inline Song stream (int seconds, Samples& samples, const std::string& folder = "/stream")
+{
+    Song song;
+    song.bpm = 120.0;
+    song.mixer = Song::defaultMixer (12);
+    constexpr int clips = 24;
+    for (int c = 0; c < clips; ++c)
+    {
+        const auto path = folder + "/take" + std::to_string (c) + ".wav";
+        samples[path] = makeTake (seconds, 55.0 * (1 + c % 7), 1234567u + (std::uint32_t) c * 7919u);
+        ChannelDef ch;
+        ch.name = "Take " + std::to_string (c + 1);
+        ch.instrument = InstrumentKind::audioClip;
+        ch.samplePath = path;
+        ch.mixerTrack = 1 + c % 12;
+        ch.volume = 0.4f;
+        song.channels.push_back (ch);
+        Clip clip;
+        clip.kind = ClipKind::audio;
+        clip.channel = c;
+        clip.track = c;
+        clip.start = 0;
+        clip.length = (std::int64_t) (seconds * song.bpm / 60.0 * ppq);
+        song.playlist.push_back (clip);
+    }
+    for (int t = 1; t <= 12; ++t)
+        song.mixer[(std::size_t) t].effects.push_back (makeEffectSlot (t % 2 == 0 ? EffectKind::parametricEq : EffectKind::compressor));
+    song.mode = PlayMode::song;
+    return song;
+}
+
+// a point every `stepBeats` over `beats`, a slow wave between lo and hi with bent segments
+inline std::vector<AutomationPoint> wavePoints (double beats, double stepBeats, float lo, float hi, int seed)
+{
+    std::vector<AutomationPoint> points;
+    for (double b = 0.0; b <= beats + 1e-9; b += stepBeats)
+    {
+        AutomationPoint p;
+        p.tick = (std::int64_t) std::llround (b * ppq);
+        const auto x = std::sin (b * 0.7 + seed * 0.37) * 0.5 + 0.5;
+        p.value = lo + (hi - lo) * (float) x;
+        p.tension = (seed + (int) (b * 4.0)) % 3 == 0 ? 0.4f : 0.0f;
+        points.push_back (p);
+    }
+    return points;
+}
+
+inline int addAutomation (Song& song, AutomationTarget target, std::string name, std::vector<AutomationPoint> points)
+{
+    Automation a;
+    a.name = std::move (name);
+    a.target = target;
+    a.points = std::move (points);
+    song.automations.push_back (std::move (a));
+    return (int) song.automations.size() - 1;
+}
+
+inline void addAutomationClip (Song& song, int automation, int track, std::int64_t start, std::int64_t length)
+{
+    Clip clip;
+    clip.kind = ClipKind::automation;
+    clip.automation = automation;
+    clip.pattern = 0;
+    clip.track = track;
+    clip.start = start;
+    clip.length = length;
+    song.playlist.push_back (clip);
+}
+
+// 200 channels: 100 synths, 20 drums (kick / snare / hat / clap), 40 samplers (8 one-shots), 40 audio clips (8 s loops);
+// inserts 1..100 (two channels each), each with a strip, a dynamics unit and every 4th an echo / modulation, sending
+// to buses 101..120 (glue, a reverb at 25 % mix, a limiter) which go to the Master (EQ + limiter). 64 bars at 140 BPM:
+// each pattern channel plays 12 of the 16 four-bar slots (1,920 clips), each audio channel 2 clips (80): 2,000 clips;
+// 200 automation clips of 8 bars (insert volumes, effect parameters, channel pans), a point every beat.
+inline Song big200 (Samples& samples, const std::string& folder = "/big200")
+{
+    Song song;
+    song.bpm = 140.0;
+    song.mixer = Song::defaultMixer (120);
+    const EffectKind strips[] = { EffectKind::ridgeStrip, EffectKind::facetEq, EffectKind::kilnChannel, EffectKind::shellChannel,
+                                  EffectKind::fretChannel };
+    const EffectKind dynamics[] = { EffectKind::crestCompressor, EffectKind::glowLeveler, EffectKind::ember, EffectKind::aether,
+                                    EffectKind::strikeShaper, EffectKind::sentryGate, EffectKind::hushDeEsser };
+    const EffectKind motion[] = { EffectKind::echoform, EffectKind::orbit, EffectKind::spiralEcho, EffectKind::latticeMod,
+                                  EffectKind::geminiDoubler };
+    const EffectKind glue[] = { EffectKind::prismMultiband, EffectKind::anvilBus, EffectKind::crestCompressor };
+    const EffectKind spaces[] = { EffectKind::foilPlate, EffectKind::atrium, EffectKind::nebula, EffectKind::halo, EffectKind::epochVerb,
+                                  EffectKind::horizon };
+    for (int t = 1; t <= 100; ++t)
+    {
+        auto& m = song.mixer[(std::size_t) t];
+        m.effects.push_back (makeEffectSlot (strips[(std::size_t) (t % 5)]));
+        m.effects.push_back (makeEffectSlot (dynamics[(std::size_t) (t % 7)]));
+        if (t % 4 == 0)
+        {
+            auto slot = makeEffectSlot (motion[(std::size_t) ((t / 4) % 5)]);
+            slot.mix = 0.3f;
+            m.effects.push_back (slot);
+        }
+        m.toMaster = false;
+        m.sends.clear();
+        MixerSend s;
+        s.target = 101 + (t - 1) % 20;
+        m.sends.push_back (s);
+    }
+    for (int t = 101; t <= 120; ++t)
+    {
+        auto& m = song.mixer[(std::size_t) t];
+        m.effects.push_back (makeEffectSlot (glue[(std::size_t) (t % 3)]));
+        auto space = makeEffectSlot (spaces[(std::size_t) (t % 6)]);
+        space.mix = 0.25f;
+        m.effects.push_back (space);
+        m.effects.push_back (makeEffectSlot (EffectKind::apexLimiter));
+    }
+    song.mixer[0].effects.push_back (makeEffectSlot (EffectKind::facetEq));
+    song.mixer[0].effects.push_back (makeEffectSlot (EffectKind::apexLimiter));
+
+    constexpr int bars = 64;
+    const int roots[4] = { 45, 41, 48, 43 };
+    const InstrumentKind drums[] = { InstrumentKind::kick, InstrumentKind::snare, InstrumentKind::hat, InstrumentKind::clap };
+    for (int k = 0; k < 8; ++k)
+        samples[folder + "/hit" + std::to_string (k) + ".wav"] = makeHit (60.0 + 35.0 * k, 99991u + (std::uint32_t) k * 31u);
+    for (int c = 0; c < 200; ++c)
+    {
+        ChannelDef ch;
+        ch.mixerTrack = 1 + c / 2;
+        ch.volume = 0.25f;
+        ch.pan = (float) ((c % 9) - 4) / 8.0f;
+        Pattern p;
+        if (c < 100)
+        {
+            ch.name = "Synth " + std::to_string (c + 1);
+            ch.instrument = InstrumentKind::synth;
+            ch.synth = presetAt ((std::size_t) c * 7);
+            for (int bar = 0; bar < 4; ++bar)
+            {
+                const auto root = roots[bar] + 12 * (c % 3);
+                if (c % 3 == 0)
+                    for (int k : { 0, 3, 7 })
+                        p.notes.push_back (makeNote (c, bar * 4, 3.8, root + k, 0.6f));
+                else
+                    for (int e = 0; e < 8; ++e)
+                        p.notes.push_back (makeNote (c, bar * 4 + e * 0.5, 0.35, root + 12 + (e * (c % 5 + 2)) % 12, 0.75f));
+            }
+        }
+        else if (c < 120)
+        {
+            ch.name = "Drum " + std::to_string (c - 99);
+            ch.instrument = drums[(std::size_t) (c % 4)];
+            for (int s = 0; s < 64; ++s)
+                if ((s * (c % 4 + 3) + c) % (c % 4 == 2 ? 2 : 5) == 0)
+                    p.notes.push_back (makeNote (c, s * 0.25, 0.2, 60, 0.6f + 0.1f * (float) (s % 4)));
+        }
+        else if (c < 160)
+        {
+            ch.name = "Sampler " + std::to_string (c - 119);
+            ch.instrument = InstrumentKind::sampler;
+            ch.samplePath = folder + "/hit" + std::to_string (c % 8) + ".wav";
+            for (int s = 0; s < 32; ++s)
+                if ((s + c) % 3 == 0)
+                    p.notes.push_back (makeNote (c, s * 0.5, 0.4, 48 + (s * 5 + c) % 24, 0.7f));
+        }
+        else
+        {
+            ch.name = "Loop " + std::to_string (c - 159);
+            ch.instrument = InstrumentKind::audioClip;
+            ch.samplePath = folder + "/loop" + std::to_string (c - 160) + ".wav";
+            samples[ch.samplePath] = makeTake (8.0, 41.0 * (1 + c % 9), 777u + (std::uint32_t) c * 101u, 0.15f);
+        }
+        song.channels.push_back (ch);
+        p.name = ch.name;
+        if (c < 160)
+        {
+            song.patterns.push_back (p);
+            const auto pattern = (int) song.patterns.size() - 1;
+            const auto length = song.patterns.back().effectiveLength (song.meter());
+            for (int slot = 0; slot < bars / 4; ++slot)
+            {
+                if ((slot + c) % 4 == 0) // (12 of 16 slots)
+                    continue;
+                Clip clip;
+                clip.pattern = pattern;
+                clip.track = c;
+                clip.start = (std::int64_t) slot * 4 * 4 * ppq;
+                clip.length = length;
+                song.playlist.push_back (clip);
+            }
+        }
+        else
+            for (int k = 0; k < 2; ++k)
+            {
+                Clip clip;
+                clip.kind = ClipKind::audio;
+                clip.channel = c;
+                clip.track = c;
+                clip.start = (std::int64_t) ((c % 4) * 8 + k * 32) * 4 * ppq;
+                clip.length = (std::int64_t) (8.0 * song.bpm / 60.0 * ppq);
+                song.playlist.push_back (clip);
+            }
+    }
+    // 200 automation clips of 8 bars on tracks 200..249
+    const auto clipTicks = (std::int64_t) 8 * 4 * ppq;
+    for (int a = 0; a < 200; ++a)
+    {
+        AutomationTarget target;
+        std::string name;
+        if (a < 100)
+        {
+            target.kind = AutomationTargetKind::mixerVolume;
+            target.index = 1 + a;
+            name = "Insert " + std::to_string (1 + a) + " volume";
+        }
+        else if (a < 160)
+        {
+            target.kind = AutomationTargetKind::effectParam;
+            target.index = 1 + (a - 100);
+            target.slot = 0;
+            target.param = a % 4;
+            name = "Insert " + std::to_string (target.index) + " slot 1 param " + std::to_string (target.param);
+        }
+        else
+        {
+            target.kind = AutomationTargetKind::channelPan;
+            target.index = (a - 160) * 5;
+            name = "Channel " + std::to_string (target.index + 1) + " pan";
+        }
+        const auto index = addAutomation (song, target, name, wavePoints (32.0, 1.0, 0.35f, 0.8f, a));
+        addAutomationClip (song, index, 200 + a % 50, (std::int64_t) ((a * 3) % (bars - 8)) * 4 * ppq, clipTicks);
+    }
+    song.mode = PlayMode::song;
+    return song;
+}
+
+// 32 synths on 16 inserts (EQ, compressor, delay), 400 automation clips of 16 bars with a point every 16th note over
+// insert volumes and pans, the sends, effect parameters and mixes, channel volumes and pans, and one tempo clip
+inline Song automation()
+{
+    Song song;
+    song.bpm = 124.0;
+    song.mixer = Song::defaultMixer (16);
+    for (int t = 1; t <= 16; ++t)
+    {
+        auto& m = song.mixer[(std::size_t) t];
+        m.effects.push_back (makeEffectSlot (t % 2 == 0 ? EffectKind::facetEq : EffectKind::parametricEq));
+        m.effects.push_back (makeEffectSlot (t % 3 == 0 ? EffectKind::crestCompressor : EffectKind::compressor));
+        auto d = makeEffectSlot (EffectKind::delay);
+        d.mix = 0.3f;
+        m.effects.push_back (d);
+        if (t > 1)
+        {
+            MixerSend s;
+            s.target = 1;
+            s.level = 0.3f;
+            m.sends.push_back (s);
+        }
+    }
+    constexpr int bars = 32;
+    for (int c = 0; c < 32; ++c)
+    {
+        ChannelDef ch;
+        ch.name = "Synth " + std::to_string (c + 1);
+        ch.instrument = InstrumentKind::synth;
+        ch.synth = presetAt ((std::size_t) c * 3);
+        ch.volume = 0.35f;
+        ch.mixerTrack = 1 + c / 2;
+        song.channels.push_back (ch);
+        auto& p = song.patterns.emplace_back();
+        p.name = ch.name;
+        for (int e = 0; e < 16; ++e)
+            p.notes.push_back (makeNote (c, e * 1.0, 0.8, 40 + (c * 5 + e * 7) % 36, 0.7f));
+        for (int b = 0; b < bars; b += 4)
+        {
+            Clip clip;
+            clip.pattern = c;
+            clip.track = c;
+            clip.start = (std::int64_t) b * 4 * ppq;
+            clip.length = p.effectiveLength (song.meter());
+            song.playlist.push_back (clip);
+        }
+    }
+    const auto clipTicks = (std::int64_t) 16 * 4 * ppq;
+    for (int a = 0; a < 400; ++a)
+    {
+        AutomationTarget target;
+        const auto track = 1 + a % 16;
+        switch (a % 8)
+        {
+            case 0: target = { AutomationTargetKind::mixerVolume, track, 0, 0 }; break;
+            case 1: target = { AutomationTargetKind::mixerPan, track, 0, 0 }; break;
+            case 2: target = { AutomationTargetKind::effectParam, track, 0, (a / 8) % 6 }; break;
+            case 3: target = { AutomationTargetKind::effectParam, track, 1, (a / 8) % 4 }; break;
+            case 4: target = { AutomationTargetKind::effectMix, track, 2, 0 }; break;
+            case 5: target = { AutomationTargetKind::mixerSend, track == 1 ? 2 : track, 1, 0 }; break;
+            case 6: target = { AutomationTargetKind::channelVolume, a % 32, 0, 0 }; break;
+            default: target = { AutomationTargetKind::channelPan, a % 32, 0, 0 }; break;
+        }
+        const auto index = addAutomation (song, target, "Automation " + std::to_string (a + 1), wavePoints (64.0, 0.25, 0.3f, 0.75f, a));
+        addAutomationClip (song, index, 40 + a % 100, (std::int64_t) (((a / 100) * 16) % bars) * 4 * ppq, clipTicks);
+    }
+    {
+        AutomationTarget tempo;
+        tempo.kind = AutomationTargetKind::tempo;
+        const auto lo = valueFromTempo (122.0), hi = valueFromTempo (126.0);
+        const auto index = addAutomation (song, tempo, "Tempo", wavePoints ((double) bars * 4.0, 1.0, lo, hi, 7));
+        addAutomationClip (song, index, 39, 0, (std::int64_t) bars * 4 * ppq);
+    }
+    song.mode = PlayMode::song;
+    return song;
+}
+
+// a scenario by name (`folder` for the audio files' paths); nullopt-like empty song name check is up to the caller
+inline bool make (const std::string& name, Song& song, Samples& samples, const std::string& folder = {})
+{
+    if (name == "synth100")
+        song = synth100 (16);
+    else if (name == "inserts50")
+        song = inserts50 (16);
+    else if (name == "stream")
+        song = stream (60, samples, folder.empty() ? "/stream" : folder);
+    else if (name == "big200")
+        song = big200 (samples, folder.empty() ? "/big200" : folder);
+    else if (name == "automation")
+        song = automation();
+    else
+        return false;
+    return true;
+}
+} // namespace lynx::perfprojects

+ 2 - 0
src/core/RenderAhead.cpp

@@ -1032,6 +1032,8 @@ void RenderAhead::account (double wallNs, double cpuNs, int samples, bool playin
                 offHold = keep ? decidedSeconds : std::min (600.0, offHold * 2.0);
                 decidedState = state != nullptr ? state->serial : 0;
                 (keep ? counters.keptOn : counters.keptOff).fetch_add (1, std::memory_order_relaxed);
+                if (keep && ! (lessCpu && overRateOn <= overRateOff))
+                    counters.keptForOverruns.fetch_add (1, std::memory_order_relaxed);
                 if (! keep)
                     drain.store (true, std::memory_order_release);
             }

+ 2 - 1
src/core/RenderAhead.h

@@ -136,7 +136,8 @@ struct Stats
 {
     std::atomic<std::uint64_t> blocks { 0 }, fromRing { 0 }, waited { 0 }, inline_ { 0 }, flushes { 0 }, drains { 0 },
         engagements { 0 }, partitionChanges { 0 }, promoted { 0 }, splitMismatches { 0 }, statesSwapped { 0 }, backoffs { 0 },
-        probes { 0 }, keptOn { 0 }, keptOff { 0 };
+        probes { 0 }, keptOn { 0 }, keptOff { 0 },
+        keptForOverruns { 0 }; // (perfgate190id: kept on by favourFewerOverruns alone, not by a CPU win)
     // the last probe: the rack's CPU (% of a core) and overruns per minute, render-ahead off and on
     std::atomic<float> probeCpuOff { 0.0f }, probeCpuOn { 0.0f }, probeOverOff { 0.0f }, probeOverOn { 0.0f };
     std::atomic<int> aheadChannels { 0 }, aheadTracks { 0 }, boundary { 0 }, window { 0 };

+ 5 - 0
src/engine/AudioEngine.cpp

@@ -6061,6 +6061,11 @@ juce::String AudioEngine::describeRealtime (bool withUnits) const
              << ", started " << n (r.engagements) << ", states taken at once " << n (r.statesSwapped) << ", channels joined live " << n (r.promoted)
              << ", partition changes " << n (r.partitionChanges) << ", boundary mismatches " << n (r.splitMismatches) << "; ahead "
              << r.aheadChannels.load() << " channels / " << r.aheadTracks.load() << " inserts, boundary " << r.boundary.load() << "\n";
+        // (perfgate190id) the engagement rule's probes: how often, what they kept, and the last one's measurements
+        text << "  render ahead probes " << n (r.probes) << ": kept on " << n (r.keptOn) << " (for fewer overruns " << n (r.keptForOverruns)
+             << "), kept off " << n (r.keptOff) << "; last probe CPU " << juce::String (r.probeCpuOff.load(), 1) << "% off / "
+             << juce::String (r.probeCpuOn.load(), 1) << "% on, overruns " << juce::String (r.probeOverOff.load(), 0) << " / "
+             << juce::String (r.probeOverOn.load(), 0) << " per minute\n";
     }
     if (withUnits && heaviestUnits.empty())
         text << "  heaviest: not measured yet\n";

+ 108 - 0
tests/PerfGate190idTests.inc

@@ -0,0 +1,108 @@
+// Round perfgate190id (community slice B12): the big-project performance gate's synthetic projects
+// (core/PerfProjects.h). The gate compares measurements across builds, so the projects must be what they promise and
+// the same bit for bit every time they are made; and they must play (a project that renders silence measures nothing).
+
+namespace pg190id
+{
+using namespace lynx;
+
+int clipsOf (const Song& song, ClipKind kind)
+{
+    return (int) std::count_if (song.playlist.begin(), song.playlist.end(), [kind] (const Clip& c) { return c.kind == kind; });
+}
+
+// `seconds` of the song from its start, as tools/perfbench renders it (the export song, live quality, one thread)
+std::vector<float> render (const Song& song, const perfprojects::Samples& samples, double seconds, int block)
+{
+    std::int64_t ticks = 0;
+    const auto exportSong = makeExportSong (song, true, 0, ticks);
+    auto provider = [&samples] (const std::string& p) {
+        const auto it = samples.find (p);
+        return it != samples.end() ? it->second : std::shared_ptr<const SampleData> {};
+    };
+    auto state = RackState::build (exportSong, nullptr, 44100.0, provider);
+    RackRenderer renderer;
+    renderer.prepare (44100.0, 2048);
+    LiveEventQueue live, midiLive;
+    const auto total = (int) (seconds * 44100.0) / block * block;
+    std::vector<float> out ((std::size_t) total * 2);
+    std::vector<float> l ((std::size_t) block), r ((std::size_t) block);
+    const auto tps = ticksPerSample (exportSong.bpm, 44100.0);
+    for (int pos = 0; pos < total; pos += block)
+    {
+        renderer.process (state.get(), true, pos * tps, block, l.data(), r.data(), &live, nullptr, &midiLive);
+        for (int i = 0; i < block; ++i)
+            out[(std::size_t) (pos + i) * 2] = l[(std::size_t) i], out[(std::size_t) (pos + i) * 2 + 1] = r[(std::size_t) i];
+    }
+    return out;
+}
+} // namespace pg190id
+
+TEST (perfgate_projects_have_the_promised_size)
+{
+    using namespace lynx;
+    perfprojects::Samples samples;
+    const auto big = perfprojects::big200 (samples);
+    CHECK (big.channels.size() == 200);
+    CHECK (big.mixer.size() == 121); // Master + 120 inserts
+    CHECK (pg190id::clipsOf (big, ClipKind::pattern) + pg190id::clipsOf (big, ClipKind::audio) == 2000);
+    CHECK (pg190id::clipsOf (big, ClipKind::automation) == 200);
+    CHECK (big.automations.size() == 200);
+    int lynxEffects = 0;
+    for (const auto& m : big.mixer)
+        lynxEffects += (int) m.effects.size();
+    CHECK (lynxEffects == 100 * 2 + 25 + 20 * 3 + 2);
+    CHECK (samples.size() == 8 + 40); // the samplers' one-shots and the audio channels' loops
+    const auto automation = perfprojects::automation();
+    CHECK (automation.automations.size() == 401);
+    CHECK (pg190id::clipsOf (automation, ClipKind::automation) == 401);
+    CHECK (automation.automations[0].points.size() == 257); // a point every 16th over 16 bars
+    perfprojects::Samples streamSamples;
+    const auto stream = perfprojects::stream (60, streamSamples);
+    CHECK (stream.channels.size() == 24 && streamSamples.size() == 24);
+    CHECK (streamSamples.begin()->second->frames() == 60 * 44100);
+    for (const auto& name : perfprojects::names())
+    {
+        Song song;
+        perfprojects::Samples s;
+        CHECK (perfprojects::make (name, song, s));
+    }
+    Song none;
+    perfprojects::Samples s;
+    CHECK (! perfprojects::make ("nothing", none, s));
+}
+
+TEST (perfgate_projects_are_the_same_every_time_and_play)
+{
+    using namespace lynx;
+    for (const auto* name : { "big200", "automation" })
+    {
+        Song a, b;
+        perfprojects::Samples sa, sb;
+        perfprojects::make (name, a, sa);
+        perfprojects::make (name, b, sb);
+        CHECK (a.automations == b.automations);
+        CHECK (a.playlist.size() == b.playlist.size());
+        bool sameClips = true;
+        for (std::size_t i = 0; i < a.playlist.size() && i < b.playlist.size(); ++i)
+            sameClips = sameClips && a.playlist[i].start == b.playlist[i].start && a.playlist[i].length == b.playlist[i].length
+                        && a.playlist[i].track == b.playlist[i].track && a.playlist[i].kind == b.playlist[i].kind;
+        CHECK (sameClips);
+        bool sameMixer = a.mixer.size() == b.mixer.size();
+        for (std::size_t t = 0; sameMixer && t < a.mixer.size(); ++t)
+            sameMixer = a.mixer[t].effects == b.mixer[t].effects;
+        CHECK (sameMixer);
+        bool sameAudio = sa.size() == sb.size();
+        for (auto i = sa.begin(), j = sb.begin(); sameAudio && i != sa.end(); ++i, ++j)
+            sameAudio = i->first == j->first && i->second->left == j->second->left && i->second->right == j->second->right;
+        CHECK (sameAudio);
+        const auto x = pg190id::render (a, sa, 0.5, 256), y = pg190id::render (b, sb, 0.5, 256);
+        CHECK (x == y);
+        float peak = 0.0f;
+        bool finite = true;
+        for (const auto v : x)
+            peak = std::max (peak, std::abs (v)), finite = finite && std::isfinite (v);
+        CHECK (finite);
+        CHECK (peak > 1.0e-3f);
+    }
+}

+ 2 - 0
tests/tests.cpp

@@ -143,6 +143,7 @@
 #include "core/DelphiMath.h"
 #include "core/LiveEventQueue.h"
 #include "core/RackRenderer.h"
+#include "core/PerfProjects.h"
 #include "core/PinOnTop.h"
 #include "core/MetronomeVoice.h"
 #include "engine/Transport.h"
@@ -17803,3 +17804,4 @@ TEST (fl_low_lifter_matches_fl_engine)
 #include "U190heLinkTests.inc" // round 190he (issue #152 item 2: linkable LYNX instruments, knobs that follow links)
 #include "PluginDrop190hfTests.inc" // issue #152 point 6: plugins dropped on the tracks (FL and Live layouts)
 #include "Rollup028Tests.inc" // round 190fv: semantic interactions of the 0.1.28 rollup
+#include "PerfGate190idTests.inc" // round perfgate190id: the performance gate's synthetic projects (community slice B12)

+ 98 - 165
tools/perfbench.cpp

@@ -17,7 +17,13 @@
 //   idle            the synth100 project with the transport stopped and nothing playing (the cost of an idle project)
 //   afterstop       the synth100 project played for --warmup seconds (not measured), then stopped (round 190gp: the
 //                   seconds after Stop, while the effects' tails die away and smart disable takes them out)
+//   big200          200 channels, 120 inserts with LYNX's own effects, 2,000 clips, 200 automation clips (round
+//                   perfgate190id; this and the next: core/PerfProjects.h, the big-project performance gate)
+//   automation      32 synths, 16 inserts, 400 dense automation clips and a tempo clip
+//   calibrate       a fixed piece of work no LYNX change touches: the machine's speed (the gate divides by it)
 //   flp:<path>      an FL Studio project, whole song (FL's own data from FL_ROOT, as renderwav)
+// --gate: one machine-readable "GATE key=value ..." line at the end (CPU, instructions, import / build / rebuild time,
+// peak memory, hash; dropouts with --paced) for scripts/perf_gate.py.
 // --threads N: N worker threads besides the calling one (the app's WorkerPool); the CPU time is then the process'
 // (every thread, spinning included) and the instructions are the calling thread's only.
 // Round 190gq (render-ahead, core/RenderAhead.h):
@@ -49,6 +55,9 @@
 #include <vector>
 
 #include <time.h>
+#if ! defined(_WIN32)
+ #include <sys/resource.h>
+#endif
 #if defined(__linux__)
  #include <linux/perf_event.h>
  #include <sys/ioctl.h>
@@ -65,6 +74,7 @@
 #include "core/Meters.h"
 #include "core/RackRenderer.h"
 #include "core/RenderAhead.h"
+#include "core/PerfProjects.h"
 #include "core/ShowcaseSong.h"
 #include "core/SynthPresets.h"
 #include "core/WorkerPool.h"
@@ -166,169 +176,61 @@ Song importProject (const std::string& path)
     return importFlp (flp::parseProject (bytes), options);
 }
 
-SynthSettings presetAt (std::size_t k)
+// the process' peak resident memory in MB (-1 when unknown)
+double peakRssMb()
 {
-    static const auto presets = synthPresets();
-    return presets.empty() ? SynthSettings {} : presets[k % presets.size()].second;
-}
-
-Note makeNote (int channel, double beat, double beats, int key, float velocity)
-{
-    Note n;
-    n.channel = channel;
-    n.start = (std::int64_t) (beat * ppq);
-    n.length = (std::int64_t) (beats * ppq);
-    n.key = key;
-    n.velocity = velocity;
-    return n;
+#if ! defined(_WIN32)
+    rusage usage {};
+    if (getrusage (RUSAGE_SELF, &usage) == 0)
+ #if defined(__APPLE__)
+        return (double) usage.ru_maxrss / 1048576.0; // (bytes on macOS)
+ #else
+        return (double) usage.ru_maxrss / 1024.0; // (kilobytes on Linux)
+ #endif
+#endif
+    return -1.0;
 }
 
-// 100 synth channels, two per insert, 50 inserts with 3 effects each; every channel plays 4-bar loops (a held chord
-// on even channels, an eighth-note line on odd ones) for the whole song
-Song makeSynth100 (int bars)
+// perfgate190id: a fixed piece of DSP-like work (biquads, a soft clip, an interpolated table read over 256 KB) that no
+// LYNX change touches. The gate divides its CPU times by this one's, so a faster or slower machine (CI runners differ)
+// moves both alike; median of 7 runs, ms of thread CPU.
+double calibrationMs()
 {
-    Song song;
-    song.bpm = 128.0;
-    song.mixer = Song::defaultMixer (50);
-    constexpr int channels = 100;
-    const EffectKind chains[][3] = {
-        { EffectKind::parametricEq, EffectKind::compressor, EffectKind::reverb },
-        { EffectKind::facetEq, EffectKind::crestCompressor, EffectKind::delay },
-        { EffectKind::eq, EffectKind::chorus, EffectKind::apexLimiter },
-        { EffectKind::filter, EffectKind::ember, EffectKind::atrium },
-        { EffectKind::ridgeStrip, EffectKind::echoform, EffectKind::limiter },
-    };
-    for (int t = 1; t <= 50; ++t)
-        for (const auto kind : chains[(std::size_t) (t % 5)])
-            song.mixer[(std::size_t) t].effects.push_back (makeEffectSlot (kind));
-    const int roots[4] = { 45, 41, 48, 43 };
-    for (int c = 0; c < channels; ++c)
+    std::vector<float> buffer ((std::size_t) 1 << 16), table (4096);
+    for (std::size_t i = 0; i < table.size(); ++i)
+        table[i] = (float) std::sin (6.283185307179586 * (double) i / (double) table.size());
+    std::uint32_t seed = 12345u;
+    for (auto& x : buffer)
     {
-        ChannelDef ch;
-        ch.name = "Synth " + std::to_string (c + 1);
-        ch.instrument = InstrumentKind::synth;
-        ch.synth = presetAt ((std::size_t) c);
-        ch.volume = 0.3f;
-        ch.mixerTrack = 1 + c / 2;
-        song.channels.push_back (ch);
-        auto& p = song.patterns.emplace_back();
-        p.name = ch.name;
-        for (int bar = 0; bar < 4; ++bar)
-        {
-            const auto root = roots[bar] + 12 * (c % 3);
-            if (c % 2 == 0)
-                for (int k : { 0, 4, 7 })
-                    p.notes.push_back (makeNote (c, bar * 4, 3.9, root + k, 0.7f));
-            else
-                for (int e = 0; e < 8; ++e)
-                    p.notes.push_back (makeNote (c, bar * 4 + e * 0.5, 0.4, root + 12 + (e * 5) % 12, 0.8f));
-        }
-        for (int b = 0; b < bars; b += 4)
-        {
-            Clip clip;
-            clip.pattern = c;
-            clip.track = c % 100;
-            clip.start = (std::int64_t) b * 4 * ppq;
-            clip.length = p.effectiveLength (song.meter());
-            song.playlist.push_back (clip);
-        }
+        seed = seed * 1664525u + 1013904223u;
+        x = (float) ((int) (seed >> 9) - (1 << 22)) / (float) (1 << 22);
     }
-    song.mode = PlayMode::song;
-    return song;
-}
-
-// one synth into insert 1; inserts 1..50 in a chain of sends (n → n+1), 4 effects each, the last to the Master
-Song makeInserts50 (int bars)
-{
-    Song song;
-    song.bpm = 128.0;
-    song.mixer = Song::defaultMixer (50);
-    const EffectKind kinds[] = { EffectKind::parametricEq, EffectKind::compressor, EffectKind::distortion, EffectKind::chorus,
-                                 EffectKind::facetEq, EffectKind::ember, EffectKind::delay, EffectKind::utility };
-    for (int t = 1; t <= 50; ++t)
+    std::vector<double> runs;
+    volatile float sink = 0.0f;
+    for (int run = 0; run < 7; ++run)
     {
-        for (int k = 0; k < 4; ++k)
-        {
-            auto slot = makeEffectSlot (kinds[(std::size_t) ((t + k) % 8)]);
-            slot.mix = 0.5f;
-            song.mixer[(std::size_t) t].effects.push_back (slot);
-        }
-        if (t < 50)
-        {
-            song.mixer[(std::size_t) t].sends.clear();
-            song.mixer[(std::size_t) t].toMaster = false;
-            MixerSend s;
-            s.target = t + 1;
-            song.mixer[(std::size_t) t].sends.push_back (s);
-        }
-    }
-    ChannelDef ch;
-    ch.name = "Saw";
-    ch.instrument = InstrumentKind::synth;
-    ch.synth = presetAt (3);
-    ch.mixerTrack = 1;
-    song.channels.push_back (ch);
-    auto& p = song.patterns.emplace_back();
-    for (int e = 0; e < 16; ++e)
-        p.notes.push_back (makeNote (0, e * 1.0, 0.9, 48 + (e * 7) % 12, 0.8f));
-    for (int b = 0; b < bars; b += 4)
-    {
-        Clip clip;
-        clip.pattern = 0;
-        clip.start = (std::int64_t) b * 4 * ppq;
-        clip.length = p.effectiveLength (song.meter());
-        song.playlist.push_back (clip);
-    }
-    song.mode = PlayMode::song;
-    return song;
-}
-
-// 24 audio clips of 60 s each, on 12 inserts, playing together
-Song makeStream (int seconds, std::map<std::string, std::shared_ptr<const SampleData>>& samples)
-{
-    Song song;
-    song.bpm = 120.0;
-    song.mixer = Song::defaultMixer (12);
-    constexpr int clips = 24;
-    for (int c = 0; c < clips; ++c)
-    {
-        auto data = std::make_shared<SampleData>();
-        const auto frames = (std::size_t) (44100.0 * seconds);
-        data->left.resize (frames);
-        data->right.resize (frames);
-        std::uint32_t seed = 1234567u + (std::uint32_t) c * 7919u;
-        double phase = 0.0;
-        const auto hz = 55.0 * (1 + c % 7);
-        for (std::size_t i = 0; i < frames; ++i)
-        {
-            seed = seed * 1664525u + 1013904223u;
-            const auto noise = (float) ((int) (seed >> 9) - (1 << 22)) / (float) (1 << 22);
-            phase += hz / 44100.0;
-            const auto tone = (float) std::sin (6.283185307179586 * phase);
-            data->left[i] = 0.2f * tone + 0.02f * noise;
-            data->right[i] = 0.2f * tone - 0.02f * noise;
-        }
-        const auto path = "/stream/take" + std::to_string (c) + ".wav";
-        samples[path] = data;
-        ChannelDef ch;
-        ch.name = "Take " + std::to_string (c + 1);
-        ch.instrument = InstrumentKind::audioClip;
-        ch.samplePath = path;
-        ch.mixerTrack = 1 + c % 12;
-        ch.volume = 0.4f;
-        song.channels.push_back (ch);
-        Clip clip;
-        clip.kind = ClipKind::audio;
-        clip.channel = c;
-        clip.track = c;
-        clip.start = 0;
-        clip.length = (std::int64_t) (seconds * song.bpm / 60.0 * ppq);
-        song.playlist.push_back (clip);
+        const auto t0 = cpuMs (CLOCK_THREAD_CPUTIME_ID);
+        float z1 = 0.0f, z2 = 0.0f, y1 = 0.0f, y2 = 0.0f, phase = 0.0f;
+        for (int pass = 0; pass < 48; ++pass)
+            for (auto& x : buffer)
+            {
+                const auto in = x;
+                const auto y = 0.2f * in + 0.4f * z1 + 0.2f * z2 + 0.6f * y1 - 0.25f * y2;
+                z2 = z1, z1 = in, y2 = y1, y1 = y;
+                phase += 0.013f;
+                phase -= (float) (int) phase;
+                const auto pos = phase * 4095.0f;
+                const auto k = (int) pos;
+                const auto frac = pos - (float) k;
+                const auto t = table[(std::size_t) k] + frac * (table[(std::size_t) k + 1] - table[(std::size_t) k]);
+                const auto v = y * 0.9f + 0.1f * t;
+                x = v / (1.0f + std::fabs (v)) + 1e-7f * in;
+            }
+        runs.push_back (cpuMs (CLOCK_THREAD_CPUTIME_ID) - t0);
+        sink = sink + buffer[(std::size_t) run];
     }
-    for (int t = 1; t <= 12; ++t)
-        song.mixer[(std::size_t) t].effects.push_back (makeEffectSlot (t % 2 == 0 ? EffectKind::parametricEq : EffectKind::compressor));
-    song.mode = PlayMode::song;
-    return song;
+    std::sort (runs.begin(), runs.end());
+    return runs[runs.size() / 2];
 }
 
 std::uint64_t hashSamples (const std::vector<float>& l, const std::vector<float>& r)
@@ -352,18 +254,25 @@ int main (int argc, char** argv)
 {
     if (argc < 2)
     {
-        std::fprintf (stderr, "usage: perfbench <demo|hiphop|pop|synth100|inserts50|stream|idle|flp:path> [--block N] [--threads N] "
+        std::fprintf (stderr, "usage: perfbench <demo|hiphop|pop|synth100|inserts50|stream|big200|automation|idle|calibrate|flp:path|als:path> [--block N] [--threads N] "
                               "[--seconds S] [--reps R] [--offline] [--nometers] [--raw path] [--stopped]\n");
         return 2;
     }
     applySwitches();
     const std::string scenario = argv[1];
+    if (scenario == "calibrate") // (perfgate190id: the machine's speed, see calibrationMs)
+    {
+        const auto ms = calibrationMs();
+        std::printf ("RESULT calibrate: %.2f ms\nGATE scenario=calibrate calib_ms=%.3f\n", ms, ms);
+        return 0;
+    }
     int blockSize = 256, threads = 0, reps = 5;
     double seconds = 0.0, warmup = 0.0;
     bool offline = false, meters = true, stopped = scenario == "idle" || scenario == "afterstop", units = false, aheadMode = false, paced = false, appTransport = false,
          aheadAlways = false;
     std::vector<int> liveChannels;
     int loopBars = 0;
+    bool gate = false;
     const bool playWarmup = scenario == "afterstop"; // (the warmup plays, the measured part is stopped)
     const char* raw = nullptr;
     for (int i = 2; i < argc; ++i)
@@ -402,23 +311,25 @@ int main (int argc, char** argv)
             appTransport = true;
         else if (a == "--loop")
             loopBars = std::max (0, std::atoi (next()));
+        else if (a == "--gate") // (perfgate190id: one machine-readable GATE line at the end, scripts/perf_gate.py)
+            gate = true;
     }
 
     constexpr int sampleRate = 44100;
     std::map<std::string, std::shared_ptr<const SampleData>> cache;
     Song song;
+    const auto import0 = std::chrono::steady_clock::now();
     if (scenario == "demo")
         song = makeShowcaseSong();
     else if (scenario == "hiphop")
         song = demos::make (1);
     else if (scenario == "pop")
         song = demos::make (2);
-    else if (scenario == "synth100" || scenario == "idle" || scenario == "afterstop")
-        song = makeSynth100 (16);
-    else if (scenario == "inserts50")
-        song = makeInserts50 (16);
-    else if (scenario == "stream")
-        song = makeStream (60, cache);
+    else if (scenario == "idle" || scenario == "afterstop")
+        song = perfprojects::synth100 (16);
+    else if (perfprojects::make (scenario, song, cache)) // (the gate's synthetic projects, core/PerfProjects.h)
+    {
+    }
     else if (scenario.rfind ("als:", 0) == 0) // (round 190gq: a Live set, its arrangement on the Playlist)
     {
         const auto path = scenario.substr (4);
@@ -460,6 +371,7 @@ int main (int argc, char** argv)
         return 2;
     }
 
+    const auto importMs = std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - import0).count();
     std::int64_t songTicks = 0;
     song = makeExportSong (song, true, (std::int64_t) std::ceil (ticksPerSample (song.bpm, sampleRate) * sampleRate), songTicks);
     const auto tps = ticksPerSample (song.bpm, sampleRate);
@@ -488,13 +400,15 @@ int main (int argc, char** argv)
                  song.channels.size(), song.mixer.size(), (double) totalSamples / sampleRate, sampleRate, blockSize, threads,
                  offline ? "offline quality" : "live quality", meters ? "on" : "off", stopped ? ", stopped" : "");
 
-    std::vector<double> cpu, nsPerSample;
+    std::vector<double> cpu, nsPerSample, buildMs, droppedPerMin, overPerMin;
     std::vector<long long> instr;
     std::uint64_t firstHash = 0;
     bool sameHash = true;
     for (int rep = 0; rep < reps; ++rep)
     {
+        const auto build0 = std::chrono::steady_clock::now();
         auto state = RackState::build (song, nullptr, sampleRate, provider);
+        buildMs.push_back (std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - build0).count());
         const auto* statePtr = state.get();
         auto renderer = std::make_unique<RackRenderer>();
         if (pool != nullptr)
@@ -652,6 +566,8 @@ int main (int argc, char** argv)
         {
             std::sort (callbackMs.begin(), callbackMs.end());
             const auto audioSeconds = (double) totalSamples / sampleRate;
+            droppedPerMin.push_back (dropouts * 60.0 / audioSeconds);
+            overPerMin.push_back (over * 60.0 / audioSeconds);
             std::printf ("paced: %d dropouts (%.2f per minute), %d callbacks over their block (%.2f per minute), worst callback %.3f ms, p99 %.3f ms, "
                          "median %.3f ms (budget %.3f ms)\n", dropouts, dropouts * 60.0 / audioSeconds, over, over * 60.0 / audioSeconds, worstMs, callbackMs[std::min (callbackMs.size() - 1, (std::size_t) (0.99 * (double) callbackMs.size()))],
                          callbackMs[callbackMs.size() / 2], 1000.0 * blockSize / sampleRate);
@@ -660,12 +576,12 @@ int main (int argc, char** argv)
         {
             const auto& st = ahead->stats();
             std::printf ("ahead: blocks %llu, from ring %llu, waited %llu, inline %llu, flushes %llu, drains %llu, engagements %llu, ahead channels %d, "
-                         "ahead inserts %d, boundary %d, window %d samples, split mismatches %llu, backoffs %llu, probes %llu, kept on %llu, kept off %llu (probe cpu %.1f%% off / %.1f%% on, overruns %.0f / %.0f per minute)\n",
+                         "ahead inserts %d, boundary %d, window %d samples, split mismatches %llu, backoffs %llu, probes %llu, kept on %llu (for fewer overruns %llu), kept off %llu (probe cpu %.1f%% off / %.1f%% on, overruns %.0f / %.0f per minute)\n",
                          (unsigned long long) st.blocks.load(), (unsigned long long) st.fromRing.load(), (unsigned long long) st.waited.load(),
                          (unsigned long long) st.inline_.load(), (unsigned long long) st.flushes.load(), (unsigned long long) st.drains.load(),
                          (unsigned long long) st.engagements.load(), st.aheadChannels.load(), st.aheadTracks.load(), st.boundary.load(), st.window.load(),
                          (unsigned long long) st.splitMismatches.load(), (unsigned long long) st.backoffs.load(),
-                         (unsigned long long) st.probes.load(), (unsigned long long) st.keptOn.load(), (unsigned long long) st.keptOff.load(),
+                         (unsigned long long) st.probes.load(), (unsigned long long) st.keptOn.load(), (unsigned long long) st.keptForOverruns.load(), (unsigned long long) st.keptOff.load(),
                          (double) st.probeCpuOff.load(), (double) st.probeCpuOn.load(), (double) st.probeOverOff.load(), (double) st.probeOverOn.load());
         }
         counter.pause();
@@ -722,5 +638,22 @@ int main (int argc, char** argv)
                  "hash %016llx%s\n",
                  scenario.c_str(), blockSize, threads, median (cpu), 100.0 * median (cpu) / audioMs, median (nsPerSample),
                  (double) median (instr) / (double) totalSamples, (unsigned long long) firstHash, sameHash ? "" : " (HASH VARIES BETWEEN REPS)");
+    // rep 0's build decodes the samples (a project's load); the later ones are what an edit's new snapshot costs
+    const auto firstBuild = buildMs.front();
+    const auto rebuild = buildMs.size() > 1 ? median (std::vector<double> (buildMs.begin() + 1, buildMs.end())) : firstBuild;
+    std::printf ("project: import %.1f ms, first build %.1f ms, rebuild %.1f ms (median), peak memory %.0f MB; %zu channels, %zu inserts, "
+                 "%zu playlist clips, %zu automations\n",
+                 importMs, firstBuild, rebuild, peakRssMb(), song.channels.size(), song.mixer.size(), song.playlist.size(), song.automations.size());
+    if (gate)
+    {
+        std::printf ("GATE scenario=%s block=%d threads=%d seconds=%.2f cpu_pct=%.3f ns_per_sample=%.2f instr_per_sample=%.0f import_ms=%.2f "
+                     "build_ms=%.2f rebuild_ms=%.2f rss_mb=%.1f hash=%016llx hash_stable=%d",
+                     scenario.c_str(), blockSize, threads, audioMs / 1000.0, 100.0 * median (cpu) / audioMs, median (nsPerSample),
+                     median (instr) < 0 ? -1.0 : (double) median (instr) / (double) totalSamples, importMs, firstBuild, rebuild, peakRssMb(),
+                     (unsigned long long) firstHash, sameHash ? 1 : 0);
+        if (paced)
+            std::printf (" dropouts_per_min=%.2f overruns_per_min=%.2f", median (droppedPerMin), median (overPerMin));
+        std::printf ("\n");
+    }
     return 0;
 }