diff --git a/.cspell/words.txt b/.cspell/words.txt index 4765948ea..ce861eb09 100644 --- a/.cspell/words.txt +++ b/.cspell/words.txt @@ -11,6 +11,7 @@ direnv envrc esac esbuild +fcntl flac ftyp Ghostty @@ -18,20 +19,25 @@ hakula hakulattic indoc isom +kbytes +killpg libiconv libwebp magick Menlo MSVC +ncpu nixfmt nixos nixpkgs nocapture noindex +openpty osascript oxalica pkgs pname +Popen rasterizes rects resvg @@ -50,6 +56,7 @@ substituters syntect taiki taplo +TIOCSWINSZ tomllib tspan unpoisoned diff --git a/README.md b/README.md index d26ec283f..2249ef032 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ A minimal, extensible Rust coding agent harness (`ox`) built for experienced eng - **Minimal Rust core and language-agnostic extensions** - Small, TUI-free Rust core (`ox-core`) with 4 built-in tools, SQLite session persistence, zero telemetry, and a workspace trust gate. + - Lightweight native footprint: 12.45 MiB stripped binary, 7.14 ms median `--version` startup, 12.03 MiB idle TUI RSS, and 171 µs full 120x40 frame draws on Apple M1 Pro (see [Performance](docs/reference/performance.md)). - Process-isolated stdio JSON-RPC 2.0 plugins in any language for tools, commands, compaction, hooks, prompt sections, hints, and attachment converters (see [Building Plugins](docs/guides/building-plugins.md)). - Out-of-process MCP (`ox-plugin-mcp`), keeping `ox-core` MCP-agnostic. diff --git a/docs/README.md b/docs/README.md index cd1baa953..37f32dc04 100644 --- a/docs/README.md +++ b/docs/README.md @@ -24,6 +24,7 @@ Documentation for `oxide-code` (`ox`) is organized into three user-facing bucket | [Compaction](reference/core/compaction.md) | Automatic and manual compaction, preservation, and session boundaries | | [Configuration](reference/core/configuration.md) | `config.toml` layering, `package_roots`, providers, and model bindings | | [Models](reference/core/models.md) | Data-driven model catalog TOML schema and tier profiles | +| [Performance](reference/performance.md) | Measured binary footprint, startup latency, RSS, and hot-path benches | | [Sessions](reference/core/sessions.md) | SQLite session schema, `seq` invariants, and rewind semantics | | [Steering](reference/core/steering.md) | Mid-stream steering channel, injection points, and persistence | | [System Prompt](reference/core/system-prompt.md) | Named system prompt sections and declarative Markdown overrides | diff --git a/docs/reference/performance.md b/docs/reference/performance.md new file mode 100644 index 000000000..2e41c038a --- /dev/null +++ b/docs/reference/performance.md @@ -0,0 +1,75 @@ +--- +title: Performance +description: Measured binary footprint, startup latency, memory usage, and Criterion hot-path benchmarks for ox. +--- + +This page records measured binary size, startup latency, memory footprint, and Criterion microbenchmark numbers for `ox`, along with how to reproduce them locally. + +## Methodology and Test Environment + +All numbers on this page were collected with [`scripts/bench-footprint.nu`](../../scripts/bench-footprint.nu) against a release build of `ox` (`lto = true`, `codegen-units = 1`, `strip = true` in `Cargo.toml`). + +- **Date**: 2026-12-06 +- **Hardware**: Apple M1 Pro (8 cores, `arm64`) +- **OS**: macOS 27.2.1 (`26B131`) +- **Toolchain**: `rustc 1.100.1 (20ddd0171 2026-11-25)` + +How each metric is measured: + +- **Binary size**: Size of the resolved executable on disk in MiB, following symlinks and shell wrapper scripts to the underlying binary. +- **`--version` startup**: Median and p95 wall-clock time across 20 sequential invocations of ` --version`. +- **`--version` peak RSS**: Median peak resident set size across 5 invocations using `/usr/bin/time -l` on macOS (bytes converted to MiB) or `/usr/bin/time -v` on Linux (KiB converted to MiB). +- **Idle PTY RSS**: Resident set size of `ox --no-session --model claude-sonnet-4-5 --trust` sampled via `ps -o rss=` after 1.5 seconds in a 120x40 PTY once the initial TUI frame renders. +- **Criterion hot paths**: Median point estimates from `cargo bench -p ox-core --bench hot_paths` and `cargo bench -p ox-tui --bench render` (100 samples per benchmark). + +### Reproducing Locally + +Run the benchmark script from the repository root inside the Nix development shell: + +```bash +nix develop -c ./scripts/bench-footprint.nu --build --compare --criterion +``` + +Pass `--json` to emit machine-readable JSON, or omit `--compare` and `--criterion` for a quick footprint check of `ox` alone. Missing comparison CLIs on `PATH` are skipped automatically. + +## CLI Footprint and Startup + +The table below compares `ox` against other coding agent CLIs installed on the same host. These tools ship different architectures and runtimes: `ox` is a stripped native Rust binary with out-of-process extensions, `codex` is a larger native binary, and `claude` and `omp` are standalone Bun-compiled executables that bundle a JavaScript runtime. Because `--version` exits before initializing full interactive UIs, plugin hosts, or network clients, it measures baseline binary launch overhead. + +| CLI | Version | Runtime / Packaging | Binary Size | `--version` Median | `--version` p95 | `--version` Peak RSS | Idle PTY RSS | +| -------- | ----------------------- | --------------------------- | ----------: | -----------------: | --------------: | -------------------: | -----------: | +| `ox` | `ox 0.2.0-alpha.1` | Native Rust (LTO, stripped) | 12.45 MiB | 7.14 ms | 8.27 ms | 7.13 MiB | 12.03 MiB | +| `claude` | `2.1.337 (Claude Code)` | Bundled Bun executable | 393.29 MiB | 18.56 ms | 21.06 ms | 20.28 MiB | n/a | +| `codex` | `codex-cli 0.174.0` | Native binary | 406.84 MiB | 13.49 ms | 15.37 ms | 14.06 MiB | n/a | +| `omp` | `omp/19.4.4` | Bundled Bun executable | 239.18 MiB | 16.20 ms | 20.62 ms | 29.84 MiB | n/a | + +## Criterion Hot-Path Benchmarks + +### `ox-core` Hot Paths + +Benchmarks in [`crates/ox-core/benches/hot_paths.rs`](../../crates/ox-core/benches/hot_paths.rs) cover SSE wire framing, context compaction, model catalog loading, and skill frontmatter parsing. + +| Group | Benchmark | Workload | Median | +| --------------------- | ------------------------------- | ----------------------------------------------------------------- | -------: | +| `ox_core/compaction` | `allocate_fair_budgets_64` | Fair budget allocation across 64 items | 202.3 ns | +| `ox_core/frontmatter` | `skill_parse` | Parse a `SKILL.md` frontmatter header and body | 634.5 ns | +| `ox_core/compaction` | `truncate_chars_with_marker` | UTF-8 character-safe truncation with marker | 1.46 µs | +| `ox_core/compaction` | `find_cut_point_48_msgs` | Locate compaction cut boundary in a 48-message session | 4.95 µs | +| `ox_core/compaction` | `extract_files_xml_and_prefix` | Extract read and modified file paths from session and summary XML | 6.06 µs | +| `ox_core/catalog` | `builtin` | Construct the built-in model catalog | 11.25 µs | +| `ox_core/catalog` | `from_toml_16_models` | Parse a 16-model TOML catalog definition | 24.00 µs | +| `ox_core/sse` | `openai_responses_64b_chunks` | Parse an OpenAI Responses SSE stream in 64-byte chunks | 46.91 µs | +| `ox_core/sse` | `anthropic_messages_64b_chunks` | Parse an Anthropic Messages SSE stream in 64-byte chunks | 66.13 µs | + +### `ox-tui` Rendering Hot Paths + +Benchmarks in [`crates/ox-tui/benches/render.rs`](../../crates/ox-tui/benches/render.rs) cover incremental Markdown rendering, full terminal frame drawing at 120x40, and SVG snapshot generation. + +| Group | Benchmark | Workload | Median | +| ----------------- | ------------------------------------ | ----------------------------------------------------------------------- | --------: | +| `ox_tui/markdown` | `render_markdown_incremental_warm` | Warm incremental Markdown cache hit | 2.33 µs | +| `ox_tui/ui` | `render_populated_transcript_120x40` | Full Ratatui frame draw on a populated 4-turn transcript (120x40) | 171.12 µs | +| `ox_tui/svg` | `buffer_to_svg_120x40` | Render a 120x40 Ratatui buffer to SVG | 419.26 µs | +| `ox_tui/markdown` | `render_markdown_multi_block` | Cold full Markdown parse with GFM table and `syntect` Rust highlighting | 471.38 µs | + +At 171.12 µs per full 120x40 frame draw and 2.33 µs for warm incremental Markdown updates, frame rendering stays well under a 16.67 ms (60 FPS) budget. diff --git a/scripts/bench-footprint.nu b/scripts/bench-footprint.nu new file mode 100755 index 000000000..683d1837e --- /dev/null +++ b/scripts/bench-footprint.nu @@ -0,0 +1,455 @@ +#!/usr/bin/env nu + +# Measure binary size, CLI startup latency, memory footprint, and optional Criterion hot-path +# benchmarks for `ox` and installed comparison CLIs. + +const SCRIPT_DIR = path self "." +const BYTES_PER_MIB = 1048576.0 +const KIB_PER_MIB = 1024.0 +const COMPARE_TARGETS = ["claude" "codex" "omp"] + +def resolve-binary [cmd: string]: nothing -> oneof { + let found = (which $cmd | where type == "external") + if ($found | is-empty) { + return null + } + + mut current = ($found | get 0.path | path expand) + + for _ in 0..5 { + let size = (try { ls $current | get 0.size | into int } catch { 0 }) + if $size <= 0 or $size > 4096 { + break + } + + let text = (try { open --raw $current | into string } catch { "" }) + if not ($text | str starts-with "#!") { + break + } + + let matches = ( + $text + | lines + | each {|line| + let parsed = ( + $line + | parse --regex r#'^\s*exec\s+(?:-a\s+\S+\s+)?(?:"([^"]+)"|'([^']+)'|(\S+))'# + ) + if ($parsed | is-not-empty) { + let row = ($parsed | get 0) + [$row.capture0 $row.capture1 $row.capture2] + | where { ($in | is-not-empty) } + | get --optional 0 + } else { + null + } + } + | compact + ) + if ($matches | is-empty) { + break + } + + let target = ($matches | last) + if not ($target | path exists) { + break + } + + let resolved = ($target | path expand) + if $resolved == $current { + break + } + $current = $resolved + } + + $current +} + +def binary-size-mib [bin: path]: nothing -> float { + let bytes = (ls $bin | get 0.size | into int) + ($bytes / $BYTES_PER_MIB) | math round --precision 2 +} + +def version-string [bin: path]: nothing -> string { + let res = (^$bin --version | complete) + let raw = if ($res.stdout | str trim | is-not-empty) { + $res.stdout + } else { + $res.stderr + } + + let first_line = ( + $raw + | lines + | where { ($in | str trim | is-not-empty) } + | get --optional 0 + ) + ($first_line | default "unknown" | str trim) +} + +def percentile [sorted: list, pct: float]: nothing -> float { + let len = ($sorted | length) + let rank = (($len * $pct / 100.0 | math ceil | into int) - 1) + let idx = if $rank < 0 { + 0 + } else if $rank >= $len { + $len - 1 + } else { + $rank + } + $sorted | get $idx +} + +def measure-startup [bin: path, runs: int]: nothing -> record { + let samples = ( + 1..$runs + | each { + let start = (date now) + let _ = (^$bin --version | complete) + let elapsed_ns = (((date now) - $start) | into int) + ($elapsed_ns / 1_000_000.0) + } + | sort + ) + + { + median_ms: ($samples | math median | math round --precision 2) + p95_ms: (percentile $samples 95.0 | math round --precision 2) + } +} + +def parse-peak-rss-mib [stderr: string, os_name: string]: nothing -> oneof { + if $os_name == "macos" { + let parsed = ($stderr | parse --regex '(?m)^\s*(\d+)\s+maximum resident set size\b') + if ($parsed | is-empty) { + null + } else { + let bytes = ($parsed | get 0.capture0 | into float) + ($bytes / $BYTES_PER_MIB) | math round --precision 2 + } + } else { + let parsed = ($stderr | parse --regex '(?m)Maximum resident set size \(kbytes\):\s*(\d+)') + if ($parsed | is-empty) { + null + } else { + let kib = ($parsed | get 0.capture0 | into float) + ($kib / $KIB_PER_MIB) | math round --precision 2 + } + } +} + +def measure-peak-rss [bin: path, samples: int]: nothing -> oneof { + if not ("/usr/bin/time" | path exists) { + return null + } + + let os_name = $nu.os-info.name + let time_flag = if $os_name == "macos" { "-l" } else { "-v" } + + let values = ( + 1..$samples + | each { + let res = (^/usr/bin/time $time_flag $bin --version | complete) + parse-peak-rss-mib $res.stderr $os_name + } + | compact + | sort + ) + + if ($values | is-empty) { + null + } else { + $values | math median | math round --precision 2 + } +} + +def measure-pty-idle-rss [ + bin: path + args: list + wait_sec: float +]: nothing -> oneof { + if (which "python3" | is-empty) { + return null + } + + let py_code = ([ + "import fcntl, os, pty, select, signal, struct, subprocess, sys, termios, time" + "wait_sec = float(sys.argv[1])" + "cmd = sys.argv[2:]" + "master, slave = pty.openpty()" + "fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 40, 120, 0, 0))" + "env = os.environ.copy()" + "env.setdefault('TERM', 'xterm-256color')" + "proc = subprocess.Popen(cmd, stdin=slave, stdout=slave, stderr=slave, env=env, start_new_session=True)" + "os.close(slave)" + "replied = False" + "buf = bytearray()" + "deadline = time.monotonic() + wait_sec" + "while time.monotonic() < deadline:" + " if proc.poll() is not None: break" + " r, _, _ = select.select([master], [], [], max(0.0, min(0.05, deadline - time.monotonic())))" + " if r:" + " try: chunk = os.read(master, 4096)" + " except OSError: break" + " if not chunk: break" + " buf.extend(chunk)" + " if not replied and b'\\x1b[c' in buf:" + " os.write(master, b'\\x1b[?0u\\x1b[?62c')" + " replied = True" + "rss = ''" + "if proc.poll() is None:" + " out = subprocess.run(['ps', '-o', 'rss=', '-p', str(proc.pid)], capture_output=True, text=True)" + " rss = out.stdout.strip()" + " try: os.killpg(proc.pid, signal.SIGTERM)" + " except ProcessLookupError: pass" + " try: proc.wait(timeout=2.0)" + " except subprocess.TimeoutExpired:" + " try: os.killpg(proc.pid, signal.SIGKILL)" + " except ProcessLookupError: pass" + " proc.wait(timeout=2.0)" + "os.close(master)" + "print(rss)" + ] | str join "\n") + + let res = ( + ^python3 + -c $py_code + ($wait_sec | into string) + $bin + ...$args + | complete + ) + let raw = ($res.stdout | str trim) + if $res.exit_code != 0 or ($raw | is-empty) { + return null + } + + let kib = (try { $raw | into float } catch { return null }) + ($kib / $KIB_PER_MIB) | math round --precision 2 +} + +def measure-cli [ + name: string + bin: path + runs: int + idle_args: oneof, nothing> +]: nothing -> record { + let startup = (measure-startup $bin $runs) + let peak_rss = (measure-peak-rss $bin 5) + let idle_rss = if $idle_args != null { + measure-pty-idle-rss $bin $idle_args 1.5 + } else { + null + } + + { + name: $name + binary: $bin + version: (version-string $bin) + binary_mib: (binary-size-mib $bin) + startup_median_ms: $startup.median_ms + startup_p95_ms: $startup.p95_ms + peak_rss_mib: $peak_rss + idle_rss_mib: $idle_rss + } +} + +def format-ns [ns: float]: nothing -> string { + if $ns < 1_000.0 { + $"($ns | math round --precision 1) ns" + } else if $ns < 1_000_000.0 { + $"(($ns / 1_000.0) | math round --precision 2) µs" + } else { + $"(($ns / 1_000_000.0) | math round --precision 2) ms" + } +} + +def run-cargo [args: list]: nothing -> nothing { + let res = (^cargo ...$args | complete) + if $res.exit_code != 0 { + if ($res.stderr | is-not-empty) { + print --stderr $res.stderr + } + error make { msg: $"cargo ($args | str join ' ') failed with exit code ($res.exit_code)" } + } +} + +def run-criterion-benches [repo_root: path]: nothing -> list { + run-cargo ["bench" "-p" "ox-core" "--bench" "hot_paths"] + run-cargo ["bench" "-p" "ox-tui" "--bench" "render"] + + let criterion_dir = ($repo_root | path join "target/criterion") + let estimate_files = ( + glob ($criterion_dir | path join "ox_*/*/new/estimates.json") + | sort + ) + + $estimate_files + | each {|file| + let meta = (open ($file | path dirname | path join "benchmark.json")) + let data = (open $file) + let median_ns = ($data.median.point_estimate | into float) + + { + group: $meta.group_id + name: $meta.function_id + median_ns: ($median_ns | math round --precision 2) + median_human: (format-ns $median_ns) + } + } + | sort-by group name +} + +def collect-env-info []: nothing -> record { + let os_name = $nu.os-info.name + let arch = (^uname -m | str trim) + let os_label = if $os_name == "macos" { + let prod = (^sw_vers -productName | str trim) + let ver = (^sw_vers -productVersion | str trim) + let build = (^sw_vers -buildVersion | str trim) + $"($prod) ($ver) \(($build)\)" + } else { + (^uname -sr | str trim) + } + + let cpu = if $os_name == "macos" { + (^sysctl -n machdep.cpu.brand_string | str trim) + } else { + let line = ( + try { + open --raw "/proc/cpuinfo" + | lines + | where { ($in | str starts-with "model name") } + | first + } catch { + null + } + ) + if $line != null { + $line | split row ":" | get 1 | str trim + } else { + $arch + } + } + + let cores = if $os_name == "macos" { + (^sysctl -n hw.ncpu | str trim | into int) + } else { + (^nproc | str trim | into int) + } + + { + date: (date now | format date "%Y-%m-%d") + os: $os_label + arch: $arch + cpu: $cpu + cores: $cores + rustc: (^rustc --version | str trim) + } +} + +def format-opt [val: oneof, suffix: string]: nothing -> string { + if $val == null { + "n/a" + } else { + $"($val) ($suffix)" + } +} + +def render-markdown [report: record]: nothing -> string { + let env_info = $report.environment + mut sections = [ + "## Environment" + "" + $"- **Date**: ($env_info.date)" + $"- **Hardware**: ($env_info.cpu) \(($env_info.cores) cores, ($env_info.arch)\)" + $"- **OS**: ($env_info.os)" + $"- **Toolchain**: `($env_info.rustc)`" + "" + "## CLI Footprint and Startup" + "" + "| CLI | Version | Binary Size | `--version` Median | `--version` p95 | `--version` Peak RSS | Idle PTY RSS |" + "| --- | --- | ---: | ---: | ---: | ---: | ---: |" + ] + + for row in $report.targets { + let peak = (format-opt $row.peak_rss_mib "MiB") + let idle = (format-opt $row.idle_rss_mib "MiB") + $sections = ( + $sections + | append $"| `($row.name)` | `($row.version)` | ($row.binary_mib) MiB | ($row.startup_median_ms) ms | ($row.startup_p95_ms) ms | ($peak) | ($idle) |" + ) + } + + if ($report.criterion | is-not-empty) { + $sections = ( + $sections + | append [ + "" + "## Criterion Hot-Path Benchmarks" + "" + "| Group | Benchmark | Median |" + "| --- | --- | ---: |" + ] + ) + for bench in $report.criterion { + $sections = ( + $sections + | append $"| `($bench.group)` | `($bench.name)` | ($bench.median_human) |" + ) + } + } + + $sections | str join "\n" +} + +# Measure `ox` binary size, startup latency, memory footprint, and optional Criterion hot paths. +def main [ + --build # Rebuild `target/release/ox` before measuring + --runs (-n): int = 20 # Number of `--version` invocations for startup timing + --compare # Compare against installed `claude`, `codex`, and `omp` binaries on PATH + --criterion # Run `ox-core` and `ox-tui` Criterion benchmarks and summarize medians + --json # Print structured JSON +]: nothing -> nothing { + if $runs < 1 { + error make { msg: "--runs must be at least 1" } + } + + let repo_root = ($SCRIPT_DIR | path dirname) + cd $repo_root + + let ox_bin = ($repo_root | path join "target/release/ox") + if $build or not ($ox_bin | path exists) { + run-cargo ["build" "--release" "-p" "ox"] + } + + mut targets = [(measure-cli "ox" $ox_bin $runs ["--no-session" "--model" "claude-sonnet-4-5" "--trust"])] + + if $compare { + for name in $COMPARE_TARGETS { + let resolved = (resolve-binary $name) + if $resolved != null { + $targets = ($targets | append (measure-cli $name $resolved $runs null)) + } + } + } + + let criterion = if $criterion { + run-criterion-benches $repo_root + } else { + [] + } + + let report = { + environment: (collect-env-info) + runs: $runs + targets: $targets + criterion: $criterion + } + + if $json { + print ($report | to json) + } else { + print (render-markdown $report) + } +} diff --git a/website/astro.config.ts b/website/astro.config.ts index 50c077628..7864bdb26 100644 --- a/website/astro.config.ts +++ b/website/astro.config.ts @@ -78,6 +78,7 @@ export default defineConfig({ { slug: 'reference/core/steering' }, { slug: 'reference/core/system-prompt' }, { slug: 'reference/core/trust' }, + { slug: 'reference/performance' }, ], }, diff --git a/website/src/content/docs/index.mdx b/website/src/content/docs/index.mdx index 1ed249f87..795e14278 100644 --- a/website/src/content/docs/index.mdx +++ b/website/src/content/docs/index.mdx @@ -35,7 +35,9 @@ import { Card, CardGrid } from '@astrojs/starlight/components'; Small, TUI-free Rust core (`ox-core`) with SQLite persistence, zero telemetry, and a workspace - trust gate. [Architecture →](/architecture/overview/) + trust gate. 12.45 MiB stripped binary, 7.14 ms median startup, 12.03 MiB idle TUI RSS, and 171 + µs frame draws. [Architecture →](/architecture/overview/) · [Performance + →](/reference/performance/) Language-agnostic stdio JSON-RPC 2.0 plugins and out-of-process MCP (`ox-plugin-mcp`). [Building