Skip to content
alexander-srcPublic

About

Optimize Anything: cross-language profiling, equivalence-gated interleaved benchmarking, and MCP optimization loops for coding agents

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

oa

Rust guardrail that stops coding agents from faking benchmarks, loosening tests, or bloating RAM.

Quick start · Upstream PRs · Benchmarks · How oa works · Limitations · GitHub Action · MCP & CLI

Animated oa demo catching locked-test edits, blocking broken output, and verifying a 6.02x speedup

Ask a coding agent to "make this faster" and it usually does one of four things: edits a test assertion, keeps a change inside run-to-run noise, breaks an edge case, or buys 10% less wall time at the cost of +40% RAM.

oa is a single Rust binary (1.6 MB, #![forbid(unsafe_code)], 2 direct dependencies) that runs as a local CLI, a stdio MCP server, and a reusable GitHub Action. It locks tests and benchmark scripts with SHA-256 hashes (Cheat Guard), verifies exact stdout/file output equivalence, profiles Python (scripts, -m, and inline -c), Node.js, Go, Linux perf (with ELF file:line snippets and live LD_PRELOAD peak-heap attribution via --heap-track), and macOS sample, runs balanced interleaved A/B pairs and cyclic round-robin matrices against detached git shadow worktrees, bisects git performance regressions in O(log N) steps (oa bisect), gates wall time and peak RSS jointly (--metric pareto), and exports Markdown tables, dark/light SVG charts, offline HTML reports, RFC 4180 CSV, SARIF 2.1.0, JUnit XML, and git patches.

Quick start

Install

Homebrew (macOS and Linux):

brew install alexander-src/tap/oa

Shell installer (Linux x86_64/aarch64 and macOS arm64/x86_64):

curl -fsSL https://raw.githubusercontent.com/alexander-src/oa/main/install.sh | sh

Or build from source with Cargo:

cargo install --git https://github.com/alexander-src/oa.git

Prebuilt binaries for Linux (x86_64, aarch64, plus static musl builds), macOS (arm64, x86_64), and Windows (x86_64) with SHA256SUMS.txt are attached to GitHub Releases. Release history lives in CHANGELOG.md, and a zero-dependency Node launcher lives under npm/oa-agents.

Try it in 1 second

Run the self-contained demo (creates a temp git repo, exercises Cheat Guard and Equivalence Gate, verifies a 6x+ speedup, and cleans up):

oa demo

Check local profiler backends (python, node, go, cargo, perf, pahole, sample), RSS support, and installed coding agents:

oa doctor

Connect your agent (MCP)

Register oa as an MCP server and install its optimization playbook (SKILL.md) in one command (auto-detects Claude Code, Antigravity, Cursor, Gemini CLI, and Codex):

oa setup

Try asking your agent: "Use oa to initialize an optimization session in this repo (bench_cmd: python3 bench.py, test_cmd: pytest -q). Profile the hot path, iterate on the top bottlenecks, revert anything that fails Cheat Guard or Mann-Whitney U, run oa_verify, export oa_diff, and generate a final oa_report."

Use from the terminal (CLI)

# Lock tests/bench, snapshot refs/oa/baseline, capture reference SHA-256 and initial profile
oa init --bench "python3 bench.py" --test "pytest -q"

# Inspect hotspots with source snippets (or diff against baseline after edits)
oa profile --top 12

# Run Cheat Guard -> tests -> SHA-256 equivalence -> balanced interleaved A/B
oa evaluate --pairs 12

# Keep verified win (updates refs/oa/best) or revert and log the dead end
oa checkpoint --keep --hypothesis "pack parser events in Int32Array tape"
oa checkpoint --revert --hypothesis "switch lexer to finditer" --dead-end "0.96x regression"

# End-to-end verification gate (exits non-zero on tamper, test failure, or noise)
oa verify --pairs 20

# Export Markdown, SVG, offline HTML, RFC 4180 CSV, SARIF 2.1.0, JUnit XML, and a clean git patch
oa report --out REPORT.md
oa report --format svg --theme dark --out bench.svg
oa report --format html --theme light --out report.html
oa report --format csv --out ledger.csv
oa report --format sarif --out oa.sarif
oa report --format junit --out junit.xml
oa diff --out optimization.patch

# Remove .oa/ worktrees and refs once your patch is committed (preserves working tree edits)
oa clean --refs

Real oa demo and oa verify terminal output

Need a quick interleaved comparison, git regression bisect, or hotspot profile without initializing a session? Run oa compare on 2+ commands or git revisions (--git / --git-refs), bisect a commit range with oa bisect, or run oa profile --cmd directly:

# Compare your working tree (or a branch) against main in detached worktrees
oa compare --git main --bench "cargo run --release" --build "cargo build --release" --pairs 15 --check-output --markdown --svg compare.svg --html compare.html --csv pairs.csv --sarif gate.sarif --junit junit.xml

# Compare 3+ commands or git revisions in a cyclic round-robin matrix (cancels host drift)
oa compare "python3 v1.py" "python3 v2.py" "python3 v3.py" --pairs 12 --check-output --markdown --html matrix.html --summary-csv matrix-summary.csv
oa compare --git-refs v1.0,v1.1,HEAD --bench "cargo run --release" --build "cargo build --release" --format csv --out git-matrix.csv

# Compare two binaries with live Linux peak-live heap diff and a diverging SVG chart
oa compare "./bin_old input.dat" "./bin_new input.dat" --pairs 15 --check-output --heap-track --diff-svg heap-diff.svg --markdown

# Statistically bisect a git commit range in O(log N) steps (never touches your working tree)
oa bisect --good v1.0 --bad HEAD --bench "python3 bench.py" --threshold 5 --markdown bisect.md --html bisect.html

# Save a portable baseline snapshot on main, inspect or diff snapshots offline, and track trends over time
oa compare --save-snapshot snapshots/v1.json --label v1.0 -- "python3 bench.py"
oa snapshot-info snapshots/ --sort-by median --format md --csv snapshots.csv
oa compare --baseline-snapshot snapshots/v1.json --check-output --fail-on-regression -- "python3 bench.py"
oa snapshot-diff snapshots/v1.json snapshots/v2.json --fail-on-regression --max-regression-pct 5 --format junit --out diff.junit.xml
oa trend snapshots/ --sort time --threshold 5 --fail-on-regression --format html --out trend.html

# Gate a multi-benchmark suite and absolute wall/RSS budgets from oa.toml
oa suite --init
oa suite --list oa.toml --format md
oa suite oa.toml --save-snapshots snapshots/ --format html --out suite.html --csv suite.csv --junit suite-junit.xml
oa suite oa.toml --tag critical --fail-fast --summary --format md

# One-shot profile with source snippets and live Linux peak-heap attribution (no oa init required)
oa profile "python3 bench.py" --top 10
oa profile "./target/release/app input.dat" --heap-track

# Export a diverging CPU hotspot diff SVG inside an active session, or diff two profile files directly
oa profile --diff-from baseline --svg cpu-diff.svg
oa profile-diff base.folded cand.folded --top 15 --min-delta 0.5 --format html --out profile-diff.html --csv profile-diff.csv

# Generate a deterministic benchmark harness automatically if the repo has none
oa benchgen --out .oa/generated_bench.py

To optimize memory footprint or both latency and memory together, pass --metric rss or --metric pareto (with optional --max-rss-regression 1.05 / --max-wall-regression 1.05) to oa init, oa evaluate, oa verify, oa run, or oa compare. Pass --timeout <SECS> (such as --timeout 30 or --timeout 500ms, or timeout_secs in oa.toml and MCP calls) on execution commands to abort hung builds or benchmarks cleanly. Bundled walkthroughs live under examples/slow_log_parser (--metric wall) and examples/ram_aggregator (--metric rss).

Upstream PRs

Every row below is an upstream pull request measured with oa (--check-output, --metric pareto, and --heap-track). Full reproduction commands and additional local showcases (Textualize/rich, Keats/tera, DaveGamble/cJSON, nodeca/js-yaml, Python-Markdown, brave/adblock-rust) live in BENCHMARKS.md.

Verified multi-language speedups and peak RSS reductions measured with oa

Target Status Verified result Verification PR
sharkdp/bat
Rust · 61k+ stars
Merged (v0.26.0) 1.80x wrapped (49.4 → 26.9 ms) · 1.32x --show-all · p=0.0000 Full upstream suite · identical SHA-256 #4154
Delgan/loguru
Python · 22k+ stars
Merged (4 commits) 1.04x to 1.16x per-record allocation cuts · -2.9% RSS 22/22 CI checks green #1557
boykopovar/AnyPS5
C++20 · PS5 relinker
Approved (2 reviews) 3.26x to 5.03x rewrite pass · 1.70x x64 decoder (#28223)
-67.0% to -67.5% peak RSS (164.9 → 54.4 MiB)
36/36 CTests + 472k-vector oracle · exact byte output #28125
sharkdp/bat
Rust · 61k+ stars · --heap-track
Merged (master) 1.62x --list-languages (4.65 → 2.86 ms) · 1.43x small file
-36.8% peak-live heap · -60.1% heap churn · p<0.0001
Full cargo test suite · identical SHA-256 across 4 workloads #4165
bootandy/dust
Rust · 12.8k stars
Open (CI green) 2.10x -D (48.8 → 23.3 ms) · 2.33x -t · 1.56x default
-56.6% to -72.6% peak RSS (60.2 → 16.5 MiB) · p=0.0000
90/90 cargo tests · identical SHA-256 across 16 CLI flags #664
jqlang/jq
C (-O2) · 32k+ stars
Open (CI green) 124.36x array diff numbers (535.6 → 4.3 ms)
69.76x strings · 25.29x objects · -0.8% RSS · p=0.0000
9/9 test suites · ASan/LSan/UBSan clean · exact SHA-256 #3768

Running oa compare --svg with wall time and Peak RSS produces a dual-axis Pareto comparison card automatically (shown here from jqlang/jq#3768):

Auto-generated oa compare dual-axis wall time and Peak RSS SVG chart

Running oa report --format svg --theme dark on a multi-step session (such as Keats/tera) plots the full experiment trajectory:

Auto-generated oa report SVG chart from the Keats/tera session

How oa works

The five-stage oa optimization loop

oa enforces five controls in order on every optimization step:

  1. Profile first (oa profile). Picks the right backend for your command and returns ranked hotspots with source snippets, allocation sites, hardware counters, bottleneck class (CPU_ALGORITHMIC, SERIALIZATION_BOUND, ALLOC_PRESSURE, GC_OR_ALLOC_BOUND, LOCK_CONTENTION, IO_OR_SYSCALL), and --diff-from hotspot deltas.
  2. Cheat Guard (oa init + oa evaluate). Hashes tracked test and benchmark files into .oa/locks.json. Editing any locked file triggers CheatBlocked, and oa checkpoint --keep rejects any post-evaluation working tree change via a full tree SHA-256 fingerprint.
  3. Behavioral Equivalence Gate. Checks exit code and SHA-256 of stdout, stderr, and declared --output-file artifacts before timing (with --ignore-line for dynamic timestamps or --oracle for custom validators).
  4. Balanced interleaved A/B. Alternates A-B and B-A pairs between your working tree and a detached git shadow worktree under .oa/worktrees/ so CPU frequency scaling and background load cancel out. Cumulative session gains chain paired ratios rather than dividing un-interleaved medians taken minutes apart.
  5. Statistical verdict and verification gate. Accepts a change (KeepRecommended) only when two-sided Mann-Whitney U p <= alpha (default 0.01) and the 2,000-resample bootstrap 95% CI lower bound exceeds --min-speedup (default 1.03x). oa verify re-checks HEAD against refs/oa/baseline from scratch and exits non-zero on failure.

How oa compares

Capability oa hyperfine criterion / pytest-benchmark Agent ad-hoc time
Balanced interleaved A/B pairs vs git baseline Yes No (sequential) Separate runs No
Automatic test and benchmark Cheat Guard locks Yes No No No
Byte-level output SHA-256 equivalence gate Yes No No No
Built-in cross-language profiler + source snippets Yes No No No
Peak RSS (--metric rss / pareto) on Linux, macOS, Windows Yes No Partial No
Native Linux peak-live heap attribution (--heap-track) Yes No No No
Stdio MCP server + SKILL.md for coding agents Yes (20 tools) No No No
Statistical git regression bisection (oa bisect) Yes (O(log N)) No No No
Markdown, SVG, offline HTML, CSV, SARIF 2.1.0, JUnit XML, and git patch export Yes Markdown / CSV HTML / JSON No

Supported profiler backends

Language / Runtime Backend Extracted signals
Python python:cProfile+tracemalloc Function self/cum ms, call counts, source snippets, tracemalloc top allocation sites, peak RSS
Node.js / TS node:v8-cpu+heap-prof V8 .cpuprofile sample tree, V8 --heap-prof allocation sites, GC overhead, source file/line hotspots
Go (go test) go:pprof+mem go test -cpuprofile + -memprofile (pprof -alloc_space), GC/lock class, source snippets
Linux native (Rust, C, C++) linux:perf / linux:heaptrack perf stat (IPC, branch-miss %, cache-miss %), perf report ELF file:line hotspots, perf page-faults RSS-growth sites, live LD_PRELOAD peak-live heap & churn attribution (--heap-track), pahole -P packable DWARF structs, rootless :u fallback
macOS native (Rust, C, C++) macos:sample /usr/bin/sample top-of-stack symbol frames with automatic macos:rusage fallback

GitHub Action

Drop uses: alexander-src/oa@v0.17.0 into any workflow to gate pull requests against their base branch on statistically verified speedups, peak RSS, and output SHA-256 equivalence (posts results to $GITHUB_STEP_SUMMARY and fails on regression or output mismatch):

- uses: alexander-src/oa@v0.17.0
  with:
    mode: git-compare
    base-ref: ${{ github.event.pull_request.base.sha }}
    build-cmd: cargo build --release
    bench-cmd: ./target/release/my_bench
    metric: pareto
    max-rss-regression: 1.05
    max-wall-regression: 1.05
    pairs: 15
    check-output: true
    fail-on-regression: true

Also supports mode: compare (any two commands via cmd-a and cmd-b, single-command baseline capture via save-snapshot, or candidate gating against baseline-snapshot), mode: verify (verifies an active .oa/ session against refs/oa/baseline), and mode: suite (runs an oa.toml benchmark suite via suite-config, suite-filter, suite-tag, suite-fail-fast, and save-snapshots-dir), plus optional sarif-path, html-path, junit-path, baseline-snapshot, save-snapshot, label, copy-files, env, label-a, and label-b inputs. See action.yml for all inputs and outputs (verdict, ratio, p-value, wall-change-pct, rss-change-pct, peak-rss-a-kb, peak-rss-b-kb, outputs-identical, sarif-path, html-path, junit-path, snapshot-path).

MCP & CLI

oa mcp speaks JSON-RPC 2.0 over stdio (both NDJSON and Content-Length framing) and exposes 20 tools:

MCP Tool CLI Equivalent Purpose
oa_discover oa discover Zero-config repo scanner inferring languages, build/test commands, and benchmark candidates
oa_benchgen oa benchgen Generate a deterministic benchmark harness when a repo has no ready-made benchmark
oa_init oa init Lock test/bench files, snapshot refs/oa/baseline, capture output SHA-256 and baseline profile
oa_profile oa profile Profile current tree (or standalone --cmd), classify bottleneck, list live --heap-track / heap sites and pahole struct padding, diff vs baseline or best
oa_evaluate oa evaluate (bench) Enforce Cheat Guard, build, run tests, check SHA-256 equivalence, run interleaved A/B pairs (wall, rss, or pareto with regression guardrails)
oa_checkpoint oa checkpoint Advance refs/oa/best on verified wins or revert working tree and log dead ends
oa_verify oa verify Fresh end-to-end verification of HEAD vs refs/oa/baseline with CI exit code and badge
oa_status oa status Live session metric, cumulative gain, Cheat Guard lock health, dirty files, diff stat
oa_ledger oa ledger Inspect experiment history, Pareto frontier IDs, and ruled-out dead ends
oa_report oa report Export Markdown, JSON, dark/light SVG, offline HTML, RFC 4180 CSV, SARIF 2.1.0, or JUnit XML (--format md|json|svg|html|csv|sarif|junit)
oa_diff oa diff Export the clean unified patch and diff stat between refs/oa/baseline and refs/oa/best
oa_compare oa compare Standalone interleaved A/B across two commands, --git <rev>[..<rev2>], or portable snapshots (--save-snapshot, --baseline-snapshot, --label)
oa_compare_matrix oa compare (3+ / --git-refs) Multi-candidate cyclic round-robin matrix across 2+ commands or git revisions with statistical ranking (json, md, csv, sarif, junit)
oa_bisect oa bisect Statistical O(log N) git regression bisection across good..bad using detached shadow worktrees
oa_trend oa trend Longitudinal wall-time and Peak RSS trend analysis and regression gating across 2+ saved snapshots (text, JSON, Markdown, CSV, HTML, SARIF, JUnit XML)
oa_snapshot_diff oa snapshot-diff Offline statistical diff of two saved benchmark JSON snapshots without executing commands (text, JSON, Markdown, HTML, JUnit XML, SARIF, CSV, SVG)
oa_profile_diff oa profile-diff Side-by-side hotspot diff across two oa profile JSON reports or folded stack files (text, JSON, Markdown, CSV, HTML)
oa_suite oa suite Run or validate (--list / list_only) a declarative multi-benchmark suite and absolute wall/RSS budgets from oa.toml (--summary, --fail-fast, text, JSON, Markdown, CSV, HTML, SARIF, JUnit XML)
oa_doctor oa doctor Inspect local hardware, profilers (python, node, go, cargo, perf, pahole, sample), RSS support, host stability audit, and agent MCP/skill configs
oa_clean oa clean [--refs] Remove .oa/ shadow worktrees and session state (requires confirm: true via MCP, preserves working tree edits)

Additional CLI commands (all supporting both --flag value and --flag=value): oa snapshot-info (offline metadata and distribution summary for 1+ saved snapshot JSON files or directories with --sort-by name|median|rss|timestamp, --format text|json|md|csv, and --csv), oa snapshot-diff (offline statistical diff of two saved snapshot JSON files with --max-regression-pct, --max-rss-pct, --min-effect-pct, --check-output, --fail-on-regression, and --format text|json|md|html|junit|sarif|csv|svg), oa trend (longitudinal wall/RSS trend analysis and HTML/CSV/SARIF/JUnit export across saved snapshot JSON files or directories with --sort, --threshold, --fail-on-regression, and --format text|json|md|csv|html|sarif|junit), oa bisect (statistical O(log N) git regression bisection with --good, --bad, --bench, --threshold, --max-rss-regression, --markdown, --html), oa run (autonomous discover -> benchgen -> profile -> agent -> evaluate -> keep/revert loop with --agent claude|codex|gemini|opencode|cmd, --metric pareto, and --heap-track), oa completions <bash|zsh|fish|powershell> (shell completions), oa man [-o <FILE>] (Unix man(1) roff manual page), oa demo (self-contained walkthrough), oa doctor (local profiler & agent check), oa setup (auto-configure MCP + SKILL.md), and oa clean [--refs].

FAQ

Does oa touch my git history or push anything?

No. oa stores snapshots under private git refs (refs/oa/baseline, refs/oa/best, refs/oa/exp/<n>) and shadow worktrees under .oa/ (automatically added to .git/info/exclude). Your branch history and remotes stay untouched. Run oa clean --refs after committing to remove .oa/ and all refs/oa/* refs.

How does Windows Peak RSS measurement work without unsafe Rust?

On Linux and macOS, oa uses /usr/bin/time (or python3 resource.getrusage). On Windows, oa wraps --metric rss executions via stdlib Python ctypes calling Win32 K32GetProcessMemoryInfo and QueryInformationJobObject (PeakJobMemoryUsed), keeping the Rust binary #![forbid(unsafe_code)].

What if my workload has nondeterministic output (timestamps, UUIDs, floats)?

Pass --ignore-line <SUBSTR> to strip dynamic lines before hashing, or pass --oracle "<CMD>" to delegate equivalence checking to a custom validator script (for example, numeric tolerance rtol/atol).

Does oa require root for Linux perf?

No. When /proc/sys/kernel/perf_event_paranoid blocks kernel events, oa retries automatically with user-space :u counters (cycles:u, instructions:u, branches:u, branch-misses:u) and user-space perf record. Compile native targets with -g or CARGO_PROFILE_RELEASE_DEBUG=true to resolve ELF hotspots to project file:line snippets.

Limitations

  • oa cannot invent algorithmic breakthroughs on already-tuned SIMD or assembly kernels (on brave/adblock-rust, the verified gain was 1.05x and oa rejected 4 regressions/noise edits).
  • Correctness is only as strong as your test suite, --output-file hashes, or custom --oracle; code paths uncovered by both tests and benchmark outputs are not formally verified.
  • Single-machine local benchmarking only; distributed and multi-node latency profiles are out of scope.
  • --heap-track is Linux-only, needs a C compiler (cc/gcc/clang) and addr2line for file:line resolution, and only intercepts dynamically linked libc allocators (malloc/calloc/realloc/free), not static musl binaries or custom embedded allocators.
  • --metric rss on Windows requires python on PATH (for the stdlib ctypes Win32 memory query); Linux and macOS use /usr/bin/time or python3.
  • Very fast commands (< 15 ms) are dominated by process-spawn overhead (oa warns automatically when candidate median drops below 15 ms or CV exceeds 8%); put an inner loop in the benchmark script so measured work is at least 30-50 ms.

Contributing

See CONTRIBUTING.md for development commands (cargo test --all-targets, cargo clippy --all-targets -- -D warnings), the profiler adapter contract, and open good first issue tickets.

License

MIT

About

Optimize Anything: cross-language profiling, equivalence-gated interleaved benchmarking, and MCP optimization loops for coding agents

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages