[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75M14513VRCFYR523M62FVT":3,"skill-same:01M75M14513VRCFYR523M62FVT":81},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":20,"linkOnly":21,"markdownContent":22,"markdownBody":23,"frontMatter":24,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":6,"updatedAt":32,"install":33,"resources":46},"01M75M14513VRCFYR523M62FVT","lean-elaboration",null,"Diagnose and improve Lean 4 elaboration performance in a repo — locate genuine hot spots, route by profile phase, apply the proven levers (consumer import narrowing, nlinarith elimination, targeted simp-only, head-class caches, leaf splits, folding hypothesis types to the abbrev their consumer expects, naming the function in congr), and A\u002FB every change. Use when a repo builds slowly, a file blows past heartbeats, before landing perf edits, or when planning an elaboration campaign.","stanfish06\u002Fskillquarium","stanfish06","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F93099613?v=4","01M75F1CK4ZW109ZK3T26VN52F","Zhiyuan","01M75F1CM53VH6F79DZ8GXKKES",12,"CC-BY-4.0","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Flean-elaboration\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Flean-elaboration\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: lean-elaboration\ndescription: Diagnose and improve Lean 4 elaboration performance in a repo — locate genuine hot spots, route by profile phase, apply the proven levers (consumer import narrowing, nlinarith elimination, targeted simp-only, head-class caches, leaf splits, folding hypothesis types to the abbrev their consumer expects, naming the function in congr), and A\u002FB every change. Use when a repo builds slowly, a file blows past heartbeats, before landing perf edits, or when planning an elaboration campaign.\n---\n\n# Lean Elaboration Improvement\n\nThis guidance distills repeated A\u002FB measurements from large Lean 4 and Mathlib\nrepositories. The examples preserve useful magnitudes and negative results\nwithout carrying private project history into the workflow. Full evidence:\n[references\u002Fevidence.md](references\u002Fevidence.md).\n\nCompanion skills: **lean-elaboration-test** (the repo-level measurement\nsnapshot — run it first to find candidates), **lean-learnings** (ambient-space\nand reusable Mathlib guidance).\n\n## Rule zero\n\n**Improve elaboration by measurement, not by taste.** A proof that looks\ncleaner can be slower; a verbose proof can be much faster. The measured studies' costliest\nmistakes were interventions rolled out by analogy or aesthetics: a \"cleanup\"\nfile-split added +360s wall-clock in one afternoon; a cache rolled out to a\nsibling file regressed it. Every intervention gets a profile before and an A\u002FB\nafter, and speculative edits that don't move the numbers are reverted before\ncommit.\n\n## The loop\n\n1. **Find candidates at repo level** — run the lean-elaboration-test snapshot;\n   take the heavy tail (files ≥10s\u002F≥20s\u002F≥30s build wall-clock) from the build\n   log.\n2. **Confirm each candidate with a warm own-file profile** — build wall-clock\n   includes upstream rebuilds, olean writes, and contention; it overstates\n   own-file cost by ~2.5× in the recorded measurements.\n   Use the full-log and exit-status-preserving command in Phase 4 of\n   **lean-elaboration-test**. Classify only a successful run and retain its\n   complete output. Read the `cumulative profiling times` block. A \"50s file\"\n   may have only 1–3s of fixable cost. If `import` dominates, **the file is not fixable locally**\n   — the lever is upstream, or in what this file imports; do not touch its proofs.\n3. **Route by dominant phase** (dominant = >5s AND >25% of total):\n\n   | Dominant phase | Meaning | Action |\n   |---|---|---|\n   | `typeclass inference` | instance search \u002F overloaded algebra | head-class cache (guards below); explicit instance args; definitional bridges |\n   | `interpretation` | tactic execution — `nlinarith`\u002F`linarith`\u002F`polyrith` | explicit bounds + monotonicity lemmas + `calc`; `positivity` |\n   | `simp` | simp engine \u002F definitional unfolding | `simp only` with explicit list — but only where single calls exceed ~1s; `rfl`\u002F`exact`\u002F`dsimp`+`rw` for definitional bridges |\n   | `elaboration` | term elaboration, big unification | **run the `sorry`-substitution test first** (below); then lever 8, narrow wide simp chains, extract standalone lemmas, check for `Real.rpow`\u002F`Real.exp` entering numeric tactics |\n   | `import` | upstream olean load | fix upstream or narrow this file's imports; NOT a local proof problem |\n   | `tactic execution` | tactic doing real work post-elab | check for `congr` events (lever 9); split the proof, extract a helper |\n   | `type checking` | large terms | break into named `have`s \u002F helper lemmas |\n\n3b. **Before touching any proof, ask whether the cost is even in the proof.**\n   Replace the suspect declaration's body with `sorry` and re-profile. If the\n   phase total is **unchanged**, the cost is in elaborating the *statement*, and\n   no tactic, simp, cache, or import lever can touch it — go to lever 8. This\n   one-minute test prevents whole afternoons of proof tuning against a signature\n   problem. (Measured: a file at 9.55s elaboration read 9.57s with both proof\n   bodies `sorry`d.) A sibling declaration with the same hypotheses but a\n   cheaper conclusion is the control that confirms it.\n\n   **Locating anonymous events.** `--profile` often reports statement cost as\n   bare `elaboration took 5.3s` with no declaration name. Bisect by inserting\n   `#exit` at successive line numbers in an untracked copy and re-profile. A\n   short bisection usually pins the cost to one declaration without editing\n   tracked source.\n\n4. **Apply ONE intervention** — never stack changes before measuring.\n5. **A\u002FB and keep-or-revert** — compare a baseline and one edited variant of\n   the same file under matched machine load, toolchain, imports, and cache state;\n   run each variant at least three times, alternating their order when practical.\n   Default profile phase times are elapsed times and are affected by contention,\n   just like wall-clock measurements (Lean uses a [steady-clock timer](https:\u002F\u002Fgithub.com\u002Fleanprover\u002Flean4\u002Fblob\u002Fmaster\u002Fsrc\u002Futil\u002Ftimeit.h)).\n   If the profile and repeated wall-clock\n   results disagree or their variation obscures the change, report the result as\n   inconclusive and remeasure under comparable load. Keep the edit only if\n   the relevant phase repeatedly drops ≥2s (or ≥10%) without moving cost\n   somewhere worse.\n   Three consecutive failures of one technique on a file family = stop\n   applying that technique to the family.\n\n## The levers, ranked by reliability\n\n### 1. Import-load reduction in consumers (the biggest structural lever)\nRemove\u002Fnarrow imports in the files that *consume* a heavy module; never\n\"quarantine\" by splitting the upstream file while re-exporting everything\n(that failed: same content, 2.5× cost across three files). Verify\nsymbol-level: enumerate the imported module's public API by grep and check\nusage — naive candidate lists have a **~50% false-positive rate**\n(load-bearing instances\u002Ftactics), so build-verify each removal in the first\npass, not a follow-up. Avoid umbrella imports: import the precise provider\nfile, not the namespace facade. Measured: one consumer-side sweep cut whole\nconsumer groups 22–46% and a single file −59% with zero content change.\n\n### 2. `nlinarith`\u002F`linarith` elimination from arithmetic closers\nOnce nonlinear facts are named hypotheses, close with monotonicity lemmas\n(`add_le_add`, `sub_le_sub_right`, `mul_nonpos_of_nonpos_of_nonneg`) and\n`calc`; use `positivity` for pure sign goals; prefer `linarith only [...]`.\nMeasured: interpretation 14.6s → 3.15s; a file's `nlinarith` count 7 → 0 with\nown-file cost halved. **Near `Real.rpow`\u002F`Real.exp`: extract the pure-algebra\ncore as a standalone lemma over abstract reals** so numeric tactics never\nenter transcendental terms (`set`-bound exp-lets unfold inside `nlinarith`\nand cause expensive weak-head normalization; use `clear_value` or opaque\nvariables).\n\n### 3. Targeted `simp` narrowing — bimodal, so check the precondition\n`simp`\u002F`simpa` → `simp only`, or better `exact`\u002F`rfl`\u002F`dsimp [defs]; rw [law]`\nfor definitional bridges. **Works spectacularly** on files where individual\nsimp calls exceed ~1s (18.8s → 0.3s). **Null result** as a blanket file-scope\nsweep where peaks are \u003C1s (−0.2s against ±3s noise — reverted). Screen with\nthe profile's per-call `simp took Nms` lines; skip calls under ~200ms. Commit\nonly on >3s sustained file-level A\u002FB.\n\n### 4. Head-class instance caches (`private instance ... := inferInstance`)\nFor files with big `variable`\u002F`include` blocks (≥50 lines, referencing things\nlike `[NeZero d]`, `[IsProbabilityMeasure P]`, or project-type-indexed\ninstances): cache each recurring head-class once so resolution happens once\nper file and propagates via olean to importers. Guards, all mandatory —\nlearned from a rollout in which 4 of 6 planned caches were inapplicable and\n1 of the remaining 2 was null:\n- **Only above the 5s floor**: below 5s cumulative typeclass inference, caches\n  typically *hurt* (disambiguation overhead).\n- **Only for CLOSED instance searches.** A cache cannot terminate an *open*\n  search whose goal head is still a metavariable (e.g. `SMul ℝ ?α` from\n  elaborating `•` before the type family is known) — it only lengthens the\n  candidate list. Diagnose with `trace.Meta.synthInstance` before choosing:\n  closed search → cache; open search → **type ascriptions at the\n  elaboration-order pinch** (measured: 8→0 SMul events, −91% typeclass, where\n  the prescribed cache was refuted by A\u002FB).\n- **Placement is load-bearing**: top-level \u002F namespace-level, **outside any\n  `section ... variable` block** — section scoping hides the cache and it\n  silently does nothing (the operative distinction is top-level vs\n  section-scoped, not namespace membership).\n- **Leaf-first**: in an import chain, cache the leaf only; a redundant cache\n  upstream of an already-cached file *regressed* +1.2s.\n- **Cache only head-classes the file actually uses**; never derived classes.\n- **Never roll out by analogy**: identical brackets gave PASS on one file and\n  FAIL on its direct sibling. A\u002FB each file.\n- Propagation check: if downstream consumers improve \u003C0.5s, the cache didn't\n  propagate — placement is wrong.\n- When creating a structurally similar file, check whether it should import a\n  cached provider or needs its own measured cache. Several cacheless variants\n  once added more than 1,000 seconds of CPU in one build.\n\n### 5. Leaf splitting with DAG-shaped imports\nSplitting pays only when it changes what gets loaded or unblocks parallelism:\npush the parent's heavy imports down to only the sub-modules that need them\n(grep symbol counts per line range), make sub-module edges a DAG not a chain,\nand let independent halves be siblings. Splitting a file while consumers\nstill transitively need all parts is a pure loss (import preamble + olean\noverhead ×N). File-size discipline (~1,000–1,500-line ceiling) is about\nedit-iteration latency and parallelism, not cumulative CPU.\n\n### 6. Standalone lemma extraction \u002F clean-context elaboration\nExtract an expensive mathlib call or a heavy algebraic step into a\n`private lemma` with a minimal signature: instances resolve once, the call\nsite is a cheap application, and each lemma gets its own heartbeat budget.\nThis is also the escape from single-expensive-unification walls. Related:\nkeep membership\u002Fproof arguments out of heavy dependent surfaces; avoid\npartially-applied heavy theorems with pinned late implicits; prefer small\nconstructor lemmas over monolithic wired-up `abbrev`s.\n\n### 7. Statement hygiene that doubles as perf\n- >10 named hypotheses on a theorem → compress (structure bundle, typeclass\n  instances, caller-side `norm_num`, definitional `let`s). LLM agents don't\n  feel signature pain — one theorem reached 85 hypotheses \u002F 539-line\n  signature before anyone flagged it.\n- Unused section variables \u002F auto-bound instances are per-declaration\n  instance-search cost; keep the linter at zero.\n- rfl `_def` lemmas instead of `simp only [thedef]` unfolding of heavy\n  definitions.\n\n### 8. Fold a hypothesis type to the abbrev its consumer expects\nThe single highest-yield statement-level fix found so far (−98% elaboration,\nthree times). **Precondition:** a hypothesis is written in fully *unfolded*\nform, and the **conclusion feeds it into a dependent term** whose own signature\ndeclares that argument through an `abbrev`. Lean then discharges the\nunfolded-vs-abbrev defeq for the entire binder block, repeatedly.\n\n```lean\n-- costly: hypothesis unfolded, but `perturb` declares its arg as `FluxIntegrable U a u`\ntheorem foo (hu : ∀ φ : Test U, IntegrableOn (fun x => ⟪A x (u.grad x), φ.grad x⟫) U) :\n    P (perturb u w hu) = ...\n-- cheap: same proposition, stated the way the consumer expects\ntheorem foo (hu : FluxIntegrable U a u) : P (perturb u w hu) = ...\n```\n\nBecause the abbrev is definitionally the term, **this is notation, not\nsemantics**: the statement is unchanged and no consumer needs touching. Verify\nwith a full build anyway. The tell is verbosity *plus* dependent use — a sibling\nwith the identical unfolded block but no dependent consumer costs ~0 ms, so do\nnot \"clean up\" verbose binders that nothing consumes; you will gain nothing.\n\n**Sweeping for it:** grep is too weak (the unfolded text varies with binder\nnames and formatting). Parse instead — for each declaration, split the signature\nat the top-level `:` with a paren-depth counter, then flag any explicit binder\nwhose type is long (>90 chars) and contains `fun`\u002F`∀` **and** whose name occurs\nin the conclusion. On a 600k-line repo that yielded 42 candidates in 22 files;\nprofiling showed all but three had elaboration \u003C450 ms. Expect a low hit rate\nand profile before editing — the detector finds the shape, not the cost.\n\n### 9. Name the function in `congr`\n`congr`\u002F`congr 1` searches for a congruence decomposition. When you already know\nwhich function is being peeled, name it: `refine congrArg f ?_`. Same subgoals,\nno search.\n\n```lean\ncongr 1                                  -- 5.6s\nrefine congrArg (· ^ (1 \u002F p.toReal)) ?_  -- ~0s, goal `X = Y` as before\n```\n\nBare `congrArg _ ?_` usually fails to infer `f` — supply it (`congrArg Real.sqrt`,\n`congrArg (HMul.hMul _)`, `congrArg (· ^ e)`). Typical goals: `f a = f b` after a\n`rw` through an `rfl`-lemma, or after a `change`. Screen a repo by profiling\nmodules whose build-wall is ≥10s and which contain `congr`, then grep the profile\nfor `Tactic.congr took` — costs cluster bimodally at either \u003C100 ms or >2.5s, so\nthe expensive ones are unmistakable. Measured: 9.10s → 0.85s, 8.28s → 3.28s,\n6.35s → 0.65s.\n\n## The negative catalog — do not retry these\n\n- `set_option maxHeartbeats` \u002F `synthInstance.maxHeartbeats` bumps: changes\n  the failure threshold, not the cost. Treat a default-heartbeat failure as a\n  design signal. If the repository bans overrides, treat that as a hard rule.\n- `attribute [reducible]` on instances: shifts synthesis cost to defeq checks.\n- Splitting a slow file \"for performance\" without import\u002Fvariable-block\n  changes: cumulative CPU stays flat or rises.\n- Section-scoped `private instance` caches: inert, silently.\n- \"Backup\" caches for derived classes (`FiniteDimensional` alongside an\n  existing chain): regressed when tried.\n- Blind unused-import removal from grep lists: ~50% false positives; the\n  single biggest predicted win of one audit broke the build.\n- Structural dedup\u002Fhelper extraction from similarity audits: 2 of 3 failed\n  line-by-line inspection; discount such candidates 50–70%.\n- Tuning namespace orchestrator\u002Ffacade files: their cost is olean\n  deserialization; splitting moves it around.\n- Chasing \"diffuse typeclass\" files (thousands of sub-100ms searches, no\n  dominant head-class): proof restructuring left 8.5s → 8.5s. This is the\n  structural floor; accept it or reconsider the ambient types (see\n  `lean-learnings`).\n- Trusting a profile taken while other agents\u002Fusers use the CPUs, or\n  comparing a parallel batch profile with a serial one.\n- `#print axioms` (or other `#`-commands) left in source files: they re-run\n  at every rebuild — measured at 98% of one module's elaboration cost. Put\n  axiom audits in probe files outside the build root.\n\n## Sharp edges\n\n- **`touch` does not reliably invalidate** because Lake uses content hashes.\n  Use a repository-provided guarded invalidation command. If none exists,\n  resolve and remove only the exact project-owned module artifacts after\n  confirming the path cannot enter a dependency tree.\n- **Do not use `lake clean` for profiling.** It can erase dependency caches.\n  Invalidate only the repository-owned artifacts needed for the measurement,\n  under the repository's authorization rules.\n- **Profile totals don't sum to wall-clock**: olean serialization and IR\n  compilation are uncategorized. Use the phase breakdown to pick the lever,\n  wall-clock\u002FA-B to judge success.\n- `lean --profile` truncates events under 100ms; diffuse files underreport in\n  per-decl listings but show in the cumulative block. For per-declaration\n  attribution of unattributed elaboration time, rerun with\n  `-D trace.profiler.output=\u003Cfile>.json`.\n- **Elaboration cost compounds with downstream load**: files get slower with\n  zero edits as new callers exercise their theorem surfaces. A regression\n  with no proportional line growth is load compounding or contention, not\n  necessarily new bad code — check predicted (Δlines × prior ms\u002Fline) vs\n  actual ΔCPU before hunting a culprit file.\n- **Compute which bound you are under before optimizing anything.** Two\n  numbers: the work-floor (`total CPU \u002F cores`) and the critical chain\n  (longest weighted import path). The larger one is your wall-clock. The same\n  repo can be **chain-bound on a dev box and work-bound in CI** — one measured\n  case: 11,350s CPU \u002F 1,767s chain is chain-bound on 8 cores (floor 1,419s, so\n  only on-chain fixes help) but work-bound on a 4-core runner (floor 2,838s, so\n  *every* CPU saving converts). Off-chain work is not worthless; it is worthless\n  *for the machine shape where the chain dominates*. Say which one you optimized\n  when you report a win.\n- Cumulative-CPU savings convert to wall-clock only through the critical\n  path; under ~5× parallelism much of a saved file's time was already\n  overlapped. When the heavy tail is flat, further per-file work has\n  diminishing wall-clock returns.\n\n## Repository-wide mode\n\nFor a repo-wide effort (not a single hot file):\n\n1. **Snapshot first** (lean-elaboration-test), then triage the top-30 into\n   cost classes: include-block typeclass families (cache), tactic-bound\n   arithmetic (lever 2), simp-bound (lever 3), import-bound (lever 1 on\n   consumers, or leave), orchestrators\u002Ffacades (leave), genuine analytic\n   content (leave), diffuse-typeclass (leave\u002Faccept).\n2. Fix the **roots**, expect transitive gains; if the ten downstream files\n   don't improve, that's diagnostic, not bad luck.\n3. **One intervention per commit**, perf-only commits (no statement changes —\n   if a proof restructuring seems needed, profile first and ask), A\u002FB\n   evidence in the commit or report.\n4. Re-run the snapshot at matched parallelism to score the work; write\n   the dated report; keep the heavy-tail tier counts (≥10\u002F20\u002F30s) as the\n   local trend metric.\n5. **Codify demonstrated local invariants in the repo's agent instructions** —\n   for example, caches in measured hot areas or profiling before a split.\n   Keep local policy separate from portable guidance.\n6. Know when to stop: when the tail is 3 files of diffuse typeclass and the\n   only lever left is the critical path, further per-file tuning is not worth\n   agent time.\n","# Lean Elaboration Improvement\n\nThis guidance distills repeated A\u002FB measurements from large Lean 4 and Mathlib\nrepositories. The examples preserve useful magnitudes and negative results\nwithout carrying private project history into the workflow. Full evidence:\n[references\u002Fevidence.md](references\u002Fevidence.md).\n\nCompanion skills: **lean-elaboration-test** (the repo-level measurement\nsnapshot — run it first to find candidates), **lean-learnings** (ambient-space\nand reusable Mathlib guidance).\n\n## Rule zero\n\n**Improve elaboration by measurement, not by taste.** A proof that looks\ncleaner can be slower; a verbose proof can be much faster. The measured studies' costliest\nmistakes were interventions rolled out by analogy or aesthetics: a \"cleanup\"\nfile-split added +360s wall-clock in one afternoon; a cache rolled out to a\nsibling file regressed it. Every intervention gets a profile before and an A\u002FB\nafter, and speculative edits that don't move the numbers are reverted before\ncommit.\n\n## The loop\n\n1. **Find candidates at repo level** — run the lean-elaboration-test snapshot;\n   take the heavy tail (files ≥10s\u002F≥20s\u002F≥30s build wall-clock) from the build\n   log.\n2. **Confirm each candidate with a warm own-file profile** — build wall-clock\n   includes upstream rebuilds, olean writes, and contention; it overstates\n   own-file cost by ~2.5× in the recorded measurements.\n   Use the full-log and exit-status-preserving command in Phase 4 of\n   **lean-elaboration-test**. Classify only a successful run and retain its\n   complete output. Read the `cumulative profiling times` block. A \"50s file\"\n   may have only 1–3s of fixable cost. If `import` dominates, **the file is not fixable locally**\n   — the lever is upstream, or in what this file imports; do not touch its proofs.\n3. **Route by dominant phase** (dominant = >5s AND >25% of total):\n\n   | Dominant phase | Meaning | Action |\n   |---|---|---|\n   | `typeclass inference` | instance search \u002F overloaded algebra | head-class cache (guards below); explicit instance args; definitional bridges |\n   | `interpretation` | tactic execution — `nlinarith`\u002F`linarith`\u002F`polyrith` | explicit bounds + monotonicity lemmas + `calc`; `positivity` |\n   | `simp` | simp engine \u002F definitional unfolding | `simp only` with explicit list — but only where single calls exceed ~1s; `rfl`\u002F`exact`\u002F`dsimp`+`rw` for definitional bridges |\n   | `elaboration` | term elaboration, big unification | **run the `sorry`-substitution test first** (below); then lever 8, narrow wide simp chains, extract standalone lemmas, check for `Real.rpow`\u002F`Real.exp` entering numeric tactics |\n   | `import` | upstream olean load | fix upstream or narrow this file's imports; NOT a local proof problem |\n   | `tactic execution` | tactic doing real work post-elab | check for `congr` events (lever 9); split the proof, extract a helper |\n   | `type checking` | large terms | break into named `have`s \u002F helper lemmas |\n\n3b. **Before touching any proof, ask whether the cost is even in the proof.**\n   Replace the suspect declaration's body with `sorry` and re-profile. If the\n   phase total is **unchanged**, the cost is in elaborating the *statement*, and\n   no tactic, simp, cache, or import lever can touch it — go to lever 8. This\n   one-minute test prevents whole afternoons of proof tuning against a signature\n   problem. (Measured: a file at 9.55s elaboration read 9.57s with both proof\n   bodies `sorry`d.) A sibling declaration with the same hypotheses but a\n   cheaper conclusion is the control that confirms it.\n\n   **Locating anonymous events.** `--profile` often reports statement cost as\n   bare `elaboration took 5.3s` with no declaration name. Bisect by inserting\n   `#exit` at successive line numbers in an untracked copy and re-profile. A\n   short bisection usually pins the cost to one declaration without editing\n   tracked source.\n\n4. **Apply ONE intervention** — never stack changes before measuring.\n5. **A\u002FB and keep-or-revert** — compare a baseline and one edited variant of\n   the same file under matched machine load, toolchain, imports, and cache state;\n   run each variant at least three times, alternating their order when practical.\n   Default profile phase times are elapsed times and are affected by contention,\n   just like wall-clock measurements (Lean uses a [steady-clock timer](https:\u002F\u002Fgithub.com\u002Fleanprover\u002Flean4\u002Fblob\u002Fmaster\u002Fsrc\u002Futil\u002Ftimeit.h)).\n   If the profile and repeated wall-clock\n   results disagree or their variation obscures the change, report the result as\n   inconclusive and remeasure under comparable load. Keep the edit only if\n   the relevant phase repeatedly drops ≥2s (or ≥10%) without moving cost\n   somewhere worse.\n   Three consecutive failures of one technique on a file family = stop\n   applying that technique to the family.\n\n## The levers, ranked by reliability\n\n### 1. Import-load reduction in consumers (the biggest structural lever)\nRemove\u002Fnarrow imports in the files that *consume* a heavy module; never\n\"quarantine\" by splitting the upstream file while re-exporting everything\n(that failed: same content, 2.5× cost across three files). Verify\nsymbol-level: enumerate the imported module's public API by grep and check\nusage — naive candidate lists have a **~50% false-positive rate**\n(load-bearing instances\u002Ftactics), so build-verify each removal in the first\npass, not a follow-up. Avoid umbrella imports: import the precise provider\nfile, not the namespace facade. Measured: one consumer-side sweep cut whole\nconsumer groups 22–46% and a single file −59% with zero content change.\n\n### 2. `nlinarith`\u002F`linarith` elimination from arithmetic closers\nOnce nonlinear facts are named hypotheses, close with monotonicity lemmas\n(`add_le_add`, `sub_le_sub_right`, `mul_nonpos_of_nonpos_of_nonneg`) and\n`calc`; use `positivity` for pure sign goals; prefer `linarith only [...]`.\nMeasured: interpretation 14.6s → 3.15s; a file's `nlinarith` count 7 → 0 with\nown-file cost halved. **Near `Real.rpow`\u002F`Real.exp`: extract the pure-algebra\ncore as a standalone lemma over abstract reals** so numeric tactics never\nenter transcendental terms (`set`-bound exp-lets unfold inside `nlinarith`\nand cause expensive weak-head normalization; use `clear_value` or opaque\nvariables).\n\n### 3. Targeted `simp` narrowing — bimodal, so check the precondition\n`simp`\u002F`simpa` → `simp only`, or better `exact`\u002F`rfl`\u002F`dsimp [defs]; rw [law]`\nfor definitional bridges. **Works spectacularly** on files where individual\nsimp calls exceed ~1s (18.8s → 0.3s). **Null result** as a blanket file-scope\nsweep where peaks are \u003C1s (−0.2s against ±3s noise — reverted). Screen with\nthe profile's per-call `simp took Nms` lines; skip calls under ~200ms. Commit\nonly on >3s sustained file-level A\u002FB.\n\n### 4. Head-class instance caches (`private instance ... := inferInstance`)\nFor files with big `variable`\u002F`include` blocks (≥50 lines, referencing things\nlike `[NeZero d]`, `[IsProbabilityMeasure P]`, or project-type-indexed\ninstances): cache each recurring head-class once so resolution happens once\nper file and propagates via olean to importers. Guards, all mandatory —\nlearned from a rollout in which 4 of 6 planned caches were inapplicable and\n1 of the remaining 2 was null:\n- **Only above the 5s floor**: below 5s cumulative typeclass inference, caches\n  typically *hurt* (disambiguation overhead).\n- **Only for CLOSED instance searches.** A cache cannot terminate an *open*\n  search whose goal head is still a metavariable (e.g. `SMul ℝ ?α` from\n  elaborating `•` before the type family is known) — it only lengthens the\n  candidate list. Diagnose with `trace.Meta.synthInstance` before choosing:\n  closed search → cache; open search → **type ascriptions at the\n  elaboration-order pinch** (measured: 8→0 SMul events, −91% typeclass, where\n  the prescribed cache was refuted by A\u002FB).\n- **Placement is load-bearing**: top-level \u002F namespace-level, **outside any\n  `section ... variable` block** — section scoping hides the cache and it\n  silently does nothing (the operative distinction is top-level vs\n  section-scoped, not namespace membership).\n- **Leaf-first**: in an import chain, cache the leaf only; a redundant cache\n  upstream of an already-cached file *regressed* +1.2s.\n- **Cache only head-classes the file actually uses**; never derived classes.\n- **Never roll out by analogy**: identical brackets gave PASS on one file and\n  FAIL on its direct sibling. A\u002FB each file.\n- Propagation check: if downstream consumers improve \u003C0.5s, the cache didn't\n  propagate — placement is wrong.\n- When creating a structurally similar file, check whether it should import a\n  cached provider or needs its own measured cache. Several cacheless variants\n  once added more than 1,000 seconds of CPU in one build.\n\n### 5. Leaf splitting with DAG-shaped imports\nSplitting pays only when it changes what gets loaded or unblocks parallelism:\npush the parent's heavy imports down to only the sub-modules that need them\n(grep symbol counts per line range), make sub-module edges a DAG not a chain,\nand let independent halves be siblings. Splitting a file while consumers\nstill transitively need all parts is a pure loss (import preamble + olean\noverhead ×N). File-size discipline (~1,000–1,500-line ceiling) is about\nedit-iteration latency and parallelism, not cumulative CPU.\n\n### 6. Standalone lemma extraction \u002F clean-context elaboration\nExtract an expensive mathlib call or a heavy algebraic step into a\n`private lemma` with a minimal signature: instances resolve once, the call\nsite is a cheap application, and each lemma gets its own heartbeat budget.\nThis is also the escape from single-expensive-unification walls. Related:\nkeep membership\u002Fproof arguments out of heavy dependent surfaces; avoid\npartially-applied heavy theorems with pinned late implicits; prefer small\nconstructor lemmas over monolithic wired-up `abbrev`s.\n\n### 7. Statement hygiene that doubles as perf\n- >10 named hypotheses on a theorem → compress (structure bundle, typeclass\n  instances, caller-side `norm_num`, definitional `let`s). LLM agents don't\n  feel signature pain — one theorem reached 85 hypotheses \u002F 539-line\n  signature before anyone flagged it.\n- Unused section variables \u002F auto-bound instances are per-declaration\n  instance-search cost; keep the linter at zero.\n- rfl `_def` lemmas instead of `simp only [thedef]` unfolding of heavy\n  definitions.\n\n### 8. Fold a hypothesis type to the abbrev its consumer expects\nThe single highest-yield statement-level fix found so far (−98% elaboration,\nthree times). **Precondition:** a hypothesis is written in fully *unfolded*\nform, and the **conclusion feeds it into a dependent term** whose own signature\ndeclares that argument through an `abbrev`. Lean then discharges the\nunfolded-vs-abbrev defeq for the entire binder block, repeatedly.\n\n```lean\n-- costly: hypothesis unfolded, but `perturb` declares its arg as `FluxIntegrable U a u`\ntheorem foo (hu : ∀ φ : Test U, IntegrableOn (fun x => ⟪A x (u.grad x), φ.grad x⟫) U) :\n    P (perturb u w hu) = ...\n-- cheap: same proposition, stated the way the consumer expects\ntheorem foo (hu : FluxIntegrable U a u) : P (perturb u w hu) = ...\n```\n\nBecause the abbrev is definitionally the term, **this is notation, not\nsemantics**: the statement is unchanged and no consumer needs touching. Verify\nwith a full build anyway. The tell is verbosity *plus* dependent use — a sibling\nwith the identical unfolded block but no dependent consumer costs ~0 ms, so do\nnot \"clean up\" verbose binders that nothing consumes; you will gain nothing.\n\n**Sweeping for it:** grep is too weak (the unfolded text varies with binder\nnames and formatting). Parse instead — for each declaration, split the signature\nat the top-level `:` with a paren-depth counter, then flag any explicit binder\nwhose type is long (>90 chars) and contains `fun`\u002F`∀` **and** whose name occurs\nin the conclusion. On a 600k-line repo that yielded 42 candidates in 22 files;\nprofiling showed all but three had elaboration \u003C450 ms. Expect a low hit rate\nand profile before editing — the detector finds the shape, not the cost.\n\n### 9. Name the function in `congr`\n`congr`\u002F`congr 1` searches for a congruence decomposition. When you already know\nwhich function is being peeled, name it: `refine congrArg f ?_`. Same subgoals,\nno search.\n\n```lean\ncongr 1                                  -- 5.6s\nrefine congrArg (· ^ (1 \u002F p.toReal)) ?_  -- ~0s, goal `X = Y` as before\n```\n\nBare `congrArg _ ?_` usually fails to infer `f` — supply it (`congrArg Real.sqrt`,\n`congrArg (HMul.hMul _)`, `congrArg (· ^ e)`). Typical goals: `f a = f b` after a\n`rw` through an `rfl`-lemma, or after a `change`. Screen a repo by profiling\nmodules whose build-wall is ≥10s and which contain `congr`, then grep the profile\nfor `Tactic.congr took` — costs cluster bimodally at either \u003C100 ms or >2.5s, so\nthe expensive ones are unmistakable. Measured: 9.10s → 0.85s, 8.28s → 3.28s,\n6.35s → 0.65s.\n\n## The negative catalog — do not retry these\n\n- `set_option maxHeartbeats` \u002F `synthInstance.maxHeartbeats` bumps: changes\n  the failure threshold, not the cost. Treat a default-heartbeat failure as a\n  design signal. If the repository bans overrides, treat that as a hard rule.\n- `attribute [reducible]` on instances: shifts synthesis cost to defeq checks.\n- Splitting a slow file \"for performance\" without import\u002Fvariable-block\n  changes: cumulative CPU stays flat or rises.\n- Section-scoped `private instance` caches: inert, silently.\n- \"Backup\" caches for derived classes (`FiniteDimensional` alongside an\n  existing chain): regressed when tried.\n- Blind unused-import removal from grep lists: ~50% false positives; the\n  single biggest predicted win of one audit broke the build.\n- Structural dedup\u002Fhelper extraction from similarity audits: 2 of 3 failed\n  line-by-line inspection; discount such candidates 50–70%.\n- Tuning namespace orchestrator\u002Ffacade files: their cost is olean\n  deserialization; splitting moves it around.\n- Chasing \"diffuse typeclass\" files (thousands of sub-100ms searches, no\n  dominant head-class): proof restructuring left 8.5s → 8.5s. This is the\n  structural floor; accept it or reconsider the ambient types (see\n  `lean-learnings`).\n- Trusting a profile taken while other agents\u002Fusers use the CPUs, or\n  comparing a parallel batch profile with a serial one.\n- `#print axioms` (or other `#`-commands) left in source files: they re-run\n  at every rebuild — measured at 98% of one module's elaboration cost. Put\n  axiom audits in probe files outside the build root.\n\n## Sharp edges\n\n- **`touch` does not reliably invalidate** because Lake uses content hashes.\n  Use a repository-provided guarded invalidation command. If none exists,\n  resolve and remove only the exact project-owned module artifacts after\n  confirming the path cannot enter a dependency tree.\n- **Do not use `lake clean` for profiling.** It can erase dependency caches.\n  Invalidate only the repository-owned artifacts needed for the measurement,\n  under the repository's authorization rules.\n- **Profile totals don't sum to wall-clock**: olean serialization and IR\n  compilation are uncategorized. Use the phase breakdown to pick the lever,\n  wall-clock\u002FA-B to judge success.\n- `lean --profile` truncates events under 100ms; diffuse files underreport in\n  per-decl listings but show in the cumulative block. For per-declaration\n  attribution of unattributed elaboration time, rerun with\n  `-D trace.profiler.output=\u003Cfile>.json`.\n- **Elaboration cost compounds with downstream load**: files get slower with\n  zero edits as new callers exercise their theorem surfaces. A regression\n  with no proportional line growth is load compounding or contention, not\n  necessarily new bad code — check predicted (Δlines × prior ms\u002Fline) vs\n  actual ΔCPU before hunting a culprit file.\n- **Compute which bound you are under before optimizing anything.** Two\n  numbers: the work-floor (`total CPU \u002F cores`) and the critical chain\n  (longest weighted import path). The larger one is your wall-clock. The same\n  repo can be **chain-bound on a dev box and work-bound in CI** — one measured\n  case: 11,350s CPU \u002F 1,767s chain is chain-bound on 8 cores (floor 1,419s, so\n  only on-chain fixes help) but work-bound on a 4-core runner (floor 2,838s, so\n  *every* CPU saving converts). Off-chain work is not worthless; it is worthless\n  *for the machine shape where the chain dominates*. Say which one you optimized\n  when you report a win.\n- Cumulative-CPU savings convert to wall-clock only through the critical\n  path; under ~5× parallelism much of a saved file's time was already\n  overlapped. When the heavy tail is flat, further per-file work has\n  diminishing wall-clock returns.\n\n## Repository-wide mode\n\nFor a repo-wide effort (not a single hot file):\n\n1. **Snapshot first** (lean-elaboration-test), then triage the top-30 into\n   cost classes: include-block typeclass families (cache), tactic-bound\n   arithmetic (lever 2), simp-bound (lever 3), import-bound (lever 1 on\n   consumers, or leave), orchestrators\u002Ffacades (leave), genuine analytic\n   content (leave), diffuse-typeclass (leave\u002Faccept).\n2. Fix the **roots**, expect transitive gains; if the ten downstream files\n   don't improve, that's diagnostic, not bad luck.\n3. **One intervention per commit**, perf-only commits (no statement changes —\n   if a proof restructuring seems needed, profile first and ask), A\u002FB\n   evidence in the commit or report.\n4. Re-run the snapshot at matched parallelism to score the work; write\n   the dated report; keep the heavy-tail tier counts (≥10\u002F20\u002F30s) as the\n   local trend metric.\n5. **Codify demonstrated local invariants in the repo's agent instructions** —\n   for example, caches in measured hot areas or profiling before a split.\n   Keep local policy separate from portable guidance.\n6. Know when to stop: when the tail is 3 files of diffuse typeclass and the\n   only lever left is the critical path, further per-file tuning is not worth\n   agent time.\n",{"name":5,"description":7},"master","49e49abf2f670d429e0b7e2c0349739c3fdd5cbe","skills\u002Flean-elaboration",5,"https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium","https:\u002F\u002Fgithub.com\u002Fstanfish06","https:\u002F\u002Fwww.stanfish.dev\u002F","2026-11-14 21:31:37",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add stanfish06\u002Fskillquarium --skill lean-elaboration",{"tool":39,"command":40},"bunx","bunx skills add stanfish06\u002Fskillquarium --skill lean-elaboration",{"tool":42,"command":43},"pnpm","pnpm dlx skills add stanfish06\u002Fskillquarium --skill lean-elaboration","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Flean-elaboration\u002FSKILL.md",true,[47,53,57,61,65,69,73,77],{"path":48,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":51,"sourceHtmlUrl":52},"agents\u002Fopenai.yaml","REFERENCE","参考文档",263,"https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Flean-elaboration\u002Fagents\u002Fopenai.yaml",{"path":54,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":55,"sourceHtmlUrl":56},"INDEX.md",2990,"https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Flean-elaboration\u002FINDEX.md",{"path":58,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":16},"LICENSE","许可证",18656,{"path":62,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":63,"sourceHtmlUrl":64},"LICENSES\u002FApache-2.0.txt",11358,"https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Flean-elaboration\u002FLICENSES\u002FApache-2.0.txt",{"path":66,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":67,"sourceHtmlUrl":68},"PROVENANCE.md",2674,"https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Flean-elaboration\u002FPROVENANCE.md",{"path":70,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":71,"sourceHtmlUrl":72},"references\u002Fevidence.md",7595,"https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Flean-elaboration\u002Freferences\u002Fevidence.md",{"path":74,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":75,"sourceHtmlUrl":76},"SOURCES.md",1513,"https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Flean-elaboration\u002FSOURCES.md",{"path":78,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":79,"sourceHtmlUrl":80},"THIRD_PARTY_NOTICES.md",2165,"https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Flean-elaboration\u002FTHIRD_PARTY_NOTICES.md",[82,90,99,106,113,120],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":20},"01M76ZJTRVA456GD7K8Y3EP82H","zarr-python","Stores and queries chunked N-D scientific arrays with Zarr-Python 3, including codecs, sharding, S3\u002FGCS storage, and NumPy\u002FDask\u002FXarray integration. Use for array layout, bounded I\u002FO, format migration, or scientific metadata preservation.","MIT","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fzarr-python\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":95,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":20},"01M76ZJQZ15Q1HKC5V85NHE325","yeet","Publish local changes to GitHub by confirming scope, committing intentionally, pushing the branch, and opening a draft PR through the GitHub app from this plugin, with `gh` used only as a fallback where connector coverage is insufficient.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fyeet\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fyeet\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":20},"01M76ZJ8ASZ4QYQ70Y6SBA4Z4S","xarray","N-dimensional labeled arrays and datasets in Python. Built on top of NumPy and Dask. It introduces labels in the form of dimensions, coordinates, and attributes on top of raw NumPy-like arrays, making data analysis in physical sciences more intuitive and less error-prone. Use for working with multi-dimensional scientific data, NetCDF\u002FGRIB\u002FZarr files, climate\u002Fweather\u002Foceanographic datasets, remote sensing, geospatial imaging, large out-of-memory datasets with Dask, and labeled array operations.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fxarray\u002FSKILL.md",[],[],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":20},"01M76ZHFBXD6VXPQ02VCEG202B","writing-mstest-tests","Use when asked to fix, rewrite, update, improve, modernize, show corrected code for, or explain existing MSTest tests or MSTest-specific configuration. Use for \"review\" when corrected code or edits are wanted, even for one pasted assertion or passing tests with bad failure output. Covers expected\u002Factual labels; generic Boolean, collection, string, numeric, null, identity, exception, hard-cast, and object[] checks; TestContext\u002Flifecycle; timeout\u002Fcancellation; OS\u002FCI conditions, retry, cleanup, parallelization, MSTest.Sdk project setup, and MSTESTxxxx. Honor the installed MSTest version. DO NOT USE to design new test cases (code-testing), perform report-only audits, create project files rather than explain MSTest setup, run tests, migrate frameworks, or handle non-MSTest\u002Fnon-.NET code.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fwriting-mstest-tests\u002FSKILL.md",[],[],{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":119,"publishedAt":20},"01M76ZDFDF4N88RH6HSYGS7GP2","wgs-prs","End-to-end WGS to polygenic risk score pipeline. Takes paired-end FASTQ files (or a pre-existing VCF) through nf-core\u002Fsarek for variant calling, applies VCF QC (normalisation, hard filtering, Ti\u002FTv and Het\u002FHom checks), then computes polygenic risk scores via the PGS Catalog. Fills the FASTQ to VCF gap upstream of the gwas-prs skill.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fwgs-prs\u002FSKILL.md",[],[],{"skillNo":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":124,"sourceHtmlUrl":125,"categories":126,"keywords":127,"publishedAt":20},"01M76ZCC1SC68J42QK4MDC8RCG","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fwebapp-testing\u002FSKILL.md",[],[]]