repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

convert optimize prompt to skill with sub-references

c07b9f34567b70ab85655e70d2c199841d63745b

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (14)

pi/agent/prompts/optimize.md

Deleted
deleted file mode 100644
1 ----
2 -description: Benchmark and optimize code
3 -argument-hint: "<function-or-file>"
4 ----
6 -# Benchmark and optimize code
8 -**Target**:
9 -$ARGUMENTS
11 -Workflow:
13 -1. **Profile** - Find hotspots with the best available canonical profiler for the runtime and OS.
14 - Fall back to tracing or wall time only when appropriate.
15 -2. **Choose measurement** - Match tooling to scope:
16 - - in-process hot path -> microbenchmark
17 - - CLI/process behavior -> end-to-end timing
18 - - CPU hotspot -> CPU profiler
19 - - memory/allocations -> heap profiler
20 - - I/O/network -> tracing
21 -3. **Baseline** - Create a repeatable benchmark before changing code.
22 -4. **Analyze** - Connect measurements to concrete code and explain the bottleneck.
23 -5. **Optimize** - Change only measured bottlenecks.
24 -6. **Verify** - Re-run equivalent baseline/candidate measurements.
25 - Choose an appropriate statistical comparison method.
26 - Report variance, significance, and meaningful regressions.
27 -7. **Document** - Record methodology and rationale for non-obvious optimizations.
29 -Tool choice is part of the work.
30 -Do not prescribe a specific profiler, benchmark framework, or comparison tool.
31 -Prefer canonical tools already available for the runtime, OS, and repository.
32 -Prefer existing repository automation.
34 -If required tooling is missing, stop and tell me exactly which tool is missing and why it is needed.
35 -Ask me to install or enable it.
36 -Continue once I confirm it is available.
37 -Do not silently substitute another tool or change dependencies, system, or build config.
39 -Run tests to make sure old behavior did not break.
40 -If code to be optimized is not tested, write tests first.
41 -If changes are needed to system tools, dependencies, or build system, report them to me.

pi/agent/skills/optimize/SKILL.md

Added
new file mode 100644
1 +---
2 +name: optimize
3 +description: "Benchmark and optimize code across performance, memory, startup, I/O, network, concurrency, algorithmic, caching, config categories, plus meta-level: doing less, mechanical sympathy, architecture fixes."
4 +disable-model-invocation: true
5 +---
7 +# Optimize
9 +**Target**: $ARGUMENTS
11 +## Methodology
13 +1. **Profile** → find hotspots with canonical profiler for runtime+OS. tracing/wall-time fallback OK.
14 +2. **Choose measurement** → match tool to scope:
15 + - in-process → microbenchmark
16 + - CLI/process → end-to-end timing
17 + - CPU → CPU profiler
18 + - memory/alloc → heap profiler
19 + - I/O/network → tracing
20 +3. **Baseline** → repeatable benchmark before changes.
21 +4. **Analyze** → connect measurements to code. explain bottleneck.
22 +5. **Optimize** → change only measured bottlenecks.
23 +6. **Verify** → re-run baseline/candidate. statistical comparison. report variance, significance, regressions.
24 +7. **Document** → record methodology + rationale for non-obvious optimizations.
26 +## Benchmarking Rigor
28 +- **warmup** → run before measurement; discard. stabilizes JIT, caches, branch predictors.
29 +- **outliers** → detect and remove. use IQR or MAD; report removed count.
30 +- **effect size + confidence intervals** → report magnitude and interval, not just p-values. statistical significance ≠ practical significance.
31 +- **repetition** → count based on variance source: between-build > between-execution > between-iteration. more reps for noisier sources.
32 +- **isolation** → control environment: disable auto-updates, pin CPU frequency, avoid concurrent load.
34 +## Categories
36 +- performance / hot paths
37 +- memory / allocations / reclamation
38 +- startup / cold-start / init cost
39 +- I/O / disk / syscalls / buffering
40 +- network / requests / caching / retries
41 +- concurrency / locks / worker pools
42 +- algorithmic / complexity / data structures
43 +- caching / memoization / invalidation
44 +- config / build / deps / compiler flags
46 +multiple categories? prioritize by impact + measurability.
48 +## Meta
50 +- **doing less** → same goal, fewer instructions. [ref](references/doing-less.md)
51 +- **mechanical sympathy** → substrate awareness (runtime, VM, CPU, network, API). structure data + instructions efficiently. includes data-oriented design. [ref](references/mechanical-sympathy.md)
52 +- **architecture** → system-level design wrong? serial vs batched, coupling, sync vs async. [ref](references/architecture.md)
54 +## Anti-Patterns
56 +common mistakes spanning all categories. review before profiling. [ref](references/anti-patterns.md)
58 +## References
60 +- [anti-patterns](references/anti-patterns.md)
61 +- [memory](references/memory.md)
62 +- [startup](references/startup.md)
63 +- [io](references/io.md)
64 +- [network](references/network.md)
65 +- [concurrency](references/concurrency.md)
66 +- [algorithmic](references/algorithmic.md)
67 +- [caching](references/caching.md)
68 +- [config-build](references/config-build.md)
69 +- [doing-less](references/doing-less.md)
70 +- [mechanical-sympathy](references/mechanical-sympathy.md)
71 +- [architecture](references/architecture.md)
73 +## Tooling
75 +tool choice = part of the work. no hardcoded profiler/benchmark/comparison tool.
76 +prefer canonical tools available for runtime+OS+repo. prefer existing repo automation.
78 +missing tooling? stop. say exactly which tool + why. ask to install/enable. no silent substitution. no dep/system/build changes without approval.
80 +## Testing
82 +run tests. untested code → write tests first. system/dep/build changes → report.

pi/agent/skills/optimize/references/algorithmic.md

Added
new file mode 100644
1 +# Algorithmic
3 +complexity class, data structure swaps.
5 +## Measure
7 +- algorithmic analysis → current time/space complexity
8 +- benchmarking → compare implementations on representative inputs
9 +- profiling → confirm complexity, not constant factors, is bottleneck
10 +- metrics → ops/sec, scaling across input sizes
12 +## Optimize
14 +- reduce complexity → O(n²) → O(n log n) → O(n)
15 +- efficient data structures → hash vs tree vs array by access pattern
16 +- precomputation → compute once, not repeatedly
17 +- early termination → exit when result known
18 +- divide and conquer → independent subproblems
20 +## Pitfalls
22 +- constant factors matter → better complexity may be slower for small inputs
23 +- don't optimize for sizes that never occur
24 +- worst case ≠ average case; average matters for real workloads
25 +- data structure trade-offs → memory, cache, implementation complexity

pi/agent/skills/optimize/references/anti-patterns.md

Added
new file mode 100644
1 +# Anti-Patterns
3 +Cross-cutting performance mistakes spanning all categories. identify before profiling.
5 +## Data Fetching
7 +- **N+1 queries** → fetch parent, then query children per parent. batch with JOIN or eager loading.
8 +- **unbounded collection loading** → load all rows into memory. paginate or stream.
9 +- **extraneous fetching** → load columns/relations never used. select only needed fields.
11 +## Connection & I/O
13 +- **no connection pooling** → establish/teardown per operation. pool connections.
14 +- **chatty I/O** → many small requests over network or disk. batch into single round-trip.
15 +- **sync blocking in async code** → call blocking I/O from async path. use async APIs or offload to worker.
16 +- **improper instantiation** → create/destroy shared objects per use. reuse singletons or pooled instances.
18 +## Resilience
20 +- **retry storm** → unbounded retries without backoff or circuit breaker. cap retries, add backoff, use circuit breaker.
21 +- **no caching** → fetch same data repeatedly from backend. cache frequently-read data.
23 +## Memory
25 +- **unbounded growth** → collections/queues with no eviction or limit. bound caches, add TTL.
26 +- **memory leaks** → listeners, callbacks, references retained indefinitely. clean up handlers on teardown.
27 +- **string concatenation in hot path** → O(n²) repeated concatenation. use builder/buffer.
29 +## Design
31 +- **premature optimization** → tune before measuring. profile first, optimize measured bottlenecks.
32 +- **performance decorations** → optimizations that look fast but have no impact. verify with benchmarks.
33 +- **nosy neighbor** → single tenant/workload consuming disproportionate resources. isolate or quota.
34 +- **busy database** → offload all processing to the data store. move logic to application where appropriate.
35 +- **monolithic persistence** → one store for data with very different usage patterns. split by access pattern.
37 +## Detection
39 +- profile before optimizing
40 +- benchmark before and after changes
41 +- watch for patterns above during code review
42 +- load test with realistic data volumes before production

pi/agent/skills/optimize/references/architecture.md

Added
new file mode 100644
1 +# Architecture
3 +system-level design issues causing performance problems.
5 +## Approach
7 +- understand holistically → components, data flow, communication
8 +- identify bottlenecks → serial vs parallel, tight coupling, unnecessary indirection
9 +- challenge assumptions → latency, throughput, reliability often misunderstood
10 +- redesign interfaces → batch, reduce round-trips, parallelize independent work
12 +## Patterns
14 +- **serial → batched** → processes one at a time; batch for latency/throughput
15 +- **tight coupling → loosening** → extract independent components to run parallel
16 +- **sync → async** → offload blocking to background workers
17 +- **monolithic → modular** → split for independent optimization + scaling
19 +## Example
21 +client/server API serial (one request at a time) because latency/throughput not understood. fix: batch requests → amortize latency, increase throughput.
23 +## Pitfalls
25 +- over-architecting → don't redesign whole system for small gain
26 +- operational complexity → deployment, monitoring, debugging overhead
27 +- premature scale → optimize algorithm + implementation first
28 +- local metrics ≠ end-to-end latency → what users experience

pi/agent/skills/optimize/references/caching.md

Added
new file mode 100644
1 +# Caching
3 +memoization, caching layers, invalidation.
5 +## Measure
7 +- cache profiling → hit/miss rate, size, eviction
8 +- invalidation analysis → staleness frequency
9 +- cache overhead → lookup + maintenance cost
10 +- metrics → hit ratio, avg lookup time, invalidation freq
12 +## Optimize
14 +- multi-level caching → hot (mem) → warm (shared) → cold (backend)
15 +- cache warming → pre-populate known-accessed data
16 +- efficient invalidation → TTL, version keys, event-driven
17 +- cache-aside → application manages; only cache frequent reads
18 +- write-through vs write-behind → by read/write ratio + consistency needs
20 +## Pitfalls
22 +- cache stampede → concurrent uncached keys overwhelm backend
23 +- stale data → invalidation missing
24 +- over-caching → rarely-accessed wastes memory + lookup overhead
25 +- unbounded cache → evicts or exhausts memory

pi/agent/skills/optimize/references/concurrency.md

Added
new file mode 100644
1 +# Concurrency
3 +lock contention, thread/worker sizing, race conditions.
5 +## Measure
7 +- concurrency profiling → locks, critical sections
8 +- thread dump analysis → states, blocked, deadlocks
9 +- lock analysis → hold times, wait times, contention rate
10 +- metrics → lock wait, thread utilization, context switch rate, contention ratio
12 +## Optimize
14 +- lock-free data structures → atomics over locks
15 +- reduce critical sections → minimize locked work
16 +- tune worker pools → match pool to workload (CPU vs I/O bound)
17 +- async processing → offload blocking work
18 +- partition data → sharding reduces shared structure contention
19 +- read-write locks → read-heavy workloads
21 +## Pitfalls
23 +- premature lock removal → complex, error-prone; only when contention measured
24 +- over-parallelism → context switch overhead
25 +- false sharing → adjacent writes invalidate cache lines
26 +- deadlock risk → changing lock order; test thoroughly

pi/agent/skills/optimize/references/config-build.md

Added
new file mode 100644
1 +# Config / Build
3 +build time, dependency bloat, compilation overhead.
5 +## Measure
7 +- build profiling → per-phase time (compile, link, test)
8 +- dependency analysis → tree size, transitive deps
9 +- compiler benchmarking → optimization levels vs impact
10 +- metrics → total build, incremental build, dep count/size
12 +## Optimize
14 +- parallel builds → use all cores
15 +- dependency reduction → audit, remove unused
16 +- compiler optimization → tune levels, LTO, PGO where applicable
17 +- incremental builds → cache intermediates, only changed modules
18 +- pre-built deps → system packages or pre-compiled binaries
19 +- pipeline optimization → parallelize independent steps
21 +## Pitfalls
23 +- build speed matters for dev, not prod
24 +- incremental vs full → optimize common case
25 +- optimization trade-offs → higher opt = longer compile + larger binary
26 +- dep removal risk → reimplementing functionality

pi/agent/skills/optimize/references/doing-less.md

Added
new file mode 100644
1 +# Doing Less
3 +same goal, fewer instructions.
5 +## Approach
7 +- redundant ops → compute once, not per iteration
8 +- dead code → remove branches/calculations that never affect output
9 +- logic simplification → flatten conditionals, reduce nesting, early returns
10 +- combine ops → merge passes where safe
11 +- efficient APIs → prefer built-in/library over hand-rolled
12 +- remove indirection → inline trivial functions, eliminate unnecessary abstractions
14 +## Principles
16 +- every instruction → measurable purpose
17 +- transformation that doesn't change behavior → question its necessity
18 +- simplest correct implementation → complexity is tax on future changes
20 +## Pitfalls
22 +- premature simplification → don't sacrifice correctness/readability for marginal gains
23 +- over-inlining → increases code size, hurts instruction cache
24 +- compiler already does this → verify before duplicating effort

pi/agent/skills/optimize/references/io.md

Added
new file mode 100644
1 +# I/O
3 +disk reads/writes, syscalls, buffering, blocking vs async.
5 +## Measure
7 +- syscall tracing → count, identify blocking calls
8 +- device profiling → I/O wait, throughput, queue depth
9 +- block tracing → long synchronous ops
10 +- metrics → I/O wait %, syscall count, bytes, queue depth
12 +## Optimize
14 +- batching → combine small ops into single
15 +- buffering → appropriate buffer sizes, avoid tiny reads/writes
16 +- async I/O → non-blocking or thread pools for concurrency
17 +- memory-mapped files → map into memory
18 +- pre-fetching → read ahead
19 +- reduce syscall overhead → higher-level APIs that batch internally
21 +## Pitfalls
23 +- over-batching → latency + memory waste
24 +- async complexity → only when I/O path is the bottleneck
25 +- filesystem matters → different FS, different perf
26 +- raw throughput ≠ latency under load

pi/agent/skills/optimize/references/mechanical-sympathy.md

Added
new file mode 100644
1 +# Mechanical Sympathy
3 +substrate awareness (runtime, VM, CPU, network, API) → structure data + instructions efficiently.
5 +## Core Concepts
7 +- **memory access** → cache hierarchy friendly vs cache-missing. sequential over random, small working sets
8 +- **allocations** → runtime reclamation tax: short-lived values, fragmentation, excessive retention
9 +- **compiler/backend** → what it can/cannot optimize. verify with output, don't guess
10 +- **patterns** → data-oriented design, dependency-chain-free loops, branch-prediction-friendly code
12 +## Data-Oriented Design
14 +- **SoA vs AoS** → array of structs (AoS) interleaves fields; struct of arrays (SoA) separates by field. SoA improves SIMD throughput and cache utilization when iterating one field. convert hot loops to SoA.
15 +- **hot/cold splitting** → separate frequently-accessed data (hot) from rarely-accessed (cold). reduces cache pressure; cold data doesn't pollute cache lines.
16 +- **cache line padding** → align data to cache line boundaries (64 bytes typically). prevents false sharing between threads and avoids partial line loads.
17 +- **loop tiling/blocking** → process data in blocks that fit cache rather than streaming entire dataset. improves temporal locality for multi-dimensional access.
18 +- **software prefetching** → explicitly load future data ahead of need. hides memory latency for pointer-chasing or irregular access patterns.
20 +## Approach
22 +1. understand substrate → cache hierarchy, memory layout, reclamation, compiler/backend pipeline
23 +2. structure data → contiguous over linked, padding for alignment, SoA for hot loops
24 +3. structure instructions → independent for parallel execution
25 +4. verify compiler/backend output → inspect IR/assembly
26 +5. measure → confirm substrate-aware changes help; don't assume
28 +## Timeless Principles
30 +- measure, don't guess → compiler/backend output + profiling > intuition
31 +- locality is king → sequential access orders of magnitude faster than random
32 +- allocations aren't free → CPU + reclamation time, even when allocator is fast
33 +- branch mispredictions expensive → predictable control flow faster
35 +## Pitfalls
37 +- over-engineering for hardware that may change → focus on timeless principles (locality, independence)
38 +- don't defeat compiler → write code compiler/backend can optimize
39 +- premature opt → mechanical sympathy guides design, not micro-optimization
40 +- SoA complexity → only convert when iterating single field; AoS is fine for record-style access

pi/agent/skills/optimize/references/memory.md

Added
new file mode 100644
1 +# Memory
3 +allocation patterns, leaks, heap pressure, fragmentation.
5 +## Measure
7 +- heap profiling → allocation rate, live heap, pause/freq of reclamation
8 +- allocation tracking → hot allocators, sites
9 +- reclamation logs → frequency, duration, cause
10 +- metrics → bytes/sec, heap trend, reclamation overhead %
12 +## Optimize
14 +- reuse objects/buffers for short-lived values
15 +- avoid allocations in hot loops (pre-allocate, reuse buffers)
16 +- efficient data structures (contiguous over pointer-chasing for sequential access)
17 +- tune allocator/reclamation params if applicable
18 +- size objects to fit cache lines; avoid fragmentation
19 +- avoid boxing/copying where the runtime does it implicitly
21 +## Pitfalls
23 +- premature opt: small alloc reductions may not matter if allocator is fast
24 +- over-reusing: complexity + hidden leaks
25 +- ignoring reclamation: reducing allocs may not help if reclamation already efficient
26 +- peak heap ≠ average; average matters for throughput

pi/agent/skills/optimize/references/network.md

Added
new file mode 100644
1 +# Network
3 +request patterns, caching, retries, connection reuse.
5 +## Measure
7 +- network tracing → request/response patterns
8 +- monitoring → latency, throughput, error rates
9 +- connection profiling → establish, reuse, teardown
10 +- metrics → p50/p95/p99 latency, req/sec, error rate, pool utilization
12 +## Optimize
14 +- connection pooling → reuse instead of new
15 +- caching → client, server, edge
16 +- batching → combine requests into single round-trip
17 +- compression → payload size reduction
18 +- edge caching → serve from closer locations
19 +- retry tuning → avoid thundering herds, excess retries
21 +## Pitfalls
23 +- over-caching → stale data, invalidation overhead
24 +- geography → caching helps, distance still matters
25 +- pool misconfig → too few queues, too many wastes
26 +- server latency ≠ total; propagation delay counts

pi/agent/skills/optimize/references/startup.md

Added
new file mode 100644
1 +# Startup
3 +cold-start latency, initialization cost, deferred loading.
5 +## Measure
7 +- startup profiling → process start → ready state
8 +- init timing → per-module/per-component cost
9 +- dependency analysis → large deps, their contribution to init
10 +- metrics → time to first byte, time to interactive, init cost breakdown
12 +## Optimize
14 +- lazy loading → defer until first use
15 +- split init → load only what's needed for initial path
16 +- deferred setup → postpone non-critical initialization
17 +- pre-warming → cache modules/data at startup
18 +- trim deps → audit unused
19 +- optimize critical path → speed the startup sequence
21 +## Pitfalls
23 +- over-lazy → complexity + first-use stalls
24 +- cold ≠ warm start; different problems
25 +- total time alone → break down by component
26 +- caching with startup cost