Files
bradleyshep fb0a458d4f LLM Benchmark: Sequential Upgrades Test (#4817)
# Description of Changes

AI app generation benchmark comparing SpacetimeDB vs PostgreSQL (Express
+ Socket.io + Drizzle ORM). Same AI model (Claude Sonnet 4.6), same
prompts, same chat app, two backends. Upgraded through 12 feature
levels, manually graded at each level, bugs fixed, all costs measured
via OpenTelemetry.

Results viewable at:
https://spacetimedb.com/llms-benchmark-sequential-upgrade

## Benchmark harness (`tools/llm-sequential-upgrade/`)

- `run.sh`: orchestrates headless Claude Code sessions for code
generation, sequential upgrades, and bug fixes. Tracks all API costs via
OTel. Supports `--upgrade`, `--fix`, `--composed-prompt`,
`--resume-session` modes.
- `grade.sh` / `grade-agents.sh`: grading harnesses for manual testing
of generated apps.
- `docker-compose.otel.yaml`: OTel collector + PostgreSQL services.
- `generate-report.mjs` / `parse-telemetry.mjs`: aggregate per-session
telemetry into cost reports.
- Backend guidelines in `backends/`: SpacetimeDB SDK reference, config
templates, server setup docs, PostgreSQL setup with Drizzle/Socket.io
guidance.
**After https://github.com/clockworklabs/SpacetimeDB/pull/4740 merges,
we will likely want to update this so that it reads backend and SDK
guidance from SKILLS**

## Two complete benchmark runs

**Run 1 (20260403):** Original methodology.
**Run 2 (20260406):** Refined methodology with domain bias removed from
SpacetimeDB SDK docs and PostgreSQL instructions made
feature-spec-neutral.
**Note: no meaningful changes in results were observed with these
changes. Domain familiarity biases were very small and almost certainly
not the cause of STDB's major gains over PG stack.**

Each run contains full L1-L12 app source for both backends, level
snapshots preserving state before each upgrade, and per-session OTel
cost summaries.

## 12 feature levels

| Level | Feature |
|---|---|
| L1 | Basic Chat + Typing + Read Receipts + Unread Counts |
| L2 | Scheduled Messages |
| L3 | Ephemeral Messages |
| L4 | Message Reactions |
| L5 | Message Editing with History |
| L6 | Real-Time Permissions (kick, ban, promote) |
| L7 | Rich User Presence |
| L8 | Message Threading |
| L9 | Private Rooms + Direct Messages |
| L10 | Room Activity Indicators |
| L11 | Draft Sync |
| L12 | Anonymous to Registered Migration |

## Results

| | Run 1 (20260403) | Run 2 (20260406) |
|---|---|---|
| **SpacetimeDB total cost** | $13.33 | $12.62 |
| **PostgreSQL total cost** | $17.80 | $19.68 |
| **SpacetimeDB bugs** | 5 | 2 |
| **PostgreSQL bugs** | 19 | 8 |
| **SpacetimeDB fix sessions** | 4 | 1 |
| **PostgreSQL fix sessions** | 17 | 10 |

Both runs agree: SpacetimeDB apps are cheaper to build, have fewer bugs,
and require fewer fix iterations. The refined methodology (Run 2)
widened the cost gap and **confirmed the advantage is structural, not an
artifact of domain-biased SDK docs.**

## Performance benchmark (`perf-benchmark/`)

Stress throughput tool that fires concurrent writers at peak saturation
against the AI-generated `send_message` handlers.

| Tier | SpacetimeDB (avg) | PostgreSQL (avg) | Ratio |
|---|---|---|---|
| AI-generated (as-shipped) | 5,267 msgs/sec | 694 msgs/sec | 7.6x |
| PG rate limit removed | 5,267 msgs/sec | 1,070 msgs/sec | 4.9x |
| Optimized (same features kept) | 25,278 msgs/sec | 1,139 msgs/sec |
22x |

The gap widens with optimization because SpacetimeDB's bottleneck is
fixable code patterns in the reducer while PostgreSQL's bottleneck is
architectural (sequential network round-trips to an external database).

Optimized reference code with all features preserved is in
`perf-benchmark/results/optimized-reference/`.

## Data handling

Per-session cost summaries (`cost-summary.json`, `COST_REPORT.md`,
`metadata.json`) are committed. Raw OTel telemetry
(`raw-telemetry.jsonl`) containing PII is excluded via `.gitignore` and
stored privately.

# API and ABI breaking changes

None. All changes are in `tools/llm-sequential-upgrade/`. No production
code, library, or SDK changes.

# Expected complexity level and risk

**1 - Trivial.** Self-contained benchmarking tooling and data. No
interaction with production code.

# Testing

- [x] L1-L12 upgrades completed on all 4 apps (2 backends x 2 runs) with
OTel cost capture
- [x] All levels manually graded after each upgrade; bugs filed and
fixed via the harness
- [x] Methodology refinement between runs validated (domain bias
removal, feature-neutral instructions)
- [x] Stress benchmarks run across both runs x 3 tiers (as-shipped,
rate-limit-removed, optimized)
- [x] Optimized benchmarks verified to preserve all original features
- [x] Sensitive data (PII in raw telemetry) removed from repo and
gitignored
- [ ] Reviewer: spot-check that METRICS_DATA.json / METRICS_REPORT.json
numbers match the telemetry cost-summary.json files

---------

Co-authored-by: Tyler Cloutier <cloutiertyler@users.noreply.github.com>
Co-authored-by: clockwork-labs-bot <clockwork-labs-bot@users.noreply.github.com>
2026-06-10 16:37:33 +00:00

204 lines
7.8 KiB
Bash

#!/bin/bash
# Sequential Upgrade — Parallel Benchmark Launcher
#
# Runs multiple test instances in parallel for statistical significance.
# Each instance gets isolated ports via --run-index.
#
# Usage:
# ./benchmark.sh # 3 sequential-upgrade runs, both backends
# ./benchmark.sh --runs 5 # 5 runs
# ./benchmark.sh --variant one-shot --runs 3 # 3 one-shot runs
# ./benchmark.sh --backend spacetime --runs 3 # single backend only
# ./benchmark.sh --rules standard --runs 3 # SDK-only rules
# ./benchmark.sh --level 15 # up to level 15 (22 features)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# ─── Parse arguments ─────────────────────────────────────────────────────────
NUM_RUNS=3
VARIANT="sequential-upgrade"
RULES="guided"
TEST_MODE=""
LEVEL=""
BACKENDS=("spacetime" "postgres")
while [[ $# -gt 0 ]]; do
case $1 in
--runs) NUM_RUNS="$2"; shift 2 ;;
--variant) VARIANT="$2"; shift 2 ;;
--rules) RULES="$2"; shift 2 ;;
--test) TEST_MODE="$2"; shift 2 ;;
--level) LEVEL="$2"; shift 2 ;;
--backend) BACKENDS=("$2"); shift 2 ;;
*) echo "Unknown option: $1"; exit 1 ;;
esac
done
TEST_FLAG=""
if [[ -n "$TEST_MODE" ]]; then
TEST_FLAG="--test $TEST_MODE"
fi
# ─── Compute total parallel instances ────────────────────────────────────────
NUM_BACKENDS=${#BACKENDS[@]}
TOTAL_INSTANCES=$((NUM_RUNS * NUM_BACKENDS))
echo "═══════════════════════════════════════════════════"
echo " Sequential Upgrade Benchmark"
echo "═══════════════════════════════════════════════════"
echo " Variant: $VARIANT"
echo " Rules: $RULES"
echo " Level: ${LEVEL:-auto}"
echo " Backends: ${BACKENDS[*]}"
echo " Runs: $NUM_RUNS per backend"
echo " Total: $TOTAL_INSTANCES parallel instances"
echo ""
echo " Port allocation:"
for i in $(seq 0 $((TOTAL_INSTANCES - 1))); do
OFFSET=$((i * 100))
echo " Run $i: Vite(stdb)=$((5173 + OFFSET)) Vite(pg)=$((5174 + OFFSET)) Express=$((3001 + OFFSET)) PG=$((5433 + OFFSET))"
done
echo "═══════════════════════════════════════════════════"
echo ""
# ─── Validate prerequisites ─────────────────────────────────────────────────
# Add Claude Code desktop install to PATH
_APPDATA_UNIX="${APPDATA:-$HOME/AppData/Roaming}"
if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "cygwin" ]]; then
_APPDATA_UNIX=$(cygpath "$_APPDATA_UNIX" 2>/dev/null || echo "$_APPDATA_UNIX")
fi
CLAUDE_DESKTOP_DIR="$_APPDATA_UNIX/Claude/claude-code"
if [[ -d "$CLAUDE_DESKTOP_DIR" ]]; then
CLAUDE_LATEST=$(ls -d "$CLAUDE_DESKTOP_DIR"/*/ 2>/dev/null | sort -V | tail -1)
if [[ -n "$CLAUDE_LATEST" ]]; then
export PATH="$PATH:$CLAUDE_LATEST"
fi
fi
# Check Claude CLI
if ! command -v claude &>/dev/null && ! command -v claude.exe &>/dev/null; then
echo "ERROR: Claude Code CLI not found."
exit 1
fi
echo "Starting $TOTAL_INSTANCES parallel instances..."
echo ""
# ─── Status tracking ────────────────────────────────────────────────────────
STATUS_FILE="$SCRIPT_DIR/benchmark-status.json"
echo '{}' > "$STATUS_FILE"
update_status() {
local idx="$1" backend="$2" status="$3" detail="${4:-}"
node -e "
const fs = require('fs');
const f = process.argv[1];
const s = JSON.parse(fs.readFileSync(f, 'utf-8'));
s['run-${idx}-${backend}'] = {
runIndex: $idx,
backend: '${backend}',
status: '${status}',
detail: '${detail}',
updatedAt: new Date().toISOString()
};
fs.writeFileSync(f, JSON.stringify(s, null, 2));
" -- "$STATUS_FILE" 2>/dev/null || true
}
# ─── Launch all runs ────────────────────────────────────────────────────────
# Each run gets its own run-loop.sh which handles:
# - Code generation (parallel, headless)
# - Chrome MCP grading (serialized via lock file)
# - Bug fix iterations (headless)
# - Sequential upgrades with regression testing (if applicable)
PIDS=()
RUN_INDEX=0
for run_num in $(seq 1 "$NUM_RUNS"); do
for backend in "${BACKENDS[@]}"; do
LOG_FILE="$SCRIPT_DIR/benchmark-run${RUN_INDEX}-${backend}.log"
echo "[Run $RUN_INDEX] $backend (run $run_num/$NUM_RUNS) → $LOG_FILE"
update_status "$RUN_INDEX" "$backend" "starting" "level=${LEVEL:-auto}"
(
update_status "$RUN_INDEX" "$backend" "running" "$VARIANT"
"$SCRIPT_DIR/run-loop.sh" \
--backend "$backend" \
--variant "$VARIANT" \
--level "${LEVEL:-7}" \
--rules "$RULES" \
$TEST_FLAG \
--run-index "$RUN_INDEX"
update_status "$RUN_INDEX" "$backend" "completed" "exit=$?"
) > "$LOG_FILE" 2>&1 &
PIDS+=($!)
RUN_INDEX=$((RUN_INDEX + 1))
done
done
echo ""
echo "All $TOTAL_INSTANCES instances launched. PIDs: ${PIDS[*]}"
echo ""
echo "Monitor progress:"
echo " cat benchmark-status.json # run status summary"
echo " tail -f benchmark-run*-*.log # live output"
echo ""
echo "Waiting for all runs to complete..."
# ─── Wait for all runs ──────────────────────────────────────────────────────
FAILURES=0
for i in "${!PIDS[@]}"; do
if wait "${PIDS[$i]}"; then
echo "[Run $i] completed successfully"
else
echo "[Run $i] FAILED (exit code $?)"
FAILURES=$((FAILURES + 1))
fi
done
echo ""
echo "═══════════════════════════════════════════════════"
echo " Benchmark Complete"
echo " Successful: $((TOTAL_INSTANCES - FAILURES))/$TOTAL_INSTANCES"
if [[ $FAILURES -gt 0 ]]; then
echo " Failed: $FAILURES"
fi
echo "═══════════════════════════════════════════════════"
# ─── Auto-generate reports ──────────────────────────────────────────────────
echo ""
echo "Generating reports for each run..."
for run_dir in "$SCRIPT_DIR/$VARIANT"/*/; do
if [[ -d "$run_dir/telemetry" ]]; then
RUN_DIR_NATIVE="$run_dir"
if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "cygwin" ]]; then
RUN_DIR_NATIVE=$(cygpath -w "$run_dir")
fi
node "$SCRIPT_DIR/generate-report.mjs" "$RUN_DIR_NATIVE" 2>/dev/null && \
echo " Report: $run_dir/BENCHMARK_REPORT.md" || \
echo " WARNING: Report generation failed for $run_dir"
fi
done
echo ""
echo "═══════════════════════════════════════════════════"
echo " All Done"
echo "═══════════════════════════════════════════════════"
echo ""
echo "Results:"
for run_dir in "$SCRIPT_DIR/$VARIANT"/*/; do
if [[ -f "$run_dir/BENCHMARK_REPORT.md" ]]; then
echo " $run_dir/BENCHMARK_REPORT.md"
fi
done