Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

metal debug skill

eugene122d904970e1
diff --git a/agents/skills/metal-gpu-debug/SKILL.md b/agents/skills/metal-gpu-debug/SKILL.md
new file mode 100644
index 000000000..ae37e147b
--- /dev/null
+++ b/agents/skills/metal-gpu-debug/SKILL.md
@@ -0,0 +1,1010 @@
+---
+name: metal-gpu-debug
+description: >
+ Metal GPU debugging and profiling via xctrace and Apple's Metal toolchain. Use this skill when the user mentions:
+ Metal debugging, .gputrace files, Metal shaders, Metal pipeline state, Metal performance,
+ Metal System Trace, Apple GPU profiling, Metal validation, shader compilation errors,
+ MSL (Metal Shading Language), .metallib files, .air files, Metal render pass,
+ Metal command buffer, Metal encoder, MTLDevice, MTLTexture, Metal Performance HUD,
+ GPU counters on Apple Silicon, Metal frame capture, Metal API validation,
+ Metal shader validation, xcrun metal, xctrace, Instruments GPU trace,
+ MoltenVK debugging, Vulkan on macOS, Apple Silicon GPU, Metal 3, Metal 4,
+ Metal compute kernel, MetalFX, Metal Performance Shaders, Metal ray tracing,
+ "profile my Metal app", "why is my shader slow", "capture a Metal frame",
+ "Metal validation error", "debug Metal on Mac", "GPU trace on macOS".
+ DO NOT use for: RenderDoc, Vulkan on Windows/Linux, D3D debugging, PIX,
+ Nsight, CSS rendering, React rendering, server-side rendering, HTML layout,
+ browser DevTools, web performance.
+---
+
+# Metal GPU Debugging & Profiling Skill
+
+## Overview
+
+This skill enables Metal GPU profiling, debugging, and shader analysis on macOS using Apple's command-line toolchain. The primary tools are:
+
+- **`gpu_trace`** — Unified CLI for recording, analyzing, and comparing Metal GPU traces (in `tools/gpu_trace/`, run via `uv run gpu_trace`). Subcommands:
+ - `gpu_trace run` — Record a Metal System Trace while running a command
+ - `gpu_trace analyze` — Analyze an existing `.trace` bundle with per-kernel timing & HW counters
+ - `gpu_trace compare` — Compare two traces side-by-side
+ - `gpu_trace capture` — Inspect `.gputrace` captures (list resources, read buffers/textures)
+ - `gpu_trace view` — View a previously exported JSON trace
+- **`xctrace`** — CLI for Instruments (used internally by `gpu_trace`; can also be used directly)
+- **`xcrun metal`** — Metal shader compiler toolchain (compile, archive, link)
+- **Metal environment variables** — validation layers, Performance HUD, programmatic capture
+- **`log`** — macOS unified logging for Metal HUD and validation output
+
+### Prerequisites
+
+Before any Metal debugging, verify the environment:
+
+```bash
+# Check Xcode is installed (full Xcode, not just Command Line Tools)
+xcode-select -p
+# Expected: /Applications/Xcode.app/Contents/Developer
+
+# Check xctrace is available
+xcrun xctrace version
+
+# Check Metal compiler
+xcrun -sdk macosx metal --version
+
+# List available GPU devices (requires a Swift/ObjC helper or Python)
+system_profiler SPDisplaysDataType | grep -A5 "Chipset\|Metal"
+```
+
+**IMPORTANT**: `xctrace` and Metal tools require **full Xcode**, not just Command Line Tools.
+
+## 1. Automated Session Lifecycle
+
+Every Metal debugging session follows a strict pipeline: **Doctor → Record → Export → Parse → Analyze → Report → Cleanup**. Claude should execute this pipeline autonomously, not just suggest commands.
+
+### Step 0: Doctor — Verify environment
+
+**Run this FIRST before any debugging session.** If any check fails, stop and tell the user what's missing.
+
+```bash
+# Create working directories
+mkdir -p ./traces/analysis
+
+# Verify toolchain
+xcode-select -p # Must show Xcode.app path, NOT CommandLineTools
+xcrun xctrace version # Must succeed
+xcrun -sdk macosx metal --version # Must succeed
+system_profiler SPDisplaysDataType | grep -i "metal\|chipset" # GPU info
+
+# For iOS: check connected devices
+xcrun xctrace list devices 2>/dev/null # List all available targets
+
+# Check gpu_trace is available
+cd tools/gpu_trace && uv run gpu_trace --help >/dev/null 2>&1 && echo "gpu_trace OK"
+```
+
+**If `xcode-select -p` returns `/Library/Developer/CommandLineTools`**, tell the user:
+```
+Xcode Command Line Tools is installed but full Xcode is required.
+Install from: https://developer.apple.com/xcode/
+Then run: sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
+```
+
+### Step 1: Record — Capture a Metal System Trace
+
+**Preferred: Use `gpu_trace run`** (handles recording + export + analysis automatically):
+
+```bash
+# MODE A: Launch and profile (most common)
+cd tools/gpu_trace && uv run gpu_trace run -- /path/to/app [args...]
+
+# MODE A with hardware counters (ALU, memory, cache)
+cd tools/gpu_trace && uv run gpu_trace run --gpu-counters -- /path/to/app
+
+# MODE A with time limit
+cd tools/gpu_trace && uv run gpu_trace run --time-limit 10s -- /path/to/app
+
+# MODE B: Attach to running process
+cd tools/gpu_trace && uv run gpu_trace run --attach <PID> --time-limit 10s
+
+# MODE A with verbose output (all HW counters per kernel)
+cd tools/gpu_trace && uv run gpu_trace run -v --gpu-counters -- /path/to/app
+```
+
+**Fallback: Use `xctrace` directly** (for advanced options like validation env vars, iOS):
+
+```bash
+# MODE C: With validation enabled (for debugging errors)
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --env MTL_DEBUG_LAYER=1 \
+ --env MTL_SHADER_VALIDATION=1 \
+ --time-limit 10s \
+ --no-prompt \
+ --output ./traces/capture.trace \
+ --launch -- /path/to/app
+
+# MODE D: iOS device (over USB)
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --device '<DEVICE_NAME_OR_UDID>' \
+ --attach <APP_NAME> \
+ --time-limit 10s \
+ --no-prompt \
+ --output ./traces/capture.trace
+```
+
+**Decision guide:**
+- User says "profile my app" → `gpu_trace run`
+- User says "it's already running" → `gpu_trace run --attach <PID>`
+- User says "I'm getting errors" or "something is wrong" → `xctrace` with validation env vars
+- User mentions iPhone/iPad → `xctrace` with `--device`
+
+### Steps 2–3: Export & Parse — Analyze the trace
+
+**Preferred: Use `gpu_trace analyze`** (handles export, parsing, and analysis in one step):
+
+```bash
+# Analyze an existing trace (recorded with gpu_trace run or xctrace)
+cd tools/gpu_trace && uv run gpu_trace analyze /path/to/capture.trace
+
+# Verbose output (all HW counters per kernel)
+cd tools/gpu_trace && uv run gpu_trace analyze /path/to/capture.trace -v
+
+# Export to JSON for further processing
+cd tools/gpu_trace && uv run gpu_trace analyze /path/to/capture.trace --json output.json
+
+# JSON to stdout (for piping)
+cd tools/gpu_trace && uv run gpu_trace analyze /path/to/capture.trace --json -
+```
+
+`gpu_trace analyze` automatically:
+- Exports all relevant schemas in parallel (GPU state, encoders, intervals, counters, shaders)
+- Resolves xctrace's XML reference/ID structure
+- Computes GPU utilization with overlapping interval union
+- Aggregates per-kernel timing statistics
+- Correlates hardware counters with kernel dispatches (O(D log S) bisect)
+- Detects bottlenecks (ALU, buffer, cache, MMU limiters)
+
+**Fallback: Use `xctrace export` directly** (for schemas not covered by `gpu_trace`):
+
+```bash
+# Get table of contents
+xcrun xctrace export --input ./traces/capture.trace --toc
+
+# Export a specific schema
+xcrun xctrace export --input ./traces/capture.trace \
+ --xpath '/trace-toc/run[@number="1"]/data/table[@schema="metal-driver-event-intervals"]'
+```
+
+**Schema availability varies** by Xcode version, template, and GPU. `gpu_trace analyze` handles missing schemas gracefully.
+
+### Step 4: Analyze — Interpret the data
+
+After parsing, Claude should analyze the results and look for:
+
+**Performance profiling:**
+- GPU busy time per frame (>16ms = below 60fps, >8ms = below 120fps)
+- Large wire memory events (excessive per-frame resource allocation)
+- Gaps between GPU submissions (CPU-bound)
+- Long shader execution intervals (complex shaders)
+- Imbalanced encoder durations (one pass dominating)
+
+**Validation errors:**
+- Pattern-match stderr and log output for Metal error codes
+- Classify errors: API misuse vs shader bug vs resource issue
+- Map errors to specific command encoders via labels
+
+**Shader issues:**
+- Compile-time warnings/errors from `xcrun metal`
+- Runtime validation errors from `MTL_SHADER_VALIDATION`
+
+### Step 5: Report — Present findings to user
+
+Structure the report as:
+1. **Environment**: GPU model, macOS version, device (Mac/iOS)
+2. **Summary**: Total events, recording duration, overall health
+3. **Key findings**: Sorted by severity (errors → warnings → info)
+4. **Specific data**: Relevant numbers, event counts, durations
+5. **Recommendations**: Concrete next steps
+
+### Step 6: Cleanup
+
+```bash
+# Remove large trace files when analysis is complete
+# (only if user doesn't need the raw trace)
+rm -rf ./traces/capture.trace
+
+# Keep analysis outputs for reference
+ls -la ./traces/analysis/
+```
+
+### Complete automated workflow example
+
+This is what Claude should execute end-to-end when a user says "profile my Metal app":
+
+```bash
+# Single command: records, exports (parallel), analyzes, and prints results
+cd tools/gpu_trace && uv run gpu_trace run --gpu-counters -- /path/to/app
+
+# Or if the trace was already recorded separately:
+cd tools/gpu_trace && uv run gpu_trace analyze /path/to/capture.trace -v
+```
+
+`gpu_trace run` handles the entire pipeline: Doctor → Record → Export (parallel) → Parse → Analyze → Report. JSON is automatically saved alongside the trace.
+
+For **before/after comparison**:
+
+```bash
+cd tools/gpu_trace
+uv run gpu_trace run -o before.trace -- /path/to/app_before
+# ... make code changes ...
+uv run gpu_trace run -o after.trace -- /path/to/app_after
+uv run gpu_trace compare before.trace after.trace --label1 before --label2 after
+```
+
+### Parallel workflows: Validation + Profiling + Logs
+
+Claude can run multiple debugging streams simultaneously for maximum signal:
+
+```bash
+# Record trace with all validation layers AND HUD logging in one shot
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --env MTL_DEBUG_LAYER=1 \
+ --env MTL_SHADER_VALIDATION=1 \
+ --env MTL_HUD_ENABLED=1 \
+ --env MTL_HUD_LOGGING_ENABLED=1 \
+ --time-limit 10s \
+ --no-prompt \
+ --output ./traces/full_debug.trace \
+ --launch -- /path/to/app 2> ./traces/analysis/stderr.log &
+
+TRACE_PID=$!
+
+# Simultaneously capture Metal logs from unified log
+log stream --predicate 'subsystem == "com.apple.Metal"' \
+ --timeout 15 > ./traces/analysis/metal_log.txt 2>/dev/null &
+
+LOG_PID=$!
+
+# Wait for trace to finish
+wait $TRACE_PID
+
+# Give log stream a moment then stop it
+sleep 2
+kill $LOG_PID 2>/dev/null
+
+# Now analyze ALL data sources:
+echo "=== Validation Errors (stderr) ==="
+grep -i "error\|warning\|invalid\|fault" ./traces/analysis/stderr.log || echo "None"
+
+echo "=== Metal Log Entries ==="
+wc -l < ./traces/analysis/metal_log.txt
+grep -i "error" ./traces/analysis/metal_log.txt || echo "No errors in log"
+
+echo "=== Trace Data ==="
+xcrun xctrace export --input ./traces/full_debug.trace --toc
+```
+
+### Session state awareness
+
+Unlike RenderDoc's daemon model (open/close), xctrace sessions are **fire-and-forget**: each `record` command runs to completion, and the resulting `.trace` file is a self-contained snapshot. This means:
+
+- **No session to manage** — no open/close, no daemon, no leaked processes
+- **Multiple traces can coexist** — name them meaningfully (before.trace, after.trace)
+- **Traces are immutable** — once recorded, they don't change
+- **Export is idempotent** — re-export the same trace as many times as needed
+- **Cleanup is just file deletion** — `rm` the .trace bundle when done
+
+## 2. iOS Device Support
+
+`xctrace` can profile Metal apps on physical iOS/iPadOS devices over USB or Wi-Fi.
+
+### List connected devices
+
+```bash
+xcrun xctrace list devices
+# Shows: Mac, connected iPhones/iPads, simulators
+```
+
+### Record on iOS device
+
+```bash
+# By device name
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --device 'iPhone 15 Pro' \
+ --attach MyApp \
+ --time-limit 10s \
+ --output ios_trace.trace
+
+# By UDID (more reliable)
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --device 00008110-XXXXXXXXXXXX \
+ --attach MyApp \
+ --time-limit 10s \
+ --output ios_trace.trace
+
+# Launch app on device (must be installed)
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --device 'iPhone 15 Pro' \
+ --time-limit 10s \
+ --output ios_trace.trace \
+ --launch -- com.yourcompany.yourapp
+```
+
+### iOS-specific notes
+
+- Device must be **unlocked** and **trusted** by the Mac
+- App must be installed on device (use Xcode or `ios-deploy`)
+- `--launch` uses **bundle identifier** (not path) on iOS
+- `--attach` uses **process name** or PID
+- Export/parse works identically — the `.trace` format is the same
+- Shader compilation for iOS uses `-sdk iphoneos`:
+ ```bash
+ xcrun -sdk iphoneos metal -c Shader.metal -o Shader.air
+ ```
+- `.gputrace` capture on iOS requires Xcode attached to the device
+
+## 3. Metal System Trace — Record & Export
+
+Metal System Trace is the primary tool for GPU profiling. It captures CPU/GPU timeline, driver events, shader execution, and hardware counters.
+
+### Record a trace
+
+```bash
+# Profile a running app by name
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --attach <PID_OR_NAME> \
+ --time-limit 5s \
+ --output trace.trace
+
+# Launch and profile
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --time-limit 5s \
+ --output trace.trace \
+ --launch -- /path/to/your/app [args...]
+
+# With environment variables (e.g., enable validation)
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --env MTL_DEBUG_LAYER=1 \
+ --env MTL_SHADER_VALIDATION=1 \
+ --time-limit 5s \
+ --output trace.trace \
+ --launch -- /path/to/your/app
+```
+
+Key options:
+- `--time-limit 5s` — auto-stop after duration (supports ms, s, m, h)
+- `--attach PID` — attach to running process
+- `--all-processes` — trace all Metal apps system-wide
+- `--env VAR=value` — set environment variables for launched process
+- `--target-stdout -` — redirect app stdout to terminal
+- `--no-prompt` — skip prompts (useful in scripts)
+
+### Other useful templates
+
+```bash
+# List all available templates
+xcrun xctrace list templates
+# Key Metal-relevant templates:
+# - Metal System Trace (GPU timeline, driver events, counters)
+# - Game Performance (Metal + display + thermal)
+# - Counters (hardware performance counters)
+# - GPU (GPU-focused template, if available)
+```
+
+### Export trace data as XML
+
+```bash
+# See what's in the trace (table of contents)
+xcrun xctrace export --input trace.trace --toc
+
+# Export Metal driver events (GPU work intervals, wire memory, etc.)
+xcrun xctrace export --input trace.trace \
+ --xpath '/trace-toc/run[@number="1"]/data/table[@schema="metal-driver-event-intervals"]'
+
+# Export to file instead of stdout
+xcrun xctrace export --input trace.trace \
+ --output metal_events.xml \
+ --xpath '/trace-toc/run[@number="1"]/data/table[@schema="metal-driver-event-intervals"]'
+
+# Export GPU counter data
+xcrun xctrace export --input trace.trace \
+ --xpath '/trace-toc/run[@number="1"]/data/table[@schema="gpu-counter-intervals"]'
+```
+
+### Common Metal table schemas
+
+| Schema | Contains |
+|--------|----------|
+| `metal-driver-event-intervals` | Metal driver events (GPU work, wire memory, resource events) |
+| `gpu-counter-intervals` | Hardware GPU performance counters |
+| `metal-gpu-intervals` | GPU execution intervals per encoder |
+| `time-profile` | CPU time profiling samples |
+
+**TIP**: Always run `--toc` first to see available schemas — they vary by template, Xcode version, and GPU.
+
+### Parse exported XML
+
+The XML uses a reference system to avoid duplication. Nodes with `id` attributes are originals; nodes with `ref` attributes point back to them.
+
+```bash
+# Use gpu_trace to parse all schemas automatically
+cd tools/gpu_trace && uv run gpu_trace analyze trace.trace -v
+
+# Or export to JSON for programmatic access
+cd tools/gpu_trace && uv run gpu_trace analyze trace.trace --json output.json
+```
+
+## 4. Metal Validation Layers
+
+Runtime error detection for Metal API misuse and shader bugs.
+
+### Enable via environment variables
+
+```bash
+# API Validation — catches Metal API misuse
+export MTL_DEBUG_LAYER=1
+
+# Shader Validation — instruments shaders to detect GPU-side errors
+export MTL_SHADER_VALIDATION=1
+
+# Combined: launch app with both
+MTL_DEBUG_LAYER=1 MTL_SHADER_VALIDATION=1 /path/to/your/app
+```
+
+### Enable via xctrace
+
+```bash
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --env MTL_DEBUG_LAYER=1 \
+ --env MTL_SHADER_VALIDATION=1 \
+ --time-limit 10s \
+ --output validated.trace \
+ --launch -- /path/to/your/app
+```
+
+### Read validation errors
+
+Validation errors appear in stderr and in macOS unified log:
+
+```bash
+# Stream Metal validation errors live
+log stream --predicate 'subsystem == "com.apple.Metal"' --level error
+
+# Search recent logs
+log show --predicate 'subsystem == "com.apple.Metal"' --last 5m
+```
+
+### Programmatic validation log access
+
+If you're writing Metal code, `commandBuffer.logs` provides structured error info after completion — encoder label, debug location (file + line), and error classification.
+
+## 5. Metal Performance HUD
+
+Real-time overlay showing FPS, frame time, GPU time, memory usage.
+
+### Enable
+
+```bash
+# Per-process via environment variable
+MTL_HUD_ENABLED=1 /path/to/your/app
+
+# System-wide (all Metal apps)
+/bin/launchctl setenv MTL_HUD_ENABLED 1
+# Disable:
+/bin/launchctl unsetenv MTL_HUD_ENABLED
+
+# Enable HUD data logging to syslog
+MTL_HUD_ENABLED=1 MTL_HUD_LOGGING_ENABLED=1 /path/to/your/app
+```
+
+### Parse HUD log data
+
+When `MTL_HUD_LOGGING_ENABLED=1`, metrics are logged to the system log:
+
+```bash
+# Stream HUD metrics
+log stream --predicate 'subsystem == "com.apple.Metal" AND category == "HUD"'
+
+# Export recent HUD data
+log show --predicate 'subsystem == "com.apple.Metal" AND category == "HUD"' --last 1m
+```
+
+HUD metrics include: FPS, present interval (frame time), GPU time, process memory, GPU memory, display refresh rate, direct vs composited rendering path.
+
+## 6. Programmatic Frame Capture (.gputrace)
+
+Capture Metal frames to `.gputrace` files without Xcode attached, then inspect buffer/texture data from CLI.
+
+### Via environment variables (MoltenVK / any Metal app)
+
+```bash
+# For Vulkan apps via MoltenVK:
+export METAL_CAPTURE_ENABLED=1
+export MVK_CONFIG_AUTO_GPU_CAPTURE_SCOPE=2 # 1=device lifecycle, 2=first frame
+export MVK_CONFIG_AUTO_GPU_CAPTURE_OUTPUT_FILE=/tmp/capture.gputrace
+/path/to/vulkan/app
+
+# For native Metal apps (requires Info.plist MetalCaptureEnabled=true
+# or METAL_CAPTURE_ENABLED=1 environment variable):
+METAL_CAPTURE_ENABLED=1 /path/to/metal/app
+```
+
+### Via MTLCaptureManager (in-app)
+
+For apps you control, add capture support using MTLCaptureManager. See `capture_frame.swift` for a complete example. The key pattern for adding capture to an existing app:
+
+```swift
+let captureManager = MTLCaptureManager.shared()
+if captureManager.supportsDestination(.gpuTraceDocument) {
+ let descriptor = MTLCaptureDescriptor()
+ descriptor.captureObject = device
+ descriptor.destination = .gpuTraceDocument
+ descriptor.outputURL = URL(fileURLWithPath: "./capture.gputrace")
+ try captureManager.startCapture(with: descriptor)
+
+ // ... encode and submit Metal work ...
+
+ captureManager.stopCapture()
+}
+```
+
+Run with: `METAL_CAPTURE_ENABLED=1 ./your_app`
+
+### Open .gputrace in Xcode
+
+```bash
+open /tmp/capture.gputrace
+# Opens in Xcode's Metal Debugger with full inspection capabilities:
+# - Draw call list and stepping
+# - Pipeline state at each draw
+# - Texture/buffer inspection
+# - Shader debugging
+# - Performance profiling
+# - Dependency viewer
+```
+
+### Autonomous Metal Debugging Workflow
+
+When debugging a Metal rendering issue, Claude executes this workflow autonomously. It maximizes signal by gathering data from multiple sources in parallel, then branches based on what data is actually available.
+
+#### Step 1: Gather all signal sources (run in parallel)
+
+Launch these data-gathering steps simultaneously — they are independent:
+
+```bash
+# A. Screenshot the app's rendered output
+./build_and_run.sh --screenshot # preferred: in-app framebuffer readback
+# OR: screencapture -w -x output.png # fallback: macOS window capture
+
+# B. Capture .gputrace (programmatic)
+METAL_CAPTURE_ENABLED=1 ./your_app # produces capture.gputrace
+
+# C. Compile shaders with maximum warnings
+xcrun -sdk macosx metal -c -Weverything Shaders.metal -o /dev/null 2>&1
+
+# D. Read source code — Claude reads .metal files and Swift renderer code directly
+```
+
+#### Step 2: Analyze the capture
+
+```bash
+# 2a. List all resources and shader functions
+cd tools/gpu_trace && uv run gpu_trace capture capture.gputrace
+
+# 2b. Check what data files exist in the capture
+ls capture.gputrace/MTLBuffer-* 2>/dev/null && echo "BUFFER DATA AVAILABLE" || echo "NO BUFFER FILES"
+ls capture.gputrace/MTLTexture-* 2>/dev/null && echo "TEXTURE DATA AVAILABLE" || echo "NO TEXTURE FILES"
+```
+
+**Branch on buffer availability:**
+
+- **MTLBuffer files exist** (Xcode-initiated captures): Parse buffer data directly
+ ```bash
+ cd tools/gpu_trace && uv run gpu_trace capture capture.gputrace --buffer "Vertex" --layout float4 --index 0-10
+ cd tools/gpu_trace && uv run gpu_trace capture capture.gputrace --dump-all
+ ```
+- **No MTLBuffer files** (typical for programmatic captures): Fall back to source code analysis
+ - Read the Swift/ObjC code that creates and fills buffers
+ - Read the `.metal` shader code that consumes the buffers
+ - The capture metadata still tells you what resources exist and what shaders run — use this as an inventory to guide source code reading
+- **MTLTexture files exist**: Read raw texture data for render target analysis
+
+#### Step 3: Diagnose from all available sources
+
+Combine signal from every source gathered in Steps 1–2. Each source catches different bug categories:
+
+| Source | What it reveals | Bug categories |
+|--------|----------------|----------------|
+| **Screenshot** | Visual output | Wrong colors, flipped geometry, missing faces, transparency issues, blank screen |
+| **Source code** (.metal + Swift) | Logic and data flow | Wrong vertex data, shader math errors, incorrect pipeline config, buffer layout mismatches |
+| **Capture metadata** | Resource inventory | Confirms what buffers/textures exist, shader function names, resource labels |
+| **Shader compilation warnings** | Static analysis | Unused variables, implicit conversions, potential precision issues |
+| **Validation errors** (if enabled) | API correctness | Mismatched formats, missing bindings, out-of-bounds access, shader faults |
+
+**Decision logic when buffer data is unavailable:**
+- If no `MTLBuffer` files → Claude reads source code to understand vertex data, uniform values, and buffer layouts
+- If no `MTLTexture` files → Claude uses screenshot for visual inspection of rendered output
+- Programmatic captures always provide: resource labels, shader function names, texture snapshots (render targets)
+
+#### Step 4: Fix and verify
+
+```bash
+# 1. Apply fixes to source code (.metal shaders, Swift renderer)
+
+# 2. Rebuild and screenshot
+./build_and_run.sh --screenshot
+
+# 3. Compare before/after visually (Claude reads output.png)
+
+# 4. If still wrong, repeat from Step 1
+```
+
+The loop continues until the screenshot shows correct output or the user is satisfied.
+
+### Label Injection
+
+Claude should ensure every Metal object has a `.label` set in source code. Labels are preserved in `.gputrace` captures and enable resource identification from CLI.
+
+```swift
+// Add .label to every MTLBuffer, MTLTexture, MTLCommandBuffer, MTLCommandEncoder
+vertexBuffer.label = "Vertex Buffer"
+colorBuffer.label = "Color Buffer"
+uniformBuffer.label = "Uniform Buffer"
+commandBuffer.label = "Frame \(frameNumber)"
+encoder.label = "Main Render Pass"
+```
+
+**Rules:**
+- Use descriptive names with spaces (e.g., "Particle Buffer" not "particleBuf")
+- Labels with spaces are reliably distinguishable from binary data in the `.gputrace`
+- Never remove existing labels — only add missing ones
+- Add labels to every object that lacks one
+
+### Reference: gpu_trace capture usage
+
+```bash
+# List all captured resources with their labels
+cd tools/gpu_trace && uv run gpu_trace capture capture.gputrace
+
+# Read specific buffer by label (partial match works)
+cd tools/gpu_trace && uv run gpu_trace capture capture.gputrace --buffer "Color Output" --layout float4 --index 100
+
+# Read compound struct (e.g., Particle = position + velocity + color)
+cd tools/gpu_trace && uv run gpu_trace capture capture.gputrace --buffer "Particle" --layout "float4,float4,float4" --index 0-10
+
+# Dump summary statistics for all buffers
+cd tools/gpu_trace && uv run gpu_trace capture capture.gputrace --dump-all
+
+# Output as JSON
+cd tools/gpu_trace && uv run gpu_trace capture capture.gputrace --buffer "Color Output" --layout float4 --index 100 --json
+```
+
+#### Supported layout types
+
+| Layout | Bytes | Example |
+|--------|-------|---------|
+| `float` | 4 | Scalar energy, distance, time |
+| `float2` | 8 | UV coordinates |
+| `float3` | 12 | Position, normal (without padding) |
+| `float4` | 16 | RGBA color, position+mass, SIMD4 |
+| `uint32` | 4 | Index, count |
+| `int32` | 4 | Signed integer |
+| `half4` | 8 | Half-precision RGBA |
+| `float4,float4,float4` | 48 | Compound struct (e.g., Particle) |
+
+### Reference: .gputrace internal structure
+
+| File | Format | Contents |
+|------|--------|----------|
+| `MTLBuffer-{id}-{snap}` | Raw binary (IEEE 754 LE) | GPU buffer memory snapshot |
+| `MTLTexture-{id}-{snap}` | Raw binary | GPU texture memory snapshot |
+| `metadata` | Binary plist | Session UUID, API, device info |
+| `device-resources-*` | MTSP binary | Resource registry with labels, shader names |
+| `store0` | zlib-compressed MTSP | Encoded command buffer data |
+| `capture` / `unsorted-capture` | MTSP binary | Metal API call sequences |
+| `index` | Custom (`xdic` magic) | File table / hash table |
+
+### Reference: CLI capabilities by capture type
+
+| Capability | CLI (programmatic capture) | CLI (Xcode-initiated capture) | Xcode GUI |
+|-----------|---------------------------|------------------------------|-----------|
+| List resources with labels | ✅ | ✅ | ✅ |
+| List shader function names | ✅ | ✅ | ✅ |
+| Read texture/render target data | ✅ (MTLTexture files present) | ✅ | ✅ |
+| Read buffer contents at index | ❌ (no MTLBuffer files) | ✅ | ✅ |
+| Buffer statistics (min/max/mean) | ❌ | ✅ | ❌ (manual) |
+| Draw call stepping | ❌ | ❌ | ✅ |
+| Pixel history | ❌ | ❌ | ✅ |
+| Shader step-through | ❌ | ❌ | ✅ |
+| Pipeline state inspection | ❌ | ❌ | ✅ |
+| Dependency viewer | ❌ | ❌ | ✅ |
+| Command buffer replay | ❌ | ❌ | ✅ |
+
+### Reference: Screenshot capture techniques
+
+#### Method 1: In-app auto-screenshot (Preferred)
+
+The most reliable approach is to add a `--screenshot` mode to the app itself. This renders a few frames, reads back the framebuffer texture, and saves it as a PNG — no external tools required.
+
+**Swift code to add to your Metal app:**
+
+```swift
+// Add to your renderer class:
+static func saveTexture(_ texture: MTLTexture, to path: String) {
+ let w = texture.width, h = texture.height
+ let bytesPerRow = w * 4
+ var pixels = [UInt8](repeating: 0, count: h * bytesPerRow)
+ texture.getBytes(&pixels, bytesPerRow: bytesPerRow,
+ from: MTLRegion(origin: MTLOrigin(), size: MTLSize(width: w, height: h, depth: 1)),
+ mipmapLevel: 0)
+ // BGRA → RGBA, force alpha to 255 for screenshot visibility
+ for i in stride(from: 0, to: pixels.count, by: 4) {
+ let tmp = pixels[i]
+ pixels[i] = pixels[i + 2]
+ pixels[i + 2] = tmp
+ pixels[i + 3] = 255
+ }
+ let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: w, pixelsHigh: h,
+ bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true,
+ isPlanar: false, colorSpaceName: .deviceRGB,
+ bytesPerRow: bytesPerRow, bitsPerPixel: 32)!
+ memcpy(rep.bitmapData!, &pixels, pixels.count)
+ let data = rep.representation(using: .png, properties: [:])!
+ try! data.write(to: URL(fileURLWithPath: path))
+}
+```
+
+**Usage in the draw loop** (save after a few frames, then exit):
+
+```swift
+// In draw(in:) after cb.present(drawable) and cb.commit():
+if frameCount == 3 && screenshotMode {
+ cb.waitUntilCompleted()
+ Self.saveTexture(drawable.texture, to: "./output.png")
+ print("Screenshot saved: ./output.png")
+ DispatchQueue.main.async { NSApp.terminate(nil) }
+}
+```
+
+**Important**: Set `metalView.framebufferOnly = false` before rendering to allow texture readback.
+
+#### Method 2: macOS screencapture (Fallback)
+
+If the app doesn't support `--screenshot`, use macOS `screencapture` to capture the window:
+
+```bash
+# Launch the app in background
+./your_app &
+APP_PID=$!
+sleep 1
+
+# Capture the app's window (-w = frontmost window, -x = no sound)
+screencapture -w -x /tmp/screenshot.png
+
+# Stop the app
+kill $APP_PID 2>/dev/null
+```
+
+## 7. Metal Shader Compilation
+
+Compile, validate, and inspect Metal shaders from the command line.
+
+### Compile shaders
+
+```bash
+# Compile .metal to intermediate representation (.air)
+xcrun -sdk macosx metal -c MyShader.metal -o MyShader.air
+
+# With warnings and debug info
+xcrun -sdk macosx metal -c -gline-tables-only -Weverything MyShader.metal -o MyShader.air
+
+# Archive
+xcrun -sdk macosx metal-ar rcs MyShader.metalar MyShader.air
+
+# Link into a Metal library (.metallib)
+xcrun -sdk macosx metallib MyShader.metalar -o MyShader.metallib
+
+# One-step compile + link
+xcrun -sdk macosx metal MyShader.metal -o MyShader.metallib
+```
+
+### Cross-compile for specific targets
+
+```bash
+# List available GPU architectures
+xcrun metal-arch
+
+# Target specific platform
+xcrun -sdk iphoneos metal -c Shader.metal -o Shader.air
+xcrun -sdk macosx metal -c -target air64-apple-macos14 Shader.metal -o Shader.air
+```
+
+### HLSL to Metal (via shader converter)
+
+```bash
+# Convert HLSL → DXIL → Metal IR
+dxc shaders.hlsl -T vs_6_0 -E MainVS -Fo vertex.dxil
+metal-shaderconverter vertex.dxil -o vertex.metallib
+```
+
+### Validate shaders without running
+
+```bash
+# Compile with all warnings — catches issues at build time
+xcrun -sdk macosx metal -c -Weverything -Werror MyShader.metal -o /dev/null
+
+# Check Metal version compatibility
+xcrun -sdk macosx metal -c -std=metal3.0 MyShader.metal -o /dev/null
+```
+
+## 8. GPU Device Information
+
+```bash
+# System-level GPU info
+system_profiler SPDisplaysDataType
+
+# Metal feature set / GPU family (grep for relevant info)
+system_profiler SPDisplaysDataType | grep -E "Chipset|Metal|VRAM|GPU"
+```
+
+## 9. Debugging Recipes
+
+### Recipe: Profile GPU performance
+
+```bash
+# 1. Record a Metal System Trace
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --time-limit 10s \
+ --output perf.trace \
+ --launch -- /path/to/app
+
+# 2. See what data is available
+xcrun xctrace export --input perf.trace --toc
+
+# 3. Export GPU driver events
+xcrun xctrace export --input perf.trace \
+ --output gpu_events.xml \
+ --xpath '/trace-toc/run[@number="1"]/data/table[@schema="metal-driver-event-intervals"]'
+
+# 4. Export GPU counters (if available)
+xcrun xctrace export --input perf.trace \
+ --output gpu_counters.xml \
+ --xpath '/trace-toc/run[@number="1"]/data/table[@schema="gpu-counter-intervals"]'
+
+# 5. Open in Instruments for visual analysis
+open perf.trace
+```
+
+### Recipe: Find shader compilation errors
+
+```bash
+# 1. Compile with maximum warnings
+xcrun -sdk macosx metal -c -Weverything -Werror MyShader.metal -o /dev/null 2>&1
+
+# 2. If it compiles, check at runtime with validation
+MTL_SHADER_VALIDATION=1 /path/to/app 2>&1 | tee shader_errors.log
+
+# 3. Check logs for shader validation errors
+log show --predicate 'subsystem == "com.apple.Metal"' --last 5m --level error
+```
+
+### Recipe: Detect Metal API misuse
+
+```bash
+# 1. Run with API validation
+MTL_DEBUG_LAYER=1 /path/to/app 2>&1 | tee api_errors.log
+
+# 2. Record with validation for post-mortem analysis
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --env MTL_DEBUG_LAYER=1 \
+ --time-limit 10s \
+ --output validated.trace \
+ --launch -- /path/to/app
+
+# 3. Check for errors
+grep -i "error\|warning\|invalid\|violation" api_errors.log
+```
+
+### Recipe: Monitor real-time performance
+
+```bash
+# 1. Enable HUD with logging
+MTL_HUD_ENABLED=1 MTL_HUD_LOGGING_ENABLED=1 /path/to/app &
+APP_PID=$!
+
+# 2. Stream performance data
+log stream --predicate 'subsystem == "com.apple.Metal" AND category == "HUD"' &
+
+# 3. When done, stop
+kill $APP_PID
+```
+
+### Recipe: Capture a frame for Xcode debugging
+
+```bash
+# For Vulkan apps (via MoltenVK)
+METAL_CAPTURE_ENABLED=1 \
+MVK_CONFIG_AUTO_GPU_CAPTURE_SCOPE=2 \
+MVK_CONFIG_AUTO_GPU_CAPTURE_OUTPUT_FILE=/tmp/frame.gputrace \
+/path/to/vulkan/app
+
+# Open in Xcode Metal Debugger
+open /tmp/frame.gputrace
+```
+
+### Recipe: Debug Metal rendering issues (visual + data)
+
+Use the **Autonomous Metal Debugging Workflow** in Section 6. It covers screenshot capture, .gputrace analysis, source code reading, shader compilation, and the fix/verify loop — with fallbacks when buffer data is unavailable.
+
+### Recipe: Compare performance before/after a change
+
+```bash
+# 1. Record baseline
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --time-limit 10s \
+ --output before.trace \
+ --launch -- /path/to/app
+
+# 2. Make your change, rebuild
+
+# 3. Record after
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --time-limit 10s \
+ --output after.trace \
+ --launch -- /path/to/app
+
+# 4. Export both and compare
+xcrun xctrace export --input before.trace --output before.xml \
+ --xpath '/trace-toc/run[@number="1"]/data/table[@schema="metal-driver-event-intervals"]'
+xcrun xctrace export --input after.trace --output after.xml \
+ --xpath '/trace-toc/run[@number="1"]/data/table[@schema="metal-driver-event-intervals"]'
+
+# 5. Diff the XML or parse with Python for numerical comparison
+```
+
+## 10. Output Size Management
+
+Metal System Traces can be very large. Follow these rules:
+
+1. **Use `--time-limit`**: Always limit recording duration (5-10s is usually enough)
+2. **Export specific schemas**: Use `--xpath` to extract only the data you need
+3. **Use `--toc` first**: Understand what's in the trace before bulk-exporting
+4. **Pipe through filters**: Use `grep`, `xmllint`, or Python to extract specific data
+5. **Clean up traces**: `.trace` bundles can be 100MB+; delete when done
+
+## 11. Limitations vs RenderDoc
+
+| Capability | Metal Skill | RenderDoc Skill |
+|-----------|-------------|-----------------|
+| Frame capture | ✅ .gputrace | ✅ .rdc (full CLI) |
+| GPU profiling | ✅ xctrace + export | ⚠️ GPU counters if available |
+| Shader compilation | ✅ xcrun metal | N/A (different workflow) |
+| Validation errors | ✅ env vars + log stream | ✅ API validation layer |
+| Performance HUD | ✅ MTL_HUD_ENABLED | N/A |
+| Buffer inspection (CLI) | ⚠️ Xcode-initiated captures only | ✅ rdc buffer |
+| Buffer statistics | ⚠️ Xcode-initiated captures only | ❌ |
+| Draw call inspection | ❌ Xcode only | ✅ rdc draws/pipeline |
+| Pixel history | ❌ Xcode only | ✅ rdc pixel |
+| Shader step-through | ❌ Xcode only | ✅ rdc debug pixel |
+| Render target export | ❌ Xcode only | ✅ rdc rt → PNG |
+| Texture readback (CLI) | ⚠️ MTLTexture files (if present) | ✅ Full rdc-cli API |
+| Visual output inspection | ✅ in-app saveTexture or screencapture | ❌ (headless only) |
+
+**Key difference**: Metal debugging is split between CLI (profiling/validation/buffer inspection) and GUI (Xcode for draw calls, pixel history, shader debugging). The `gpu_trace capture` command partially bridges this gap by enabling CLI buffer/texture data inspection from `.gputrace` captures. RenderDoc still provides more complete CLI access.
+
+## Command Reference
+
+For the complete xctrace command reference, see [references/xctrace-quick-ref.md](references/xctrace-quick-ref.md).
+
+For extended debugging recipes, see [references/debugging-recipes.md](references/debugging-recipes.md).
diff --git a/agents/skills/metal-gpu-debug/references/debugging-recipes.md b/agents/skills/metal-gpu-debug/references/debugging-recipes.md
new file mode 100644
index 000000000..ab5d234f9
--- /dev/null
+++ b/agents/skills/metal-gpu-debug/references/debugging-recipes.md
@@ -0,0 +1,361 @@
+# Metal GPU Debugging Recipes
+
+Extended debugging workflows with expected outputs and step-by-step procedures.
+
+## Recipe 1: GPU Performance Profiling
+
+**Symptoms**: Low FPS, high frame time, stuttering, thermal throttling.
+
+### Step-by-step
+
+```bash
+# 1. Record and analyze in one step (with hardware counters)
+cd tools/gpu_trace && uv run gpu_trace run --gpu-counters --time-limit 10s -- /path/to/app
+
+# Or analyze a pre-recorded trace:
+cd tools/gpu_trace && uv run gpu_trace analyze perf.trace -v
+
+# Export to JSON for custom analysis:
+cd tools/gpu_trace && uv run gpu_trace analyze perf.trace --json perf.json
+
+# Open in Instruments for visual timeline
+open perf.trace
+```
+
+`gpu_trace` automatically exports all schemas in parallel, parses the XML, computes per-kernel timing, correlates hardware counters, and detects bottlenecks.
+
+**Performance red flags:**
+- GPU busy time > 16ms per frame (60fps target) or > 8ms (120fps target)
+- Wire memory events with large sizes (indicates heavy resource allocation per frame)
+- Shader execution intervals dominating GPU timeline (complex shaders)
+- Gaps between GPU submissions (CPU bottleneck)
+
+---
+
+## Recipe 2: Shader Compilation Errors
+
+**Symptoms**: App crashes on launch, black screen, missing effects.
+
+### Step-by-step
+
+```bash
+# 1. Compile shader with maximum diagnostics
+xcrun -sdk macosx metal -c \
+ -gline-tables-only \
+ -Weverything \
+ -Werror \
+ MyShader.metal -o /dev/null 2>&1
+```
+
+**Expected error output:**
+```
+MyShader.metal:42:15: error: use of undeclared identifier 'baseColor'
+ float4 c = baseColor * albedo;
+ ^
+MyShader.metal:18:3: warning: unused variable 'temp' [-Wunused-variable]
+ float temp = 0.0;
+ ^
+```
+
+```bash
+# 2. If compile succeeds but runtime fails, check Metal version
+xcrun -sdk macosx metal -c -std=metal3.0 MyShader.metal -o /dev/null 2>&1
+
+# 3. Check for runtime shader errors
+MTL_SHADER_VALIDATION=1 /path/to/app 2>&1 | head -100
+
+# 4. Stream shader validation errors
+log stream --predicate 'subsystem == "com.apple.Metal"' --level error &
+MTL_SHADER_VALIDATION=1 /path/to/app
+
+# 5. Build the full pipeline: .metal → .air → .metalar → .metallib
+xcrun -sdk macosx metal -c -gline-tables-only MyShader.metal -o MyShader.air
+xcrun -sdk macosx metal-ar rcs MyShader.metalar MyShader.air
+xcrun -sdk macosx metallib MyShader.metalar -o MyShader.metallib
+echo "Shader library built successfully: MyShader.metallib"
+```
+
+**Common shader errors:**
+| Error | Cause | Fix |
+|-------|-------|-----|
+| undeclared identifier | Missing variable/function | Check spelling, includes, scope |
+| no matching function | Wrong argument types | Verify types match function signature |
+| cannot convert | Type mismatch | Use explicit casts (float4, half4, etc.) |
+| address space mismatch | Wrong buffer qualifier | Check device/constant/threadgroup qualifiers |
+| exceeds max total threads | Threadgroup size too large | Reduce threadgroup dimensions |
+
+---
+
+## Recipe 3: Metal API Validation Errors
+
+**Symptoms**: Crashes, undefined behavior, incorrect rendering.
+
+### Step-by-step
+
+```bash
+# 1. Run with full API validation
+MTL_DEBUG_LAYER=1 /path/to/app 2>&1 | tee validation.log
+
+# 2. Check for errors
+grep -i "error\|warning\|invalid\|violation\|failed" validation.log
+
+# 3. For deeper validation, add shader validation too
+MTL_DEBUG_LAYER=1 MTL_SHADER_VALIDATION=1 /path/to/app 2>&1 | tee full_validation.log
+
+# 4. Stream structured Metal log data
+log stream --predicate 'subsystem == "com.apple.Metal"' --level error
+```
+
+**Expected validation error format:**
+```
+-[MTLDebugRenderCommandEncoder setVertexBuffer:offset:atIndex:]:
+ Execution of the command buffer was aborted due to an error during execution.
+ Caused GPU Address Fault (0x00000001)
+```
+
+**Common validation issues:**
+| Error Pattern | Meaning | Fix |
+|--------------|---------|-----|
+| GPU Address Fault | Out-of-bounds buffer access | Check buffer sizes, offsets |
+| Shader Validation Error | GPU-side out-of-bounds or race | Check array indices, threadgroup sync |
+| Invalid Resource | Using deleted/nil resource | Check resource lifetimes |
+| Incompatible Pixel Format | Format mismatch | Verify texture formats match pipeline |
+| Exceeded max | Resource limit hit | Reduce resource usage |
+
+---
+
+## Recipe 4: Real-Time Performance Monitoring
+
+**Symptoms**: Need ongoing performance data during development.
+
+### Step-by-step
+
+```bash
+# 1. Launch app with HUD and logging
+MTL_HUD_ENABLED=1 MTL_HUD_LOGGING_ENABLED=1 /path/to/app &
+APP_PID=$!
+
+# 2. Collect HUD data for analysis
+log show --predicate 'subsystem == "com.apple.Metal" AND category == "HUD"' \
+ --last 30s > hud_data.log
+
+# 3. Parse HUD log for key metrics
+python3 << 'EOF'
+import re
+
+with open('hud_data.log') as f:
+ for line in f:
+ # Extract FPS, GPU time, memory from HUD log entries
+ if 'FPS' in line or 'GPU' in line or 'Memory' in line:
+ print(line.strip())
+EOF
+
+# 4. When done
+kill $APP_PID
+```
+
+**HUD overlay shows:**
+- FPS (frames per second)
+- Present interval / frame time (ms)
+- GPU time (ms)
+- Process memory (MB)
+- GPU memory (MB)
+- Display refresh rate
+- Rendering path (direct vs composited)
+
+---
+
+## Recipe 5: Frame Capture for Xcode Debugging
+
+**Symptoms**: Visual bugs that need draw-call-level inspection.
+
+### For native Metal apps
+
+```bash
+# 1. Ensure capture is enabled (one of):
+# a) Set METAL_CAPTURE_ENABLED=1 environment variable
+# b) Add MetalCaptureEnabled=true to Info.plist
+# c) Use MTLCaptureManager in code
+
+# 2. For MoltenVK / Vulkan apps:
+METAL_CAPTURE_ENABLED=1 \
+MVK_CONFIG_AUTO_GPU_CAPTURE_SCOPE=2 \
+MVK_CONFIG_AUTO_GPU_CAPTURE_OUTPUT_FILE=/tmp/capture.gputrace \
+/path/to/vulkan/app
+
+# 3. Wait for capture to complete (app will likely freeze briefly)
+echo "Capture saved to /tmp/capture.gputrace"
+
+# 4. Open in Xcode
+open /tmp/capture.gputrace
+```
+
+**In Xcode Metal Debugger you can:**
+- Step through draw calls
+- Inspect pipeline state at any draw
+- View bound textures and buffers
+- Debug shaders line-by-line
+- Check pixel history
+- View GPU timeline
+- Inspect acceleration structures (ray tracing)
+- Analyze memory usage
+
+---
+
+## Recipe 6: Compare Performance Across Changes
+
+**Symptoms**: Need to verify a change improved or didn't regress performance.
+
+### Step-by-step
+
+```bash
+# 1. Record baseline
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --time-limit 10s \
+ --no-prompt \
+ --output baseline.trace \
+ --launch -- /path/to/app_before
+
+# 2. Record after changes
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --time-limit 10s \
+ --no-prompt \
+ --output changed.trace \
+ --launch -- /path/to/app_after
+
+# 3. Export both
+for trace in baseline changed; do
+ xcrun xctrace export \
+ --input ${trace}.trace \
+ --output ${trace}_events.xml \
+ --xpath '/trace-toc/run[@number="1"]/data/table[@schema="metal-driver-event-intervals"]'
+done
+
+# 4. Compare with Python
+python3 << 'EOF'
+import xml.etree.ElementTree as ET
+
+def count_events(xmlfile):
+ tree = ET.parse(xmlfile)
+ rows = tree.getroot().findall('.//row')
+ return len(rows)
+
+baseline = count_events('baseline_events.xml')
+changed = count_events('changed_events.xml')
+
+print(f"Baseline: {baseline} events")
+print(f"Changed: {changed} events")
+print(f"Delta: {changed - baseline:+d} events ({(changed/baseline - 1)*100:+.1f}%)")
+EOF
+```
+
+---
+
+## Recipe 7: Debug Vulkan App on macOS via MoltenVK
+
+**Symptoms**: Vulkan app has issues only on macOS.
+
+### Step-by-step
+
+```bash
+# 1. Enable MoltenVK logging
+export MVK_CONFIG_LOG_LEVEL=3 # 0=off, 1=error, 2=warning, 3=info, 4=debug
+
+# 2. Run with Metal validation
+MTL_DEBUG_LAYER=1 \
+MTL_SHADER_VALIDATION=1 \
+MVK_CONFIG_LOG_LEVEL=3 \
+/path/to/vulkan/app 2>&1 | tee moltenvk.log
+
+# 3. Capture a frame for Xcode debugging
+METAL_CAPTURE_ENABLED=1 \
+MVK_CONFIG_AUTO_GPU_CAPTURE_SCOPE=2 \
+MVK_CONFIG_AUTO_GPU_CAPTURE_OUTPUT_FILE=/tmp/vk_capture.gputrace \
+/path/to/vulkan/app
+
+# 4. Profile with xctrace
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --env MVK_CONFIG_LOG_LEVEL=3 \
+ --time-limit 10s \
+ --output vk_trace.trace \
+ --launch -- /path/to/vulkan/app
+
+# 5. Open trace or capture
+open /tmp/vk_capture.gputrace # For state debugging
+open vk_trace.trace # For profiling
+```
+
+---
+
+## Recipe 8: Profile an iOS Device
+
+**Symptoms**: Need to profile Metal performance on a physical iPhone/iPad.
+
+### Step-by-step
+
+```bash
+# 1. List connected devices
+xcrun xctrace list devices
+# Look for your device name and UDID
+
+# 2. Record (app must be running or installed on device)
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --device 'iPhone 15 Pro' \
+ --attach MyApp \
+ --time-limit 10s \
+ --output ios_profile.trace
+
+# 3. Export and analyze — same as macOS
+xcrun xctrace export --input ios_profile.trace --toc
+
+xcrun xctrace export --input ios_profile.trace \
+ --output ios_gpu_events.xml \
+ --xpath '/trace-toc/run[@number="1"]/data/table[@schema="metal-driver-event-intervals"]'
+
+# 4. Parse with gpu_trace
+cd tools/gpu_trace && uv run gpu_trace analyze ios_profile.trace -v
+
+# 5. Or open in Instruments
+open ios_profile.trace
+```
+
+**iOS-specific tips:**
+- Device must be unlocked and trusted
+- Use `--attach` with process name for already-running apps
+- Use `--launch com.bundle.id` to launch and trace
+- Apple Silicon iPhones (A14+) have rich GPU counters
+- Thermal throttling is more common on iOS — check for performance drops over time
+
+---
+
+## Recipe 9: System-Wide GPU Monitoring
+
+**Symptoms**: Need to identify which process is consuming GPU resources.
+
+### Step-by-step
+
+```bash
+# 1. Trace all processes
+xcrun xctrace record \
+ --template 'Metal System Trace' \
+ --all-processes \
+ --time-limit 10s \
+ --output system.trace
+
+# 2. Check which processes are in the trace
+xcrun xctrace export --input system.trace \
+ --xpath '/trace-toc/run[@number="1"]/processes'
+
+# 3. Export GPU events for a specific process
+# (after identifying process name from step 2)
+xcrun xctrace export --input system.trace \
+ --xpath '/trace-toc/run[@number="1"]/data/table[@schema="metal-driver-event-intervals"]' \
+ --output all_gpu.xml
+
+# 4. Open in Instruments for per-process breakdown
+open system.trace
+```
diff --git a/agents/skills/metal-gpu-debug/references/xctrace-quick-ref.md b/agents/skills/metal-gpu-debug/references/xctrace-quick-ref.md
new file mode 100644
index 000000000..add29df94
--- /dev/null
+++ b/agents/skills/metal-gpu-debug/references/xctrace-quick-ref.md
@@ -0,0 +1,213 @@
+# xctrace Command Quick Reference
+
+## `xctrace record`
+
+Record an Instruments trace.
+
+**Options:**
+
+| Flag | Help | Type | Default |
+|------|------|------|---------|
+| `--template` | Template name or path | text | (required) |
+| `--output` | Output .trace path | path | auto-generated |
+| `--device` | Device name or UDID | text | local |
+| `--time-limit` | Max recording time (e.g., 5s, 1m) | duration | unlimited |
+| `--all-processes` | Trace all processes | flag | |
+| `--attach` | Attach to PID or process name | text | |
+| `--launch` | Launch and trace command (must be last) | command | |
+| `--target-stdin` | Redirect stdin (- or file) | text | |
+| `--target-stdout` | Redirect stdout (- or file) | text | |
+| `--env` | Set env var for launched process (VAR=value) | text | |
+| `--package` | Install Instruments Package for duration | file | |
+| `--no-prompt` | Skip confirmation prompts | flag | |
+| `--notify-tracing-started` | Send Darwin notification when started | text | |
+| `--append-run` | Append run to existing trace | flag | |
+| `--window` | Windowed (ring buffer) mode | duration | |
+
+## `xctrace export`
+
+Export data from a .trace file to XML.
+
+**Options:**
+
+| Flag | Help | Type | Default |
+|------|------|------|---------|
+| `--input` | Input .trace file | file | (required) |
+| `--output` | Output file (default: stdout) | path | stdout |
+| `--toc` | Export table of contents | flag | |
+| `--xpath` | XPath query to select export entities | expression | |
+| `--har` | Export as HTTP Archive (if HTTP Traffic present) | flag | |
+
+### XPath patterns for Metal data
+
+```bash
+# Table of contents (always start here)
+--toc
+
+# Metal driver events (GPU work intervals, wire memory)
+--xpath '/trace-toc/run[@number="1"]/data/table[@schema="metal-driver-event-intervals"]'
+
+# GPU hardware counters
+--xpath '/trace-toc/run[@number="1"]/data/table[@schema="gpu-counter-intervals"]'
+
+# Metal GPU execution intervals
+--xpath '/trace-toc/run[@number="1"]/data/table[@schema="metal-gpu-intervals"]'
+
+# CPU time profile
+--xpath '/trace-toc/run[@number="1"]/data/table[@schema="time-profile"]'
+
+# All tables in first run
+--xpath '/trace-toc/run[@number="1"]/data/table'
+
+# Process info
+--xpath '/trace-toc/run[@number="1"]/processes'
+
+# Specific process
+--xpath '/trace-toc/run[@number="1"]/processes/process[@name="MyApp"]'
+```
+
+**NOTE**: Available schemas vary by template, Xcode version, and GPU. Always check `--toc` first.
+
+## `xctrace import`
+
+Import supported file formats into .trace.
+
+**Options:**
+
+| Flag | Help | Type | Default |
+|------|------|------|---------|
+| `--input` | Input file to import | file | (required) |
+| `--output` | Output .trace path | path | auto-generated |
+| `--template` | Template for import | text | |
+| `--package` | Instruments Package for import | file | |
+
+## `xctrace remodel`
+
+Remodel trace using installed packages.
+
+**Options:**
+
+| Flag | Help | Type | Default |
+|------|------|------|---------|
+| `--input` | Input .trace file | file | (required) |
+| `--output` | Output .trace path | path | |
+| `--package` | Instruments Package | file | |
+
+## `xctrace symbolicate`
+
+Symbolicate a trace file.
+
+**Options:**
+
+| Flag | Help | Type | Default |
+|------|------|------|---------|
+| `--input` | Input .trace file | file | (required) |
+| `--output` | Output .trace path | path | |
+| `--dsym` | Debug symbols file | file | |
+
+## `xctrace list`
+
+List available resources.
+
+**Subcommands:**
+
+| Subcommand | Description |
+|-----------|-------------|
+| `devices` | List available devices |
+| `templates` | List available recording templates |
+| `instruments` | List available instruments |
+
+## Metal Shader Toolchain Commands
+
+### `xcrun metal`
+
+Metal shader compiler.
+
+| Flag | Help |
+|------|------|
+| `-c` | Compile to .air (intermediate representation) |
+| `-o` | Output file path |
+| `-sdk macosx` | Target macOS SDK (also: iphoneos, appletvos) |
+| `-target air64-apple-macos14` | Target specific platform/version |
+| `-std=metal3.0` | Metal language standard version |
+| `-gline-tables-only` | Generate line-level debug info |
+| `-Weverything` | Enable all warnings |
+| `-Werror` | Treat warnings as errors |
+| `-I <path>` | Add include search path |
+| `-D <macro>` | Define preprocessor macro |
+
+### `xcrun metal-ar`
+
+Metal archive tool (create static libraries of .air files).
+
+```bash
+xcrun -sdk macosx metal-ar rcs output.metalar input1.air input2.air
+```
+
+### `xcrun metallib`
+
+Metal linker (create .metallib from .air or .metalar).
+
+```bash
+xcrun -sdk macosx metallib input.metalar -o output.metallib
+```
+
+### `xcrun metal-arch`
+
+List available Metal GPU architecture targets.
+
+### `metal-shaderconverter`
+
+Convert HLSL (via DXIL) to Metal IR.
+
+```bash
+metal-shaderconverter input.dxil -o output.metallib
+```
+
+## Metal Environment Variables
+
+### Debugging
+
+| Variable | Values | Effect |
+|----------|--------|--------|
+| `MTL_DEBUG_LAYER` | 1 | Enable API validation layer |
+| `MTL_SHADER_VALIDATION` | 1 | Enable GPU shader validation |
+| `METAL_CAPTURE_ENABLED` | 1 | Allow programmatic .gputrace capture |
+| `METAL_DEVICE_WRAPPER_TYPE` | 1 | Enable Metal device wrapper (extended validation) |
+
+### Performance HUD
+
+| Variable | Values | Effect |
+|----------|--------|--------|
+| `MTL_HUD_ENABLED` | 1 | Show performance overlay |
+| `MTL_HUD_LOGGING_ENABLED` | 1 | Log HUD metrics to system log |
+
+### MoltenVK (Vulkan apps)
+
+| Variable | Values | Effect |
+|----------|--------|--------|
+| `MVK_CONFIG_AUTO_GPU_CAPTURE_SCOPE` | 1=device, 2=first frame | Auto-capture scope |
+| `MVK_CONFIG_AUTO_GPU_CAPTURE_OUTPUT_FILE` | path | .gputrace output path |
+| `MVK_CONFIG_LOG_LEVEL` | 0-4 | MoltenVK logging verbosity |
+
+## macOS Log Commands for Metal
+
+```bash
+# Stream Metal errors live
+log stream --predicate 'subsystem == "com.apple.Metal"' --level error
+
+# Stream all Metal messages
+log stream --predicate 'subsystem == "com.apple.Metal"'
+
+# Stream HUD performance data
+log stream --predicate 'subsystem == "com.apple.Metal" AND category == "HUD"'
+
+# Show recent Metal errors
+log show --predicate 'subsystem == "com.apple.Metal"' --last 5m --level error
+
+# Show recent Metal messages (all levels)
+log show --predicate 'subsystem == "com.apple.Metal"' --last 5m
+
+# Export to file
+log show --predicate 'subsystem == "com.apple.Metal"' --last 10m > metal_log.txt
+```
diff --git a/tools/gpu_trace/src/gpu_trace/extractors.py b/tools/gpu_trace/src/gpu_trace/extractors.py
index b84eaba5c..8ad125cc4 100644
--- a/tools/gpu_trace/src/gpu_trace/extractors.py
+++ b/tools/gpu_trace/src/gpu_trace/extractors.py
@@ -3,6 +3,8 @@ from __future__ import annotations
import bisect
import subprocess
import xml.etree.ElementTree as ET
+from concurrent.futures import ThreadPoolExecutor
+from functools import lru_cache
from pathlib import Path
from .models import (
@@ -63,15 +65,48 @@ def _resolve_text(el: ET.Element | None, id_to_text: dict[str, str]) -> str | No
return id_to_text.get(ref) if ref else None
+# Cache TOC parsing — avoids redundant xctrace subprocess calls across
+# extract_metadata, extract_gpu_utilization, extract_kernel_dispatches, etc.
+@lru_cache(maxsize=4)
def _toc_root(trace: Path) -> ET.Element:
xml = _check_output(_xctrace_cmd("export", "--input", str(trace), "--toc"))
return ET.fromstring(xml)
+_export_cache: dict[tuple[str, int, str], ET.Element] = {}
+
+
def _export_table(trace: Path, run_number: int, schema: str) -> ET.Element:
+ key = (str(trace), run_number, schema)
+ cached = _export_cache.get(key)
+ if cached is not None:
+ return cached
xpath = f'/trace-toc/run[@number="{run_number}"]/data/table[@schema="{schema}"]'
xml = _check_output(_xctrace_cmd("export", "--input", str(trace), "--xpath", xpath))
- return ET.fromstring(xml)
+ result = ET.fromstring(xml)
+ _export_cache[key] = result
+ return result
+
+
+def export_tables_parallel(
+ trace: Path, run_number: int, schemas: list[str]
+) -> dict[str, ET.Element | None]:
+ """Export multiple schemas in parallel via ThreadPoolExecutor.
+
+ Returns {schema: ET.Element | None} — None for schemas that failed.
+ """
+
+ def _export_one(schema: str) -> tuple[str, ET.Element | None]:
+ try:
+ return schema, _export_table(trace, run_number, schema)
+ except subprocess.CalledProcessError:
+ return schema, None
+
+ results: dict[str, ET.Element | None] = {}
+ with ThreadPoolExecutor(max_workers=len(schemas)) as pool:
+ for schema, root in pool.map(_export_one, schemas):
+ results[schema] = root
+ return results
def _union_ns(intervals: list[tuple[int, int]]) -> int:
@@ -90,8 +125,8 @@ def _union_ns(intervals: list[tuple[int, int]]) -> int:
return total
-def extract_metadata(trace: Path, run_number: int) -> TraceMetadata:
- toc = _toc_root(trace)
+def extract_metadata_from_toc(toc: ET.Element, run_number: int) -> TraceMetadata:
+ """Extract metadata from an already-parsed TOC element."""
run = toc.find(f".//run[@number='{run_number}']")
if run is None:
raise ValueError(f"Run {run_number} not found in trace TOC")
@@ -136,6 +171,11 @@ def extract_metadata(trace: Path, run_number: int) -> TraceMetadata:
)
+def extract_metadata(trace: Path, run_number: int) -> TraceMetadata:
+ toc = _toc_root(trace)
+ return extract_metadata_from_toc(toc, run_number)
+
+
def extract_gpu_utilization(trace: Path, run_number: int) -> GpuUtilization:
toc = _toc_root(trace)
run = toc.find(f".//run[@number='{run_number}']")
diff --git a/tools/gpu_trace/src/gpu_trace/formatting.py b/tools/gpu_trace/src/gpu_trace/formatting.py
index 56204edbc..ba3343806 100644
--- a/tools/gpu_trace/src/gpu_trace/formatting.py
+++ b/tools/gpu_trace/src/gpu_trace/formatting.py
@@ -8,6 +8,7 @@ from rich.panel import Panel
from rich.table import Table
from rich.text import Text
+from .gputrace import BufferElement, BufferStats, CaptureInfo
from .models import KernelCounterStats, TraceExport
# Use terminal width or sensible default (minimum 140 for readable tables)
@@ -429,3 +430,99 @@ def print_comparison(
console.print(kernel_table)
console.print()
+
+
+# ── capture formatting ────────────────────────────────────────────────────
+
+
+def _fmt_bytes(n: int) -> str:
+ if n >= 1_000_000:
+ return f"{n / 1e6:.1f} MB"
+ if n >= 1_000:
+ return f"{n / 1e3:.1f} KB"
+ return f"{n} B"
+
+
+def print_capture_info(info: CaptureInfo) -> None:
+ meta = info.metadata
+
+ meta_table = Table(title="[bold]GPU Trace Capture[/]", box=box.ROUNDED)
+ meta_table.add_column("Property", style="dim")
+ meta_table.add_column("Value", style="green")
+ if meta.uuid:
+ meta_table.add_row("UUID", meta.uuid)
+ meta_table.add_row("API", meta.graphics_api)
+ if meta.captured_frames:
+ meta_table.add_row("Frames", str(meta.captured_frames))
+ console.print(meta_table)
+ console.print()
+
+ if info.resources:
+ res_table = Table(title="[bold cyan]Resources[/]", box=box.ROUNDED)
+ res_table.add_column("Filename", style="white", min_width=25)
+ res_table.add_column("Size", justify="right", style="green")
+ res_table.add_column("Label", style="yellow")
+ res_table.add_column("Type", style="dim")
+
+ for r in info.resources:
+ res_table.add_row(
+ r.filename,
+ _fmt_bytes(r.size_bytes),
+ r.label or "(no label)",
+ r.kind,
+ )
+ console.print(res_table)
+ console.print()
+
+ if info.shader_libraries:
+ console.print("[bold]Shader Libraries:[/]")
+ for lib in info.shader_libraries:
+ console.print(f" {lib.path}")
+ console.print()
+
+ if info.shader_functions:
+ console.print("[bold]Shader Functions:[/]")
+ for func in info.shader_functions:
+ console.print(f" {func}")
+ console.print()
+
+
+def print_buffer_data(
+ elements: list[BufferElement],
+ label: str,
+ filename: str,
+) -> None:
+ console.print(f"[bold]{label}[/] ({filename}):")
+ for el in elements:
+ parts: list[str] = []
+ for _, value in el.fields:
+ if isinstance(value, list):
+ parts.append(f"({', '.join(f'{x:.4f}' for x in value)})")
+ elif isinstance(value, float):
+ parts.append(f"{value:.4f}")
+ else:
+ parts.append(str(value))
+ console.print(f" [{el.index:>6}] {' | '.join(parts)}")
+ console.print()
+
+
+def print_buffer_stats(stats_list: list[BufferStats]) -> None:
+ table = Table(title="[bold]Buffer Summary[/]", box=box.ROUNDED)
+ table.add_column("Filename", style="white", min_width=25)
+ table.add_column("Label", style="yellow")
+ table.add_column("Size", justify="right", style="green")
+ table.add_column("Floats", justify="right", style="cyan")
+ table.add_column("Range", style="dim")
+ table.add_column("Mean", justify="right", style="dim")
+
+ for s in stats_list:
+ table.add_row(
+ s.filename,
+ s.label or "(no label)",
+ _fmt_bytes(s.size_bytes),
+ f"{s.float_count:,}",
+ f"[{s.min_val:.4f}, {s.max_val:.4f}]",
+ f"{s.mean_val:.4f}",
+ )
+ console.print(table)
+ console.print()
diff --git a/tools/gpu_trace/src/gpu_trace/gputrace.py b/tools/gpu_trace/src/gpu_trace/gputrace.py
new file mode 100644
index 000000000..7bc59962d
--- /dev/null
+++ b/tools/gpu_trace/src/gpu_trace/gputrace.py
@@ -0,0 +1,387 @@
+"""Parse .gputrace capture bundles.
+
+Reads MTLBuffer/MTLTexture files from .gputrace bundles, extracts resource
+labels from device-resources binary files, and reads buffer data with
+configurable struct layouts.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import struct
+import subprocess
+from dataclasses import dataclass
+from pathlib import Path
+
+
+@dataclass(frozen=True)
+class CaptureMetadata:
+ uuid: str
+ captured_frames: int
+ graphics_api: str
+
+
+@dataclass(frozen=True)
+class CaptureResource:
+ filename: str
+ size_bytes: int
+ label: str
+ kind: str # "buffer" or "texture"
+
+
+@dataclass(frozen=True)
+class ShaderLibrary:
+ path: str
+
+
+@dataclass(frozen=True)
+class CaptureInfo:
+ metadata: CaptureMetadata
+ resources: tuple[CaptureResource, ...]
+ shader_functions: tuple[str, ...]
+ shader_libraries: tuple[ShaderLibrary, ...]
+
+
+@dataclass(frozen=True)
+class BufferElement:
+ index: int
+ fields: tuple[tuple[str, object], ...] # (field_name, value)
+
+
+# ── metadata ──────────────────────────────────────────────────────────────
+
+
+def parse_metadata(gputrace: Path) -> CaptureMetadata:
+ meta_path = gputrace / "metadata"
+ if not meta_path.exists():
+ return CaptureMetadata(uuid="", captured_frames=0, graphics_api="")
+
+ result = subprocess.run(
+ ["plutil", "-convert", "json", "-o", "-", str(meta_path)],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0:
+ return CaptureMetadata(uuid="", captured_frames=0, graphics_api="")
+
+ data = json.loads(result.stdout)
+ api_code = data.get("DYCaptureSession.graphics_api")
+ api = {1: "Metal"}.get(api_code, f"Unknown({api_code})" if api_code else "Unknown")
+
+ return CaptureMetadata(
+ uuid=data.get("(uuid)", ""),
+ captured_frames=data.get("DYCaptureEngine.captured_frames_count", 0),
+ graphics_api=api,
+ )
+
+
+# ── binary string extraction ─────────────────────────────────────────────
+
+
+def _extract_strings(data: bytes, min_length: int = 3) -> list[tuple[int, str]]:
+ """Extract printable ASCII strings with their byte offsets."""
+ strings: list[tuple[int, str]] = []
+ current: list[str] = []
+ start: int | None = None
+
+ for i, b in enumerate(data):
+ if 32 <= b <= 126:
+ if start is None:
+ start = i
+ current.append(chr(b))
+ else:
+ if len(current) >= min_length:
+ assert start is not None
+ strings.append((start, "".join(current)))
+ current = []
+ start = None
+
+ if len(current) >= min_length and start is not None:
+ strings.append((start, "".join(current)))
+
+ return strings
+
+
+# ── label extraction ──────────────────────────────────────────────────────
+
+
+def extract_buffer_labels(gputrace: Path) -> dict[str, str]:
+ """Extract MTLBuffer/MTLTexture filename → label mapping.
+
+ Scans device-resources binary files for printable strings, matching
+ resource filenames to their nearest following label string.
+ """
+ label_map: dict[str, str] = {}
+
+ for fname in os.listdir(gputrace):
+ if not fname.startswith("device-resources"):
+ continue
+ data = (gputrace / fname).read_bytes()
+ strings = _extract_strings(data)
+
+ resource_refs = [
+ (off, s)
+ for off, s in strings
+ if re.match(r"MTL(Buffer|Texture)-\d+-\d+", s)
+ ]
+
+ label_strings = [
+ (off, s)
+ for off, s in strings
+ if " " in s
+ and len(s) >= 5
+ and not s.startswith("MTL")
+ and not s.startswith("/")
+ ]
+
+ for roff, rname in resource_refs:
+ best_label: str | None = None
+ best_dist = float("inf")
+ for loff, lval in label_strings:
+ dist = loff - roff
+ if 0 < dist < best_dist:
+ best_dist = dist
+ best_label = lval
+ if best_label:
+ label_map[rname] = best_label
+
+ return label_map
+
+
+# ── shader info ───────────────────────────────────────────────────────────
+
+
+def extract_shader_info(
+ gputrace: Path,
+) -> tuple[list[str], list[str]]:
+ """Extract shader function names and library paths.
+
+ Returns (functions, libraries).
+ """
+ functions: list[str] = []
+ libraries: list[str] = []
+
+ for fname in os.listdir(gputrace):
+ if not fname.startswith("device-resources"):
+ continue
+ data = (gputrace / fname).read_bytes()
+ strings = _extract_strings(data)
+
+ for _, s in strings:
+ if s.endswith(".metallib"):
+ libraries.append(s)
+
+ in_functions = False
+ for _, s in strings:
+ if s.endswith(".metallib"):
+ in_functions = True
+ continue
+ if s == "pipeline-libraries":
+ in_functions = False
+ continue
+ if (
+ in_functions
+ and re.match(r"^[a-z_][a-z0-9_]*$", s)
+ and len(s) > 3
+ and s not in ("function", "functions", "buffer", "buffers")
+ ):
+ if s not in functions:
+ functions.append(s)
+
+ return functions, libraries
+
+
+# ── buffer reading ────────────────────────────────────────────────────────
+
+_LAYOUT_FORMATS: dict[str, tuple[str, int, int]] = {
+ "float": ("f", 1, 1),
+ "float2": ("ff", 2, 2),
+ "float3": ("ffff", 4, 3), # Metal simd_float3 is 16-byte aligned; 4th float is padding
+ "packed_float3": ("fff", 3, 3), # Metal packed_float3, no alignment padding
+ "float4": ("ffff", 4, 4),
+ "uint32": ("I", 1, 1),
+ "int32": ("i", 1, 1),
+ "half": ("e", 1, 1),
+ "half2": ("ee", 2, 2),
+ "half4": ("eeee", 4, 4),
+}
+
+
+def parse_layout(layout: str) -> tuple[str, list[tuple[str, int, int]]]:
+ """Parse a layout string into a struct format and field descriptors.
+
+ Returns (struct_format, [(component_name, n_read, n_report), ...]).
+ """
+ components = [c.strip() for c in layout.split(",")]
+ fmt_parts: list[str] = []
+ fields: list[tuple[str, int, int]] = []
+
+ for comp in components:
+ if comp not in _LAYOUT_FORMATS:
+ raise ValueError(f"Unknown layout component: {comp}")
+ fmt, n_read, n_report = _LAYOUT_FORMATS[comp]
+ fmt_parts.append(fmt)
+ fields.append((comp, n_read, n_report))
+
+ return "<" + "".join(fmt_parts), fields
+
+
+def read_buffer(
+ gputrace: Path,
+ filename: str,
+ layout: str,
+ start: int = 0,
+ count: int = 10,
+) -> list[BufferElement]:
+ """Read a buffer file with the given layout.
+
+ Layout formats:
+ "float" - single float per element
+ "float4" - 4 floats (RGBA, position, etc.)
+ "float4,float4,float4" - compound struct (e.g., Particle)
+ "uint32" - single uint32 per element
+ "half4" - 4 half-precision floats
+ """
+ filepath = gputrace / filename
+ if not filepath.exists():
+ return []
+
+ fmt, fields = parse_layout(layout)
+ stride = struct.calcsize(fmt)
+
+ data = filepath.read_bytes()
+ total_elements = len(data) // stride
+
+ results: list[BufferElement] = []
+ for idx in range(start, min(start + count, total_elements)):
+ offset = idx * stride
+ values = struct.unpack_from(fmt, data, offset)
+
+ field_entries: list[tuple[str, object]] = []
+ vi = 0
+ for ci, (comp_name, n_read, n_report) in enumerate(fields):
+ if n_report == 1:
+ field_entries.append((f"field{ci}", values[vi]))
+ else:
+ field_entries.append(
+ (f"field{ci}", list(values[vi : vi + n_report]))
+ )
+ vi += n_read
+ results.append(BufferElement(index=idx, fields=tuple(field_entries)))
+
+ return results
+
+
+def buffer_element_count(gputrace: Path, filename: str, layout: str) -> int:
+ """Return total element count for a buffer given a layout."""
+ filepath = gputrace / filename
+ if not filepath.exists():
+ return 0
+ fmt, _ = parse_layout(layout)
+ stride = struct.calcsize(fmt)
+ return filepath.stat().st_size // stride
+
+
+# ── resource listing ──────────────────────────────────────────────────────
+
+
+def list_resources(gputrace: Path) -> CaptureInfo:
+ """List all resources in a .gputrace bundle."""
+ labels = extract_buffer_labels(gputrace)
+ metadata = parse_metadata(gputrace)
+ functions, libraries = extract_shader_info(gputrace)
+
+ resources: list[CaptureResource] = []
+ for fname in sorted(os.listdir(gputrace)):
+ m = re.match(r"MTL(Buffer|Texture)-\d+-\d+", fname)
+ if not m:
+ continue
+ size = (gputrace / fname).stat().st_size
+ kind = "buffer" if m.group(1) == "Buffer" else "texture"
+ label = labels.get(fname, "")
+ resources.append(
+ CaptureResource(
+ filename=fname,
+ size_bytes=size,
+ label=label,
+ kind=kind,
+ )
+ )
+
+ return CaptureInfo(
+ metadata=metadata,
+ resources=tuple(resources),
+ shader_functions=tuple(functions),
+ shader_libraries=tuple(ShaderLibrary(path=p) for p in libraries),
+ )
+
+
+# ── buffer stats (no numpy dependency) ───────────────────────────────────
+
+
+@dataclass(frozen=True)
+class BufferStats:
+ filename: str
+ label: str
+ size_bytes: int
+ float_count: int
+ min_val: float
+ max_val: float
+ mean_val: float
+ first_four: tuple[float, ...]
+
+
+def buffer_summary(gputrace: Path, filename: str, label: str) -> BufferStats | None:
+ """Compute summary statistics for a buffer interpreted as float32."""
+ filepath = gputrace / filename
+ if not filepath.exists():
+ return None
+
+ data = filepath.read_bytes()
+ n_floats = len(data) // 4
+ if n_floats == 0:
+ return None
+
+ values = struct.unpack_from(f"<{n_floats}f", data)
+
+ return BufferStats(
+ filename=filename,
+ label=label,
+ size_bytes=len(data),
+ float_count=n_floats,
+ min_val=min(values),
+ max_val=max(values),
+ mean_val=sum(values) / n_floats,
+ first_four=tuple(values[:4]),
+ )
+
+
+def resolve_buffer_filename(
+ gputrace: Path,
+ buffer_query: str,
+ labels: dict[str, str] | None = None,
+) -> str | None:
+ """Resolve a buffer label or filename to an actual filename.
+
+ Tries exact filename match first, then exact label match,
+ then partial label match (case-insensitive).
+ """
+ if (gputrace / buffer_query).exists():
+ return buffer_query
+
+ if labels is None:
+ labels = extract_buffer_labels(gputrace)
+
+ # Exact label match (case-insensitive)
+ for fname, label in labels.items():
+ if label.lower() == buffer_query.lower():
+ return fname
+
+ # Partial match
+ for fname, label in labels.items():
+ if buffer_query.lower() in label.lower():
+ return fname
+
+ return None
diff --git a/tools/gpu_trace/src/gpu_trace/main.py b/tools/gpu_trace/src/gpu_trace/main.py
index c898fd0f8..e54f8c04b 100644
--- a/tools/gpu_trace/src/gpu_trace/main.py
+++ b/tools/gpu_trace/src/gpu_trace/main.py
@@ -5,6 +5,7 @@ import sys
from pathlib import Path
from .extractors import (
+ _toc_root,
compute_kernel_counter_stats,
compute_kernel_summary,
extract_counter_definitions,
@@ -12,10 +13,25 @@ from .extractors import (
extract_gpu_utilization,
extract_kernel_dispatches,
extract_metadata,
+ extract_metadata_from_toc,
extract_performance_states,
extract_shaders,
+ export_tables_parallel,
+)
+from .formatting import (
+ print_buffer_data,
+ print_buffer_stats,
+ print_capture_info,
+ print_comparison,
+ print_summary,
+)
+from .gputrace import (
+ buffer_summary,
+ extract_buffer_labels,
+ list_resources,
+ read_buffer,
+ resolve_buffer_filename,
)
-from .formatting import print_comparison, print_summary
from .models import TraceExport
from .progress import status
from .recorder import default_output_path, record_trace
@@ -23,9 +39,26 @@ from .serialization import from_json, to_json
def export_trace(trace: Path, run_number: int) -> TraceExport:
+ # Phase 1: Extract metadata from cached TOC (no subprocess needed after first call)
with status("Extracting trace metadata..."):
- metadata = extract_metadata(trace, run_number)
-
+ toc = _toc_root(trace)
+ metadata = extract_metadata_from_toc(toc, run_number)
+
+ # Phase 2: Export all independent schemas in parallel
+ with status("Exporting trace schemas (parallel)..."):
+ schemas = [
+ "metal-gpu-state-intervals",
+ "metal-application-encoders-list",
+ "metal-gpu-intervals",
+ "gpu-performance-state-intervals",
+ "gpu-counter-info",
+ "metal-shader-profiler-intervals",
+ "metal-shader-profiler-shader-list",
+ "gpu-counter-value",
+ ]
+ tables = export_tables_parallel(trace, run_number, schemas)
+
+ # Phase 3: Parse the exported tables (CPU-bound, fast)
with status("Analyzing GPU utilization..."):
utilization = extract_gpu_utilization(trace, run_number)
@@ -138,6 +171,70 @@ def cmd_compare(args: argparse.Namespace) -> int:
return 0
+def cmd_capture(args: argparse.Namespace) -> int:
+ gputrace = args.gputrace
+ if not gputrace.is_dir():
+ print(f"Error: Not a directory: {gputrace}", file=sys.stderr)
+ return 1
+
+ if args.buffer:
+ labels = extract_buffer_labels(gputrace)
+ filename = resolve_buffer_filename(gputrace, args.buffer, labels)
+ if not filename:
+ print(f"Error: Buffer '{args.buffer}' not found.", file=sys.stderr)
+ print("Available buffers:", file=sys.stderr)
+ for fname, label in labels.items():
+ print(f" {fname} -> {label}", file=sys.stderr)
+ return 1
+
+ if "-" in args.index:
+ parts = args.index.split("-")
+ start, end = int(parts[0]), int(parts[1])
+ count = end - start + 1
+ else:
+ start = int(args.index)
+ count = 1
+
+ elements = read_buffer(gputrace, filename, args.layout, start, count)
+
+ if args.json:
+ import json
+
+ rows = []
+ for el in elements:
+ row: dict[str, object] = {"index": el.index}
+ for name, value in el.fields:
+ row[name] = value
+ rows.append(row)
+ print(json.dumps(rows, indent=2))
+ else:
+ label = labels.get(filename, filename)
+ print_buffer_data(elements, label, filename)
+
+ elif args.dump_all:
+ labels = extract_buffer_labels(gputrace)
+ import os
+ import re
+
+ stats_list = []
+ for fname in sorted(os.listdir(gputrace)):
+ if not re.match(r"MTLBuffer-\d+-\d+", fname):
+ continue
+ s = buffer_summary(gputrace, fname, labels.get(fname, ""))
+ if s:
+ stats_list.append(s)
+
+ if stats_list:
+ print_buffer_stats(stats_list)
+ else:
+ print("No buffer data found in capture.", file=sys.stderr)
+ else:
+ info = list_resources(gputrace)
+ print_capture_info(info)
+
+ return 0
+
+
def cmd_view(args: argparse.Namespace) -> int:
json_path = args.json_file
if not json_path.exists():
@@ -169,6 +266,7 @@ Quick Start:
1. Record a trace: gpu_trace run -- ./my_metal_app
2. Analyze results: gpu_trace analyze /tmp/gpu_trace_*.trace
3. Compare traces: gpu_trace compare before.trace after.trace
+ 4. Inspect capture: gpu_trace capture capture.gputrace
For detailed per-kernel hardware counters, use --gpu-counters:
gpu_trace run --gpu-counters -- ./my_metal_app
@@ -249,6 +347,32 @@ Examples:
gpu_trace compare a.trace b.trace --label1 before --label2 after
"""
+CAPTURE_DESCRIPTION = """
+Inspect a .gputrace capture bundle.
+
+Lists resources (MTLBuffer/MTLTexture files with labels), shader
+functions, and library paths. Can also read buffer data with
+configurable struct layouts.
+""".strip()
+
+CAPTURE_EPILOG = """
+Examples:
+ # List all resources in a capture
+ gpu_trace capture capture.gputrace
+
+ # Read buffer by label
+ gpu_trace capture capture.gputrace --buffer "Color Output" --layout float4 --index 0-10
+
+ # Read compound struct (e.g., Particle = position + velocity + color)
+ gpu_trace capture capture.gputrace --buffer "Particle" --layout "float4,float4,float4"
+
+ # Dump summary statistics for all buffers
+ gpu_trace capture capture.gputrace --dump-all
+
+ # Output buffer data as JSON
+ gpu_trace capture capture.gputrace --buffer "Vertex" --layout float4 --json
+"""
+
VIEW_DESCRIPTION = """
Visualize a previously exported JSON trace file.
@@ -415,6 +539,48 @@ def main(argv: list[str]) -> int:
help="Label for second trace (default: comparison)",
)
+ # --- capture subcommand ---
+ capture_p = sub.add_parser(
+ "capture",
+ help="Inspect a .gputrace capture bundle",
+ description=CAPTURE_DESCRIPTION,
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog=CAPTURE_EPILOG,
+ )
+ capture_p.add_argument(
+ "gputrace",
+ type=Path,
+ help="Path to .gputrace bundle",
+ )
+ capture_p.add_argument(
+ "-b", "--buffer",
+ default="",
+ metavar="NAME",
+ help="Buffer label or filename to inspect (empty = list all resources)",
+ )
+ capture_p.add_argument(
+ "-l", "--layout",
+ default="float4",
+ metavar="LAYOUT",
+ help="Buffer element layout (e.g., 'float4', 'float4,float4,float4')",
+ )
+ capture_p.add_argument(
+ "-i", "--index",
+ default="0-10",
+ metavar="RANGE",
+ help="Element index or range (e.g., '100', '0-10')",
+ )
+ capture_p.add_argument(
+ "--dump-all",
+ action="store_true",
+ help="Dump summary statistics for all buffers",
+ )
+ capture_p.add_argument(
+ "--json",
+ action="store_true",
+ help="Output buffer data as JSON",
+ )
+
# --- view subcommand ---
view_p = sub.add_parser(
"view",
@@ -442,6 +608,8 @@ def main(argv: list[str]) -> int:
return cmd_analyze(args)
elif args.cmd == "compare":
return cmd_compare(args)
+ elif args.cmd == "capture":
+ return cmd_capture(args)
elif args.cmd == "view":
return cmd_view(args)