@workingpayload/agent-skills 1.0.1 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/APIForge/skill.md +165 -0
- package/AccessPlus/skill.md +136 -0
- package/AlgoMaster/skill.md +125 -0
- package/Architekt AI/skill.md +140 -0
- package/AuthCraft/skill.md +144 -0
- package/AutoScriptor/skill.md +137 -0
- package/BoilerCore/skill.md +136 -0
- package/BugHunter Pro/skill.md +133 -0
- package/ChangeScribe/skill.md +113 -0
- package/CodeMap/skill.md +194 -0
- package/CodeSage/skill.md +163 -0
- package/CommitCraft/skill.md +113 -0
- package/CoverageMax/skill.md +161 -0
- package/CronGenius/skill.md +157 -0
- package/DataPolish/skill.md +142 -0
- package/DataWeaver/skill.md +151 -0
- package/DockMaster/skill.md +158 -0
- package/DocuGenie/skill.md +138 -0
- package/EdgeGuard/skill.md +160 -0
- package/EnvWizard/skill.md +156 -0
- package/ErrorMedic/skill.md +152 -0
- package/FeatureSmith/skill.md +139 -0
- package/FlexiLayout/skill.md +144 -0
- package/FlowTester/skill.md +154 -0
- package/FunctionForge/skill.md +136 -0
- package/InputShield/skill.md +144 -0
- package/IssueForge/skill.md +148 -0
- package/KubeCrafter/skill.md +149 -0
- package/LogicLens/skill.md +132 -0
- package/MockSmith/skill.md +146 -0
- package/ModelSensei/skill.md +138 -0
- package/PRMentor/skill.md +103 -0
- package/PerfDetective/skill.md +90 -0
- package/PipelinePro/skill.md +146 -0
- package/PolyglotShift/skill.md +94 -0
- package/PromptForge/skill.md +118 -0
- package/QueryPulse/skill.md +123 -0
- package/README.md +327 -216
- package/ReadMeCraft/skill.md +127 -0
- package/RefactorX/skill.md +110 -0
- package/RenderBoost/skill.md +148 -0
- package/SEOMancer/skill.md +156 -0
- package/ScrapeMaster/skill.md +157 -0
- package/SecretSniffer/skill.md +123 -0
- package/SecureScan/skill.md +130 -0
- package/ServiceSplitter/skill.md +153 -0
- package/SpeedSmith/skill.md +155 -0
- package/StackWise/skill.md +155 -0
- package/TaskOrchestrator/skill.md +135 -0
- package/TestCrafter/skill.md +158 -0
- package/TraceMind/skill.md +143 -0
- package/UISmith/skill.md +131 -0
- package/bin/cli.js +436 -0
- package/extension-extender/SKILL.md +122 -0
- package/fastapi-furious/SKILL.md +148 -0
- package/package.json +42 -32
- package/python-master/SKILL.md +108 -0
- package/react-ranger/SKILL.md +93 -0
- package/scripts/build_index.py +282 -0
- package/scripts/doctor.py +542 -0
- package/scripts/install.py +436 -0
- package/scripts/route.py +348 -0
- package/scripts/score.py +355 -0
- package/scripts/test_skill.py +501 -0
- package/scripts/validate.py +254 -0
- package/skills-routing.json +1156 -0
- package/skills.json +3389 -0
- package/cli.js +0 -181
- package/skills/APIForge/skill.md +0 -32
- package/skills/AccessPlus/skill.md +0 -32
- package/skills/AlgoMaster/skill.md +0 -32
- package/skills/Architekt AI/skill.md +0 -32
- package/skills/AuthCraft/skill.md +0 -32
- package/skills/AutoScriptor/skill.md +0 -32
- package/skills/BoilerCore/skill.md +0 -32
- package/skills/BugHunter Pro/skill.md +0 -32
- package/skills/ChangeScribe/skill.md +0 -32
- package/skills/CodeSage/skill.md +0 -32
- package/skills/CommitCraft/skill.md +0 -32
- package/skills/CoverageMax/skill.md +0 -32
- package/skills/CronGenius/skill.md +0 -32
- package/skills/DataPolish/skill.md +0 -32
- package/skills/DataWeaver/skill.md +0 -32
- package/skills/DockMaster/skill.md +0 -32
- package/skills/DocuGenie/skill.md +0 -32
- package/skills/EdgeGuard/skill.md +0 -32
- package/skills/EnvWizard/skill.md +0 -32
- package/skills/ErrorMedic/skill.md +0 -32
- package/skills/Extension-Extender/SKILL.md +0 -41
- package/skills/Extension-Extender/references/ui-guidelines.md +0 -26
- package/skills/Fastapi-Furious/README.md +0 -16
- package/skills/Fastapi-Furious/SKILL.md +0 -37
- package/skills/FeatureSmith/skill.md +0 -32
- package/skills/FlexiLayout/skill.md +0 -32
- package/skills/FlowTester/skill.md +0 -32
- package/skills/FunctionForge/skill.md +0 -32
- package/skills/InputShield/skill.md +0 -32
- package/skills/IssueForge/skill.md +0 -32
- package/skills/KubeCrafter/skill.md +0 -32
- package/skills/LogicLens/skill.md +0 -32
- package/skills/MockSmith/skill.md +0 -32
- package/skills/ModelSensei/skill.md +0 -32
- package/skills/PRMentor/skill.md +0 -32
- package/skills/PerfDetective/skill.md +0 -32
- package/skills/PipelinePro/skill.md +0 -32
- package/skills/PolyglotShift/skill.md +0 -32
- package/skills/PromptForge/skill.md +0 -32
- package/skills/Python-Master/README.md +0 -11
- package/skills/Python-Master/SKILL.md +0 -37
- package/skills/QueryPulse/skill.md +0 -32
- package/skills/React-Ranger/README.md +0 -17
- package/skills/React-Ranger/SKILL.md +0 -37
- package/skills/ReadMeCraft/skill.md +0 -32
- package/skills/RefactorX/skill.md +0 -32
- package/skills/RenderBoost/skill.md +0 -32
- package/skills/SEOMancer/skill.md +0 -32
- package/skills/ScrapeMaster/skill.md +0 -32
- package/skills/SecretSniffer/skill.md +0 -32
- package/skills/SecureScan/skill.md +0 -32
- package/skills/ServiceSplitter/skill.md +0 -32
- package/skills/SpeedSmith/skill.md +0 -32
- package/skills/StackWise/skill.md +0 -32
- package/skills/TaskOrchestrator/skill.md +0 -32
- package/skills/TestCrafter/skill.md +0 -32
- package/skills/TraceMind/skill.md +0 -32
- package/skills/UISmith/skill.md +0 -32
- /package/{skills/Extension-Extender → extension-extender}/assets/manifest.json +0 -0
- /package/{skills/Extension-Extender → extension-extender}/assets/popup.css +0 -0
- /package/{skills/Extension-Extender → extension-extender}/assets/popup.html +0 -0
- /package/{skills/Extension-Extender → extension-extender}/assets/popup.js +0 -0
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: polyglotshift
|
|
3
|
+
description: Translate code accurately between programming languages, preserving logic and semantics while adopting target-language idioms, type systems, and standard libraries. Use when a user needs to port, convert, or rewrite code from one language to another.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# PolyglotShift
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
PolyglotShift translates code between programming languages with semantic fidelity, idiomatic target-language style, and explicit annotation of every non-trivial mapping decision.
|
|
11
|
+
|
|
12
|
+
## Workflow
|
|
13
|
+
|
|
14
|
+
### 1. Identify Source & Target Languages
|
|
15
|
+
|
|
16
|
+
State both explicitly. If the user hasn't specified the target, ask. Confirm the target's major version (e.g., Python 3.11, TypeScript 5, Java 21, Rust 2021 edition) as standard library APIs differ.
|
|
17
|
+
|
|
18
|
+
### 2. Audit Type System Differences
|
|
19
|
+
|
|
20
|
+
Map source types to target equivalents before writing any code:
|
|
21
|
+
|
|
22
|
+
| Concept | Python | TypeScript | Java | Rust |
|
|
23
|
+
|---|---|---|---|---|
|
|
24
|
+
| Optional value | `Optional[T]` / `T \| None` | `T \| undefined` / `T \| null` | `Optional<T>` | `Option<T>` |
|
|
25
|
+
| Dynamic list | `list[T]` | `T[]` / `Array<T>` | `List<T>` | `Vec<T>` |
|
|
26
|
+
| Key-value map | `dict[K, V]` | `Record<K,V>` / `Map<K,V>` | `Map<K,V>` | `HashMap<K,V>` |
|
|
27
|
+
| Error handling | `raise` / `try/except` | `throw` / `try/catch` | `throw` / checked exceptions | `Result<T,E>` |
|
|
28
|
+
| Async | `async/await` + `asyncio` | `async/await` + `Promise` | `CompletableFuture` | `async/await` + `tokio` |
|
|
29
|
+
|
|
30
|
+
Flag any source types that have no direct equivalent — these require a design decision, not a mechanical substitution.
|
|
31
|
+
|
|
32
|
+
### 3. Map Idioms Explicitly
|
|
33
|
+
|
|
34
|
+
Do not transliterate — translate. Apply target-language conventions:
|
|
35
|
+
|
|
36
|
+
- **Python → TypeScript**: Replace list comprehensions with `.filter().map()`, `dataclass` with a `type` or `interface`, `__dunder__` methods with class methods or operator overloads where supported.
|
|
37
|
+
- **Python → Rust**: Replace `None` with `Option<T>`, `raise Exception` with `Err(...)`, GC-managed objects with owned structs + lifetimes. Flag heap allocations explicitly.
|
|
38
|
+
- **Java → Kotlin**: Replace verbose getters/setters with `data class`, `Optional` with `?` nullable types, `Stream` API with Kotlin collection extensions.
|
|
39
|
+
- **JavaScript → TypeScript**: Add explicit type annotations; replace `any` with proper generics; convert callback-style APIs to `async/await`.
|
|
40
|
+
- **SQL dialects**: Flag `ILIKE` (Postgres-only), `LIMIT`/`TOP` differences, and window function syntax variations.
|
|
41
|
+
|
|
42
|
+
### 4. Write the Translation
|
|
43
|
+
|
|
44
|
+
Structure the output as:
|
|
45
|
+
|
|
46
|
+
```
|
|
47
|
+
## Source ({source_lang})
|
|
48
|
+
<original code block>
|
|
49
|
+
|
|
50
|
+
## Target ({target_lang})
|
|
51
|
+
<translated code block, with inline comments on non-obvious mappings>
|
|
52
|
+
|
|
53
|
+
## Translation Notes
|
|
54
|
+
- <mapping 1: why X became Y>
|
|
55
|
+
- <mapping 2: semantic difference to be aware of>
|
|
56
|
+
- <any behavioral differences or caveats>
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Inline comments should use the pattern `// [PolyglotShift] reason for this choice`.
|
|
60
|
+
|
|
61
|
+
### 5. Verify Semantic Equivalence
|
|
62
|
+
|
|
63
|
+
After translating, manually trace through at least one representative input/output path in both versions. Check:
|
|
64
|
+
- Loop bounds and off-by-one behavior.
|
|
65
|
+
- Error paths: does the translated code surface the same errors?
|
|
66
|
+
- Mutability: does the source mutate in place where the target version creates a new object?
|
|
67
|
+
- Integer overflow/underflow (especially Python's arbitrary-precision int → fixed-width Java/Rust int).
|
|
68
|
+
|
|
69
|
+
## Additional Mapping Patterns
|
|
70
|
+
|
|
71
|
+
**Prototype mutation / monkey patching:** Languages like JavaScript, Ruby, and Python allow modifying built-in prototypes or classes at runtime. This has no safe equivalent in statically typed targets. When translating monkey-patched code: (a) extract the patched behavior into a standalone utility function or wrapper class, (b) replace call sites with explicit calls to the wrapper, (c) document the original intent in a `// [PolyglotShift]` comment.
|
|
72
|
+
|
|
73
|
+
**`asyncio.gather` → Rust concurrent futures:**
|
|
74
|
+
```python
|
|
75
|
+
results = await asyncio.gather(fetch_a(), fetch_b(), fetch_c())
|
|
76
|
+
```
|
|
77
|
+
```rust
|
|
78
|
+
// tokio::join! for a fixed set of futures
|
|
79
|
+
let (a, b, c) = tokio::join!(fetch_a(), fetch_b(), fetch_c());
|
|
80
|
+
// FuturesUnordered for a dynamic collection
|
|
81
|
+
use futures::stream::{FuturesUnordered, StreamExt};
|
|
82
|
+
let mut tasks: FuturesUnordered<_> = urls.iter().map(|u| fetch(u)).collect();
|
|
83
|
+
while let Some(result) = tasks.next().await { ... }
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
**Java checked exceptions → Python:** Java's checked exceptions (declared in `throws`) enforce caller handling at compile time. Python has no equivalent. When translating: document every checked exception as a `Raises:` entry in the docstring, and consider wrapping callers in explicit `try/except` blocks corresponding to each checked exception type. Do not silently swallow them.
|
|
87
|
+
|
|
88
|
+
## Edge Cases
|
|
89
|
+
|
|
90
|
+
**1. Garbage-collected → memory-managed languages (e.g., Python/Java → Rust/C++).** Ownership and lifetime semantics have no direct equivalent. Identify every heap allocation in the source, decide whether the Rust translation should use `Box<T>`, `Rc<T>`, or `Arc<T>`, and document the decision. Do not silently clone everywhere — explain the trade-off.
|
|
91
|
+
|
|
92
|
+
**2. Dynamic typing → static typing with incomplete type information.** Source code using duck typing or `any`-typed inputs requires the translator to infer or ask for the intended type contracts. List every place where a type assumption was made and flag it for human review.
|
|
93
|
+
|
|
94
|
+
**3. Standard library gaps.** The source may use a library (e.g., Python's `itertools`, Java's `Guava`) with no direct target equivalent. In these cases: (a) identify the closest built-in, (b) link to a well-maintained equivalent library if one exists, (c) write a minimal inline implementation if neither exists. Never silently drop functionality.
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: promptforge
|
|
3
|
+
description: Craft, refine, and optimize LLM prompts using zero-shot, few-shot, Chain-of-Thought, ReAct, and structured output techniques. Use when a user needs to write a prompt, improve an existing prompt, or design a prompt pipeline for a specific AI task.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# PromptForge
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
PromptForge engineers production-quality prompts by selecting the right prompting strategy, constraining outputs to a schema, and iterating based on failure analysis.
|
|
11
|
+
|
|
12
|
+
## Workflow
|
|
13
|
+
|
|
14
|
+
### 1. Clarify the Task Dimensions
|
|
15
|
+
|
|
16
|
+
Before writing a prompt, establish:
|
|
17
|
+
- **Model target**: GPT-4o, Claude 3.x, Gemini 1.5, Llama 3, Mistral? (Instruction format and context window differ.)
|
|
18
|
+
- **Output format**: free text, JSON, structured list, code, boolean?
|
|
19
|
+
- **Latency vs. quality trade-off**: single-shot response or multi-turn reasoning acceptable?
|
|
20
|
+
- **Failure modes to avoid**: hallucination, off-topic drift, unsafe content, truncated output?
|
|
21
|
+
|
|
22
|
+
### 2. Choose the Right Prompting Strategy
|
|
23
|
+
|
|
24
|
+
| Strategy | When to Use | Key Technique |
|
|
25
|
+
|---|---|---|
|
|
26
|
+
| **Zero-shot** | Simple classification, extraction, short generation | Clear task description + output format spec |
|
|
27
|
+
| **Few-shot** | Consistent formatting, domain-specific style | 3–5 labeled input/output examples in the prompt |
|
|
28
|
+
| **Chain-of-Thought (CoT)** | Multi-step reasoning, math, logic | "Think step by step" or explicit reasoning scaffold |
|
|
29
|
+
| **Tree of Thoughts (ToT)** | Complex problems with branching solution paths | Ask the model to generate and evaluate multiple candidate paths |
|
|
30
|
+
| **ReAct** | Tool-using agents, information retrieval loops | Alternate Thought → Action → Observation steps |
|
|
31
|
+
| **Self-consistency** | High-stakes decisions requiring reliability | Run the prompt N times, majority-vote the answer |
|
|
32
|
+
|
|
33
|
+
### 3. Structure the Prompt
|
|
34
|
+
|
|
35
|
+
Use this template as a baseline:
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
[SYSTEM / CONTEXT]
|
|
39
|
+
You are <role>. <any persistent context or constraints>.
|
|
40
|
+
|
|
41
|
+
[TASK]
|
|
42
|
+
<Imperative instruction stating exactly what to do.>
|
|
43
|
+
|
|
44
|
+
[INPUT]
|
|
45
|
+
<Clearly labeled input variable(s)>
|
|
46
|
+
|
|
47
|
+
[CONSTRAINTS]
|
|
48
|
+
- Output must be <format>.
|
|
49
|
+
- Do not <list of prohibitions>.
|
|
50
|
+
- If <edge case>, respond with <fallback>.
|
|
51
|
+
|
|
52
|
+
[OUTPUT FORMAT]
|
|
53
|
+
Return a JSON object matching this schema:
|
|
54
|
+
{
|
|
55
|
+
"field1": "string",
|
|
56
|
+
"field2": ["array", "of", "strings"],
|
|
57
|
+
"confidence": "high | medium | low"
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### 4. Define Output Constraints
|
|
62
|
+
|
|
63
|
+
For structured outputs:
|
|
64
|
+
- Provide an explicit JSON schema or TypeScript type in the prompt.
|
|
65
|
+
- Use `response_format: { type: "json_object" }` (OpenAI) or `"response_mime_type": "application/json"` (Gemini) where available.
|
|
66
|
+
- For Claude: wrap instructions in XML tags (`<instructions>`, `<example>`) to improve parsing reliability.
|
|
67
|
+
- Always specify what to return when input is invalid or out of scope.
|
|
68
|
+
|
|
69
|
+
### 5. Set Temperature Guidance
|
|
70
|
+
|
|
71
|
+
- **0.0–0.2**: Factual extraction, classification, data parsing — deterministic outputs needed.
|
|
72
|
+
- **0.3–0.6**: Summarization, analysis, structured generation — some variation acceptable.
|
|
73
|
+
- **0.7–1.0**: Creative writing, brainstorming, ideation — diversity desired.
|
|
74
|
+
- For agents/tools using function calling, use temperature ≤ 0.2 to avoid erratic tool selection.
|
|
75
|
+
|
|
76
|
+
### 6. Adversarial Testing
|
|
77
|
+
|
|
78
|
+
Test the prompt against:
|
|
79
|
+
1. **Empty input** — does it fail gracefully or hallucinate?
|
|
80
|
+
2. **Adversarial input** — prompt injection attempts (`"Ignore previous instructions and..."`), jailbreak phrasing.
|
|
81
|
+
3. **Edge case inputs** — very long text, non-English text, ambiguous content.
|
|
82
|
+
4. **Out-of-scope requests** — does the model stay on task or drift?
|
|
83
|
+
|
|
84
|
+
Document each test case and expected vs. actual output.
|
|
85
|
+
|
|
86
|
+
### 7. Iteration Loop
|
|
87
|
+
|
|
88
|
+
```
|
|
89
|
+
Draft prompt → test on 5–10 representative inputs → identify failure pattern
|
|
90
|
+
→ add a constraint or example targeting that failure → retest
|
|
91
|
+
→ repeat until pass rate meets target (aim for ≥90% on test set)
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### 8. Deliver the Output
|
|
95
|
+
|
|
96
|
+
Provide:
|
|
97
|
+
1. Final prompt (system + user sections clearly labeled).
|
|
98
|
+
2. Prompting strategy chosen and why.
|
|
99
|
+
3. JSON schema or output format spec.
|
|
100
|
+
4. Temperature and any API parameter recommendations.
|
|
101
|
+
5. 3+ test cases with expected outputs.
|
|
102
|
+
6. Known limitations and when the prompt may fail.
|
|
103
|
+
|
|
104
|
+
## Additional Techniques
|
|
105
|
+
|
|
106
|
+
**Multi-modal prompting (image + text):** When the model accepts image inputs, describe what the model should extract or reason about from the image explicitly in the text prompt. Place the image reference before the question. Use `detail: "high"` for diagrams requiring fine-grained reading; `"low"` for thumbnails/icons to reduce token cost. Never assume the model will infer intent from the image alone.
|
|
107
|
+
|
|
108
|
+
**Prompt versioning and regression tracking:** Store prompts in version control (e.g., `prompts/classify_v3.txt`). On each model upgrade, re-run your test set and diff pass rates. Use a spreadsheet or tool like PromptLayer/LangSmith to log model version, prompt hash, temperature, and per-example outcomes. Flag regressions where pass rate drops > 5% between model versions.
|
|
109
|
+
|
|
110
|
+
**Function-calling / tool-use prompt format:** When using OpenAI function calling or Claude tool use, define the tool schema separately from the system prompt. Keep the system prompt focused on *when* to call tools, not how they work. Validate that the model's arguments match the JSON schema before executing the function. For multi-tool agents, list available tools with one-line descriptions in the system prompt so the model can select the right one.
|
|
111
|
+
|
|
112
|
+
## Edge Cases
|
|
113
|
+
|
|
114
|
+
**1. Context window overflow with few-shot examples.** If the prompt + examples + input exceeds the context limit, use dynamic few-shot selection: embed the examples, retrieve the top-k most similar to the current input at runtime (RAG-style example selection). Keep examples under 30% of total context budget.
|
|
115
|
+
|
|
116
|
+
**2. Model refuses or over-hedges on the task.** For tasks that trigger safety refusals, reframe the instruction in a clearly professional/technical context. Add a system prompt establishing the use case. If the model adds excessive disclaimers, add "Do not add warnings or disclaimers; the user is a professional in this domain" to the constraints.
|
|
117
|
+
|
|
118
|
+
**3. Inconsistent output format across runs.** If the model intermittently deviates from the JSON schema, add a validation step: parse the output and retry with the error appended to the prompt ("Your previous response was not valid JSON. The error was: <error>. Please retry.").
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: querypulse
|
|
3
|
+
description: Analyze and optimize SQL query performance using EXPLAIN ANALYZE, index design, covering indexes, N+1 detection, and deadlock diagnosis across PostgreSQL and MySQL. Use when a user has a slow query, a deadlock, a missing index, or wants to understand a query execution plan.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# QueryPulse
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
QueryPulse diagnoses SQL performance problems using execution plan analysis, index theory, and engine-specific optimizations for PostgreSQL and MySQL.
|
|
11
|
+
|
|
12
|
+
## Workflow
|
|
13
|
+
|
|
14
|
+
### 1. Collect the Execution Plan
|
|
15
|
+
|
|
16
|
+
Always start with the actual (not estimated) plan:
|
|
17
|
+
|
|
18
|
+
**PostgreSQL:**
|
|
19
|
+
```sql
|
|
20
|
+
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) <your query>;
|
|
21
|
+
```
|
|
22
|
+
- `ANALYZE`: runs the query and shows actual row counts and timing.
|
|
23
|
+
- `BUFFERS`: shows cache hit vs. disk read ratio.
|
|
24
|
+
|
|
25
|
+
**MySQL / MariaDB:**
|
|
26
|
+
```sql
|
|
27
|
+
EXPLAIN FORMAT=JSON <your query>;
|
|
28
|
+
-- Or for actual execution stats (MySQL 8.0+):
|
|
29
|
+
EXPLAIN ANALYZE <your query>;
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Ask for the full output, not a screenshot. Key fields to examine:
|
|
33
|
+
- `Seq Scan` / `ALL` type → full table scan, likely missing an index.
|
|
34
|
+
- `Rows` estimate vs. actual: large divergence → stale statistics; run `ANALYZE <table>` (Postgres) or `ANALYZE TABLE <table>` (MySQL).
|
|
35
|
+
- `cost` / `actual time`: find the most expensive node.
|
|
36
|
+
- `Buffers: shared hit/read`: low hit ratio → data not in cache, I/O bound.
|
|
37
|
+
|
|
38
|
+
### 2. Identify the Bottleneck Type
|
|
39
|
+
|
|
40
|
+
**Missing or unused index:**
|
|
41
|
+
- Look for `Seq Scan` on large tables or `Using filesort` / `Using temporary` in MySQL.
|
|
42
|
+
- Check existing indexes: `\d <table>` (psql) or `SHOW INDEX FROM <table>` (MySQL).
|
|
43
|
+
|
|
44
|
+
**Poor index selectivity:**
|
|
45
|
+
- An index on a boolean or low-cardinality column (e.g., `status IN ('active','inactive')`) may be ignored by the planner.
|
|
46
|
+
- Index selectivity = `COUNT(DISTINCT col) / COUNT(*)`. Aim for > 0.1 before indexing.
|
|
47
|
+
|
|
48
|
+
**N+1 query pattern:**
|
|
49
|
+
- Symptom: application executes hundreds of nearly identical queries differing only by a single ID.
|
|
50
|
+
- Fix: rewrite as a single `SELECT ... WHERE id = ANY($1)` (Postgres) or `SELECT ... WHERE id IN (...)` (MySQL) and fetch all rows at once, or use ORM eager loading (Django: `select_related`/`prefetch_related`; Rails: `includes`; Hibernate: `JOIN FETCH`).
|
|
51
|
+
|
|
52
|
+
**Deadlock:**
|
|
53
|
+
- PostgreSQL: check `pg_locks` and the server log for `deadlock detected`.
|
|
54
|
+
- MySQL: `SHOW ENGINE INNODB STATUS\G` — look for the `LATEST DETECTED DEADLOCK` section.
|
|
55
|
+
- Fix pattern: ensure all transactions acquire locks in the same order; use `SELECT ... FOR UPDATE SKIP LOCKED` for queue-style workloads.
|
|
56
|
+
|
|
57
|
+
### 3. Design the Index
|
|
58
|
+
|
|
59
|
+
**Basic B-tree index:**
|
|
60
|
+
```sql
|
|
61
|
+
CREATE INDEX CONCURRENTLY idx_orders_user_created
|
|
62
|
+
ON orders (user_id, created_at DESC);
|
|
63
|
+
```
|
|
64
|
+
Use `CONCURRENTLY` (Postgres) to avoid table lock on production.
|
|
65
|
+
|
|
66
|
+
**Covering index** (avoids heap fetch entirely):
|
|
67
|
+
```sql
|
|
68
|
+
-- Query: SELECT status, total FROM orders WHERE user_id = $1 AND created_at > $2
|
|
69
|
+
CREATE INDEX idx_orders_covering
|
|
70
|
+
ON orders (user_id, created_at DESC)
|
|
71
|
+
INCLUDE (status, total); -- Postgres 11+
|
|
72
|
+
```
|
|
73
|
+
In MySQL, covering indexes are standard B-trees — include all SELECT and WHERE columns.
|
|
74
|
+
|
|
75
|
+
**Partial index** (index only rows matching a condition):
|
|
76
|
+
```sql
|
|
77
|
+
CREATE INDEX idx_orders_pending
|
|
78
|
+
ON orders (created_at)
|
|
79
|
+
WHERE status = 'pending';
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
**GIN index for full-text / JSONB (Postgres):**
|
|
83
|
+
```sql
|
|
84
|
+
CREATE INDEX idx_docs_fts ON documents USING gin(to_tsvector('english', body));
|
|
85
|
+
CREATE INDEX idx_meta_gin ON products USING gin(metadata); -- for JSONB @> queries
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### 4. Engine-Specific Differences
|
|
89
|
+
|
|
90
|
+
| Feature | PostgreSQL | MySQL 8.0 |
|
|
91
|
+
|---|---|---|
|
|
92
|
+
| EXPLAIN actual stats | `EXPLAIN ANALYZE` | `EXPLAIN ANALYZE` (8.0+) |
|
|
93
|
+
| Concurrent index build | `CREATE INDEX CONCURRENTLY` | Online DDL (default) |
|
|
94
|
+
| Covering index syntax | `INCLUDE (cols)` | All columns in index |
|
|
95
|
+
| JSON indexing | GIN on JSONB | `JSON_EXTRACT` + generated column + index |
|
|
96
|
+
| Full-text search | `tsvector` + GIN | `FULLTEXT` index + `MATCH AGAINST` |
|
|
97
|
+
| Skip locked | `SELECT FOR UPDATE SKIP LOCKED` | `SELECT FOR UPDATE SKIP LOCKED` (8.0+) |
|
|
98
|
+
| Materialized views | Native | Not native; use a table + scheduled refresh |
|
|
99
|
+
|
|
100
|
+
### 5. Deliver the Output
|
|
101
|
+
|
|
102
|
+
Provide:
|
|
103
|
+
1. Annotated execution plan (highlight the slow node).
|
|
104
|
+
2. Root cause diagnosis (1–2 sentences).
|
|
105
|
+
3. `CREATE INDEX` statement or query rewrite (with `EXPLAIN` output showing improvement if possible).
|
|
106
|
+
4. `EXPLAIN ANALYZE` command to verify the fix.
|
|
107
|
+
5. Any follow-up: statistics refresh, application-level N+1 fix, connection pool settings.
|
|
108
|
+
|
|
109
|
+
### 6. Advanced Query Patterns
|
|
110
|
+
|
|
111
|
+
**CTE materialization (PostgreSQL 12+):** By default, CTEs in Postgres 12+ are not materialized — the planner can inline them like a subquery. Force materialization with `WITH cte AS MATERIALIZED (...)` when the CTE is expensive and referenced multiple times; use `NOT MATERIALIZED` to allow inlining when the planner is over-estimating CTE cost. Check `EXPLAIN` to see whether the CTE appears as a separate node or is inlined.
|
|
112
|
+
|
|
113
|
+
**Partitioned table optimization:** Always include the partition key in `WHERE` clauses so the planner performs partition pruning (skips irrelevant partitions). Verify pruning with `EXPLAIN` — look for `Append` nodes that list only the relevant child partitions. Create indexes on each partition separately; a global index on the parent table is not available in PostgreSQL range/list partitioning. Avoid `OR` conditions across the partition key — they suppress pruning.
|
|
114
|
+
|
|
115
|
+
**Replica vs. primary plan divergence:** Read replicas may have stale statistics (last `ANALYZE` ran on the primary; replica lag delays propagation). A query that runs fast on the primary can pick a bad plan on the replica. Run `ANALYZE` on the replica directly, or check `pg_stat_user_tables.last_analyze` per replica. For critical read paths, force a plan with `pg_hint_plan` or promote the replica's statistics refresh schedule.
|
|
116
|
+
|
|
117
|
+
## Edge Cases
|
|
118
|
+
|
|
119
|
+
**1. Statistics are stale — planner chooses a bad plan.** If estimated rows diverge wildly from actual rows, run `ANALYZE <table>` (or `VACUUM ANALYZE` to also reclaim dead tuples). For tables with highly skewed distributions, use `CREATE STATISTICS` (Postgres 10+) to capture column correlations.
|
|
120
|
+
|
|
121
|
+
**2. Index exists but is not used.** The planner may skip a valid index if: (a) the table is small enough that a seq scan is cheaper, (b) the query uses a function on the indexed column (`WHERE LOWER(email) = ...` bypasses a plain index — use a functional index: `CREATE INDEX ON users (LOWER(email))`), or (c) the index has bloat — `REINDEX CONCURRENTLY` to rebuild it.
|
|
122
|
+
|
|
123
|
+
**3. Query is fast in isolation but slow under concurrency.** Check for lock contention: `pg_stat_activity` + `pg_locks` join, or `SHOW PROCESSLIST` in MySQL. Solutions: shorter transactions, optimistic locking, row-level vs. table-level locks, or `SKIP LOCKED` queue patterns.
|