Lift
Intent
Deliver aggressive performance improvements while preserving behavior, safety,
determinism, and maintainability. Lift is the umbrella optimization skill for
product workloads, service latency, batch/offline throughput, memory pressure,
tail behavior, algorithmic complexity, data layout, concurrency, I/O, and runtime
or compiler tuning.
Prime Directive
Profile first. Prove behavior unchanged. Change one lever at a time. Measure
before and after on the same workload. Ship only with a regression guard.
Every optimization pass must produce evidence for five questions:
- What is the performance contract?
- What does the baseline show?
- What bottleneck did profiling identify?
- Why is the proposed change behavior-preserving?
- What measured delta and guard justify shipping?
Double Diamond fit
Lift lives in Define -> Deliver.
- Define: write a performance contract, select a proof workload, and choose a
correctness oracle.
- Deliver: baseline, profile, score opportunities, run tight experiments, prove
equivalence, verify the result, and install a guard.
Hard Rules
- Measure before and after every optimization: numbers, environment, command,
workload, dataset, and sample count.
- Optimize the current bottleneck, not the loudest hunch. Use a profiler, trace,
counter, or workload-specific observation.
- Require a correctness signal before and after. Never accept a perf win with a
failing correctness gate.
- Preserve semantics unless the user explicitly approves a semantic trade-off.
- Change one lever per experiment and keep diffs reversible.
- Reject wins smaller than the noise floor unless the result is explicitly
labelled inconclusive.
- Track second-order regressions: memory, tail latency, CPU, I/O, lock waits,
cache size, and external cost.
- Stop and ask before raising resource or cost ceilings, unless the user asked
for that trade-off.
- If no runnable proof workload exists, prefix the response with
UNMEASURED:
and provide exact commands. Do not claim wins.
- For Lift-owned CLIs, use Zig binaries only (
bench_stats, perf_report) and
prove compatibility with marker checks before use.
- After any Zig CLI contract change, update docs and release/tap propagation in
the same pass so install guidance matches runtime behavior.
Mode Selection
Use measured mode whenever a proof workload can run.
- Measured mode: run baseline and variant on the same workload. Include raw
sample count, percentiles or throughput, profile evidence, correctness proof,
and regression guard.
- Unmeasured mode: start with
UNMEASURED:. Provide hypotheses and the exact
commands that would generate baseline, profile, correctness, and after data.
- Audit mode: when the user only asks for a review, produce a ranked
opportunity matrix and proof plan, but mark untested items as hypotheses.
Contract Derivation
If the user did not provide a numeric target, define the contract as:
Improve <primary metric> on <workload> versus baseline; report delta and do
not regress <correctness + secondary metrics>.
Default primary metric:
- Request-like/service code: latency p95; also report p50, p99, max, throughput,
CPU, and memory when feasible.
- Batch/offline code: throughput or wall-clock duration; also report CPU%, peak
RSS, and I/O volume.
- Memory/GC issue: peak RSS, allocation rate, and GC pause; also report latency
or throughput.
- Startup/cold path: cold-start wall time; separately measure steady-state.
- Tail problem: p99/max and variance drivers; treat variance reduction as the
primary goal.
Workload Selection
Pick the first representative runnable proof workload available:
- User-provided reproduction command or production-like workload.
- Existing repo benchmark, test harness, Makefile/justfile/taskfile, CI job, or
README workflow.
- A minimal harness around the hot path, paired with correctness checks.
- If none can be created without product ambiguity, operate in
UNMEASURED
mode and specify the missing workload requirements.
Mandatory Optimization Loop
0. PREFLIGHT -> environment, workload, correctness oracle, warmup sanity
1. BASELINE -> repeated samples, p50/p95/p99/max or throughput/RSS/allocs
2. PROFILE -> CPU, allocation, I/O, lock, queue, or tail evidence
3. PROVE -> golden outputs, invariants, property tests, or differential run
4. SCORE -> opportunity matrix: Impact x Confidence / Effort
5. IMPLEMENT -> one lever only, smallest reversible diff
6. VERIFY -> correctness gate, golden checksum/diff, benchmark rerun
7. REPROFILE -> confirm bottleneck moved or score next opportunity
8. GUARD -> benchmark budget, CI gate, monitor, or perf report
Default benchmark examples:
hyperfine --warmup 3 --runs 10 'command'
hyperfine --warmup 3 --runs 30 --export-json baseline.json 'command'
/usr/bin/time -v command 2>&1 | tee time.txt
Default behavior oracle examples:
mkdir -p golden_outputs
for input in test_inputs/*; do ./program "$input" > "golden_outputs/$(basename "$input").out"; done
sha256sum golden_outputs/* > golden_checksums.txt
sha256sum -c golden_checksums.txt
Opportunity Matrix Gate
Only implement a candidate when the score is at least 2.0, unless the user
explicitly requests exploratory work.
Score = (Impact x Confidence) / Effort
Impact: 1=<5%, 2=5-10%, 3=10-25%, 4=25-50%, 5=>50%
Confidence: 1=speculative, 3=plausible, 5=profile-confirmed
Effort: 1=minutes, 3=hours, 5=>1 day or high complexity
| Opportunity |
Hotspot evidence |
Impact |
Confidence |
Effort |
Score |
Decision |
<change> |
<profile/trace/counter> |
|
|
|
|
accept/reject |
Behavior Proof Gate
For every accepted change, document an isomorphism proof before claiming success.
Use references/behavior-proof.md for full guidance.
## Behavior proof: <change>
- Inputs covered:
- Old behavior:
- New behavior:
- Ordering preserved:
- Tie-breaking unchanged:
- Floating-point semantics:
- RNG/time/concurrency determinism:
- Error handling and edge cases:
- Golden outputs / differential check:
- Correctness command(s):
Common proof obligations:
- Batching: same operations, same effective order or explicitly stable reorder.
- Hash/index lookup: same key equivalence, same missing-key behavior, order
preserved if observable.
- Memoization: function is pure for cache key, invalidation is correct, bounds are
safe.
- Parallelization: operation is associative/commutative or merge order is stable;
no data races.
- Approximation: bounded error is explicitly accepted by the user or product
contract.
Optimization Ladder
Move down only after higher-leverage tiers are exhausted.
- Delete work: skip unused computation, redundant parsing, duplicate I/O.
- Change the algorithm: reduce complexity class or exploit monotonicity.
- Change data structures/layout: indexes, maps, heaps, SoA, contiguous buffers.
- Improve memory behavior: preallocation, pooling, arenas, allocation removal.
- Improve concurrency: shard, pipeline, batch, reduce contention, bound queues.
- Reduce I/O/serialization: fewer bytes, syscalls, round trips, and copies.
- Improve tail behavior: backpressure, timeouts, cancellation, variance control.
- Tune micro-architecture: branch predictability, SIMD, cache lines, prefetch.
- Tune compiler/runtime: PGO/LTO/JIT warmup/GC flags/inlining.
Round Escalation
- Round 0: Measurement hygiene. Stabilize benchmark and correctness oracle.
- Round 1: Standard wins: N+1 elimination, batching, indexing, memoization,
preallocation, cache bounds, JSON/serialization cleanup, log formatting removal.
- Round 2: Algorithmic and architectural wins: DP, graph reductions,
streaming, partitioning, lock sharding, layout rewrites, queue/admission fixes.
- Round 3: Advanced/exotic wins: convex/semiring recasts, FFT/NTT, suffix
arrays, sketches, cache-oblivious recursion, meet-in-the-middle, specialized
indexes, PGO/LTO/SIMD.
Each round starts with a fresh profile because bottlenecks shift.
Fast Pattern Tiers
| Tier |
Pattern |
When |
Proof concern |
| 1 |
N+1 -> batch |
Sequential external calls |
Result ordering and retry semantics |
| 1 |
Linear scan -> index/hash |
Repeated keyed lookup |
Key equality and observable order |
| 1 |
Memoization |
Repeated pure computation |
Cache key, invalidation, bounds |
| 1 |
Buffer/prealloc reuse |
Allocation in hot loop |
Aliasing and lifetime safety |
| 2 |
Binary search/two-pointer |
Sorted or monotone data |
Precondition validation |
| 2 |
Prefix sums/sliding window |
Repeated range queries |
Static data or update semantics |
| 2 |
Priority queue/top-k |
Scheduling or ranking |
Tie-breaking and stability |
| 3 |
Arena/pool/SmallVec/SoA |
Allocation or locality bound |
Lifetime, ownership, memory cap |
| 3 |
Bloom/sketch/HLL |
Membership/counting at scale |
Error bound and acceptance |
| 3 |
Lock sharding/queues |
Contention/tail bound |
Races, fairness, backpressure |
Language Triage Cheatsheet
| Ecosystem |
First profiler |
Allocation/memory |
Fast grep signals |
| Rust/Zig/C/C++ |
perf, flamegraph, Instruments |
heaptrack, DHAT, massif |
clones/copies, boxes, formatting, allocs |
| Go |
go tool pprof, go tool trace |
heap/alloc profiles, GODEBUG=gctrace=1 |
interface{}, defer in loops, fmt.Sprintf |
| Node/TypeScript |
clinic flame, node --prof |
DevTools heap, event-loop delay |
JSON parse/stringify, sync fs, await-in-loop |
| Python |
py-spy, cProfile, scalene |
memory_profiler, tracemalloc |
iterrows, string +=, list membership |
| JVM |
JFR, async-profiler |
allocation/lock events, GC logs |
boxing, reflection, synchronized hot path |
Lift-owned CLI tools
When using or changing bench_stats or perf_report, read
cli-tools.md for the Zig marker compatibility checks,
source repositories, and launcher. Reuse compatible installed tools; installation
requires existing provisioning authority.
Deliverable Format (Chat)
Lead with the measured result and comparison baseline. Include the workload and
sample count, bottleneck evidence, change, correctness and regression checks, and
material uncertainty or trade-offs. Scale detail to the task; use the existing
report template for a requested full report.
Keep evidence needed to assess the performance claim; do not repeat it in a
mandatory compliance footer.
If unmeasured, prefix the response with UNMEASURED: and give the exact
measurement, profiling, and proof commands. Do not claim deltas.
Core References (Load on Demand)
references/playbook.md — master flow, doctrine, and loop.
references/measurement.md — benchmarking, statistics, noise, and reporting.
references/profiling-tools.md — tool matrix and evidence artifacts.
references/behavior-proof.md — golden outputs, invariants, isomorphism proof.
references/opportunity-matrix.md — impact/confidence/effort score gate.
references/optimization-tactics.md — tactical catalog by layer.
references/algorithms-and-data-structures.md — algorithmic and structural levers.
references/systems-and-architecture.md — CPU, memory, OS, network tactics.
references/latency-throughput-tail.md — queueing, variance, and backpressure.
references/language-specific.md — ecosystem-specific profilers and red flags.
references/advanced-techniques.md — round-2/round-3 advanced patterns.
references/checklists.md — fast triage and validation checklists.
references/anti-patterns.md — traps to reject.
Assets
assets/perf-report-template.md — ready-to-edit measured or unmeasured report.
assets/experiment-log-template.md — one-variable experiment ledger.
assets/isomorphism-proof-template.md — per-change behavior proof.
assets/opportunity-matrix-template.md — score-gated opportunity table.
assets/golden-output-manifest.md — golden-output capture checklist.
1---2name: lift3description: Performance optimization with measurement-driven latency, throughput, memory/GC, tail, algorithmic, systems, and micro-architectural work; profile evidence, score-gated experiments, behavior proofs, golden oracles, and regression guards. Use for optimize, speed up, reduce p95/p99, increase throughput/QPS, lower CPU/memory/allocations/GC/syscalls/round trips, profiling, bottlenecks, algorithmic improvement, or benchmarked perf passes. Without a runnable workload, operate in labelled UNMEASURED mode with exact benchmark/profiling/proof commands. Prove Zig-only bench_stats/perf_report CLI iteration before shipping.4---56# Lift78## Intent910Deliver aggressive performance improvements while preserving behavior, safety,11determinism, and maintainability. Lift is the umbrella optimization skill for12product workloads, service latency, batch/offline throughput, memory pressure,13tail behavior, algorithmic complexity, data layout, concurrency, I/O, and runtime14or compiler tuning.1516## Prime Directive1718Profile first. Prove behavior unchanged. Change one lever at a time. Measure19before and after on the same workload. Ship only with a regression guard.2021Every optimization pass must produce evidence for five questions:22231. What is the performance contract?242. What does the baseline show?253. What bottleneck did profiling identify?264. Why is the proposed change behavior-preserving?275. What measured delta and guard justify shipping?2829## Double Diamond fit3031Lift lives in Define -> Deliver.3233- Define: write a performance contract, select a proof workload, and choose a34 correctness oracle.35- Deliver: baseline, profile, score opportunities, run tight experiments, prove36 equivalence, verify the result, and install a guard.3738## Hard Rules3940- Measure before and after every optimization: numbers, environment, command,41 workload, dataset, and sample count.42- Optimize the current bottleneck, not the loudest hunch. Use a profiler, trace,43 counter, or workload-specific observation.44- Require a correctness signal before and after. Never accept a perf win with a45 failing correctness gate.46- Preserve semantics unless the user explicitly approves a semantic trade-off.47- Change one lever per experiment and keep diffs reversible.48- Reject wins smaller than the noise floor unless the result is explicitly49 labelled inconclusive.50- Track second-order regressions: memory, tail latency, CPU, I/O, lock waits,51 cache size, and external cost.52- Stop and ask before raising resource or cost ceilings, unless the user asked53 for that trade-off.54- If no runnable proof workload exists, prefix the response with `UNMEASURED:`55 and provide exact commands. Do not claim wins.56- For Lift-owned CLIs, use Zig binaries only (`bench_stats`, `perf_report`) and57 prove compatibility with marker checks before use.58- After any Zig CLI contract change, update docs and release/tap propagation in59 the same pass so install guidance matches runtime behavior.6061## Mode Selection6263Use measured mode whenever a proof workload can run.6465- **Measured mode:** run baseline and variant on the same workload. Include raw66 sample count, percentiles or throughput, profile evidence, correctness proof,67 and regression guard.68- **Unmeasured mode:** start with `UNMEASURED:`. Provide hypotheses and the exact69 commands that would generate baseline, profile, correctness, and after data.70- **Audit mode:** when the user only asks for a review, produce a ranked71 opportunity matrix and proof plan, but mark untested items as hypotheses.7273## Contract Derivation7475If the user did not provide a numeric target, define the contract as:7677> Improve `<primary metric>` on `<workload>` versus baseline; report delta and do78> not regress `<correctness + secondary metrics>`.7980Default primary metric:8182- Request-like/service code: latency p95; also report p50, p99, max, throughput,83 CPU, and memory when feasible.84- Batch/offline code: throughput or wall-clock duration; also report CPU%, peak85 RSS, and I/O volume.86- Memory/GC issue: peak RSS, allocation rate, and GC pause; also report latency87 or throughput.88- Startup/cold path: cold-start wall time; separately measure steady-state.89- Tail problem: p99/max and variance drivers; treat variance reduction as the90 primary goal.9192## Workload Selection9394Pick the first representative runnable proof workload available:95961. User-provided reproduction command or production-like workload.972. Existing repo benchmark, test harness, Makefile/justfile/taskfile, CI job, or98 README workflow.993. A minimal harness around the hot path, paired with correctness checks.1004. If none can be created without product ambiguity, operate in `UNMEASURED`101 mode and specify the missing workload requirements.102103## Mandatory Optimization Loop104105```text1060. PREFLIGHT -> environment, workload, correctness oracle, warmup sanity1071. BASELINE -> repeated samples, p50/p95/p99/max or throughput/RSS/allocs1082. PROFILE -> CPU, allocation, I/O, lock, queue, or tail evidence1093. PROVE -> golden outputs, invariants, property tests, or differential run1104. SCORE -> opportunity matrix: Impact x Confidence / Effort1115. IMPLEMENT -> one lever only, smallest reversible diff1126. VERIFY -> correctness gate, golden checksum/diff, benchmark rerun1137. REPROFILE -> confirm bottleneck moved or score next opportunity1148. GUARD -> benchmark budget, CI gate, monitor, or perf report115```116117Default benchmark examples:118119```bash120hyperfine --warmup 3 --runs 10 'command'121hyperfine --warmup 3 --runs 30 --export-json baseline.json 'command'122/usr/bin/time -v command 2>&1 | tee time.txt123```124125Default behavior oracle examples:126127```bash128mkdir -p golden_outputs129for input in test_inputs/*; do ./program "$input" > "golden_outputs/$(basename "$input").out"; done130sha256sum golden_outputs/* > golden_checksums.txt131sha256sum -c golden_checksums.txt132```133134## Opportunity Matrix Gate135136Only implement a candidate when the score is at least 2.0, unless the user137explicitly requests exploratory work.138139```text140Score = (Impact x Confidence) / Effort141Impact: 1=<5%, 2=5-10%, 3=10-25%, 4=25-50%, 5=>50%142Confidence: 1=speculative, 3=plausible, 5=profile-confirmed143Effort: 1=minutes, 3=hours, 5=>1 day or high complexity144```145146| Opportunity | Hotspot evidence | Impact | Confidence | Effort | Score | Decision |147|---|---:|---:|---:|---:|---:|---|148| `<change>` | `<profile/trace/counter>` | | | | | accept/reject |149150## Behavior Proof Gate151152For every accepted change, document an isomorphism proof before claiming success.153Use `references/behavior-proof.md` for full guidance.154155```markdown156## Behavior proof: <change>157- Inputs covered:158- Old behavior:159- New behavior:160- Ordering preserved:161- Tie-breaking unchanged:162- Floating-point semantics:163- RNG/time/concurrency determinism:164- Error handling and edge cases:165- Golden outputs / differential check:166- Correctness command(s):167```168169Common proof obligations:170171- Batching: same operations, same effective order or explicitly stable reorder.172- Hash/index lookup: same key equivalence, same missing-key behavior, order173 preserved if observable.174- Memoization: function is pure for cache key, invalidation is correct, bounds are175 safe.176- Parallelization: operation is associative/commutative or merge order is stable;177 no data races.178- Approximation: bounded error is explicitly accepted by the user or product179 contract.180181## Optimization Ladder182183Move down only after higher-leverage tiers are exhausted.1841851. Delete work: skip unused computation, redundant parsing, duplicate I/O.1862. Change the algorithm: reduce complexity class or exploit monotonicity.1873. Change data structures/layout: indexes, maps, heaps, SoA, contiguous buffers.1884. Improve memory behavior: preallocation, pooling, arenas, allocation removal.1895. Improve concurrency: shard, pipeline, batch, reduce contention, bound queues.1906. Reduce I/O/serialization: fewer bytes, syscalls, round trips, and copies.1917. Improve tail behavior: backpressure, timeouts, cancellation, variance control.1928. Tune micro-architecture: branch predictability, SIMD, cache lines, prefetch.1939. Tune compiler/runtime: PGO/LTO/JIT warmup/GC flags/inlining.194195## Round Escalation196197- **Round 0:** Measurement hygiene. Stabilize benchmark and correctness oracle.198- **Round 1:** Standard wins: N+1 elimination, batching, indexing, memoization,199 preallocation, cache bounds, JSON/serialization cleanup, log formatting removal.200- **Round 2:** Algorithmic and architectural wins: DP, graph reductions,201 streaming, partitioning, lock sharding, layout rewrites, queue/admission fixes.202- **Round 3:** Advanced/exotic wins: convex/semiring recasts, FFT/NTT, suffix203 arrays, sketches, cache-oblivious recursion, meet-in-the-middle, specialized204 indexes, PGO/LTO/SIMD.205206Each round starts with a fresh profile because bottlenecks shift.207208## Fast Pattern Tiers209210| Tier | Pattern | When | Proof concern |211|---|---|---|---|212| 1 | N+1 -> batch | Sequential external calls | Result ordering and retry semantics |213| 1 | Linear scan -> index/hash | Repeated keyed lookup | Key equality and observable order |214| 1 | Memoization | Repeated pure computation | Cache key, invalidation, bounds |215| 1 | Buffer/prealloc reuse | Allocation in hot loop | Aliasing and lifetime safety |216| 2 | Binary search/two-pointer | Sorted or monotone data | Precondition validation |217| 2 | Prefix sums/sliding window | Repeated range queries | Static data or update semantics |218| 2 | Priority queue/top-k | Scheduling or ranking | Tie-breaking and stability |219| 3 | Arena/pool/SmallVec/SoA | Allocation or locality bound | Lifetime, ownership, memory cap |220| 3 | Bloom/sketch/HLL | Membership/counting at scale | Error bound and acceptance |221| 3 | Lock sharding/queues | Contention/tail bound | Races, fairness, backpressure |222223## Language Triage Cheatsheet224225| Ecosystem | First profiler | Allocation/memory | Fast grep signals |226|---|---|---|---|227| Rust/Zig/C/C++ | `perf`, flamegraph, Instruments | `heaptrack`, DHAT, massif | clones/copies, boxes, formatting, allocs |228| Go | `go tool pprof`, `go tool trace` | heap/alloc profiles, `GODEBUG=gctrace=1` | `interface{}`, `defer` in loops, `fmt.Sprintf` |229| Node/TypeScript | `clinic flame`, `node --prof` | DevTools heap, event-loop delay | JSON parse/stringify, sync fs, await-in-loop |230| Python | `py-spy`, `cProfile`, `scalene` | `memory_profiler`, `tracemalloc` | `iterrows`, string `+=`, list membership |231| JVM | JFR, async-profiler | allocation/lock events, GC logs | boxing, reflection, synchronized hot path |232233## Lift-owned CLI tools234235When using or changing `bench_stats` or `perf_report`, read236[cli-tools.md](references/cli-tools.md) for the Zig marker compatibility checks,237source repositories, and launcher. Reuse compatible installed tools; installation238requires existing provisioning authority.239240## Deliverable Format (Chat)241242Lead with the measured result and comparison baseline. Include the workload and243sample count, bottleneck evidence, change, correctness and regression checks, and244material uncertainty or trade-offs. Scale detail to the task; use the existing245[report template](assets/perf-report-template.md) for a requested full report.246Keep evidence needed to assess the performance claim; do not repeat it in a247mandatory compliance footer.248249If unmeasured, prefix the response with `UNMEASURED:` and give the exact250measurement, profiling, and proof commands. Do not claim deltas.251252## Core References (Load on Demand)253254- `references/playbook.md` — master flow, doctrine, and loop.255- `references/measurement.md` — benchmarking, statistics, noise, and reporting.256- `references/profiling-tools.md` — tool matrix and evidence artifacts.257- `references/behavior-proof.md` — golden outputs, invariants, isomorphism proof.258- `references/opportunity-matrix.md` — impact/confidence/effort score gate.259- `references/optimization-tactics.md` — tactical catalog by layer.260- `references/algorithms-and-data-structures.md` — algorithmic and structural levers.261- `references/systems-and-architecture.md` — CPU, memory, OS, network tactics.262- `references/latency-throughput-tail.md` — queueing, variance, and backpressure.263- `references/language-specific.md` — ecosystem-specific profilers and red flags.264- `references/advanced-techniques.md` — round-2/round-3 advanced patterns.265- `references/checklists.md` — fast triage and validation checklists.266- `references/anti-patterns.md` — traps to reject.267268## Assets269270- `assets/perf-report-template.md` — ready-to-edit measured or unmeasured report.271- `assets/experiment-log-template.md` — one-variable experiment ledger.272- `assets/isomorphism-proof-template.md` — per-change behavior proof.273- `assets/opportunity-matrix-template.md` — score-gated opportunity table.274- `assets/golden-output-manifest.md` — golden-output capture checklist.