diff --git a/CHANGELOG.md b/CHANGELOG.md index eee57db..78a313e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,18 +9,27 @@ Format: [Semantic Versioning](https://semver.org). Dates: YYYY-MM-DD. ### Added +- `design-iac`: Infrastructure as Code design grounded in Kief Morris "Infrastructure as Code" (O'Reilly 2021) and NTNU IIKG3005 — IaC principles (immutable infra, idempotency, snowflake anti-pattern), module design, remote state management, drift detection and remediation, GitOps workflow, IaC testing (3 reference files) +- `tool-perf`: Performance engineering grounded in MIT 6.172 (Leiserson/Shun, Bentley Rules) and Brendan Gregg "Systems Performance" (USE Method, flamegraphs) — USE Method resource checklist, profiling tool selection by stack, flamegraph reading guide, Bentley Rules (5 categories), before/after benchmark workflow (3 reference files) +- `design-migration` — schema evolution: Added Kleppmann "Designing Data-Intensive Applications" Kap. 4+11 coverage — Forward/Backward Compatibility rules, Dual-Write problem and solutions, Change Data Capture (CDC/Debezium), Avro Schema Registry, Expand-Contract pattern; new `references/schema-evolution.md` +- plugin.json: 22 → 24 skills (v1.2.0 → v1.3.0); meta-help renumbered 1–24 + +- `design-observability`: Observability architecture skill grounded in Google SRE Books (Beyer et al.) and Observability Engineering (Majors/Fong-Jones) — SLO/SLI/Error-Budget, Golden Signals, OpenTelemetry tracing, Burn Rate alerting, Incident Response + blameless postmortem (4 reference files) +- `design-cicd`: CI/CD pipeline design grounded in "Accelerate" (Forsgren/Humble/Kim) and "Continuous Delivery" (Humble/Farley) — pipeline architecture, Blue-Green/Canary/Feature Flags decision tree, DORA metrics with benchmarks, Trunk-Based Development (3 reference files) +- `tool-a11y`: Accessibility audit grounded in WCAG 2.2 (W3C) and CMU HCII 05-332 — axe-core/Lighthouse, keyboard navigation, NVDA/VoiceOver screen reader testing, all 9 new WCAG 2.2 SC, EU Accessibility Act / BFSG / EN 301 549 compliance (3 reference files) +- `design-llm` + `review-llm`: LLM system design and audit grounded in Stanford CS224N, CMU 11-667 and Berkeley CS294-196 — RAG, fine-tuning, agents, evals, OWASP LLM Top 10, prompt injection (PR #14) +- `commands/design-ux.md` and `commands/review-ux.md`: missing command files added — slash-command discovery now works for both skills +- Skill discovery improvements: overlap disambiguation (review-app/review-arch/review-secure), German trigger phrases for review-arch and review-secure, scope guard for meta-sync +- `docs/gap-analysis.md`: status tracking table (✅ Erledigt / 🔲 Offen) for all planned skills +- `docs/academic-basis.md`: verified syllabi for all planned new skills (Stanford CS224N, CMU 11-667, Berkeley CS294-196, MIT 6.5940, MIT 6.5840, CMU 18-749, CMU 17-636, W3C WAI, NTNU IIKG3005, MIT 6.172, CMU 15-721, UT Austin CS395T) - `meta-create-skill`: new meta skill for building skills using the established methodology (topic → academic research → SKILL.md + references/) - All 9 skills with inline lookup tables now follow the consistent structure: SKILL.md = workflow only, `references/` = lookup material - - Round 1 (new `references/` directories): `design-ux`, `review-ux`, `tool-style` - - Round 2 (`curriculum-mapping.md` added): `design-secure`, `review-arch`, `review-secure`, `design-api`, `design-data`, `design-migration` -- `design-ux` and `review-ux` now have `commands/` entries (were missing, slash-command discovery now works) -- `docs/gap-analysis.md`: inventory of content gaps with academic source candidates -- `docs/academic-basis.md`: verified syllabi for 6 planned new skills (Stanford CS224N, CMU 11-667, Berkeley CS294-196, MIT 6.5940, MIT 6.5840, CMU 18-749, CMU 17-636, W3C WAI, NTNU IIKG3005, MIT 6.172, CMU 15-721, UT Austin CS395T) -- Feature Flags section in `claude/app-rules.md` and `reference/app-best-practices.md` (Kill Switch, Rollout-Reihenfolge, Flag-Hygiene, Tool-Vergleich) +- Feature Flags section in `claude/app-rules.md` and `reference/app-best-practices.md` - Mirror sync check in CI: `claude/` vs `plugins/dev/rules/` must be identical - MSW + Testing Library added to essential-rules.md testing stack - TLS zum DB-Server in essential-rules.md API & Datenbank section - Secrets rotation frequency (90 days) in `claude/app-rules.md` +- plugin.json: 17 → 22 skills; meta-help renumbered 1–22 ### Fixed diff --git a/README.md b/README.md index c7b4d42..2f4f1ea 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Opinionated best-practice rules for software projects — RAG systems, AI agents, data pipelines, full-stack web apps. Three detail levels: compact essential rules for `CLAUDE.md`, thematic rule files, and detailed reference docs. -Also a **Claude Code plugin**: install once, get 18 skills in every project. +Also a **Claude Code plugin**: install once, get 24 skills in every project. --- @@ -28,6 +28,7 @@ claude plugin install dev@gerald-dev-best-practices ## Skills Start with `/dev:meta-help` — shows the full menu and launches any skill directly. +Or just describe what you need in natural language — Claude picks the right skill automatically. ### Design @@ -39,6 +40,10 @@ Start with `/dev:meta-help` — shows the full menu and launches any skill direc | `/dev:design-data` | Schema, normalization, indexes, CQRS / Event Sourcing | | `/dev:design-migration` | Zero-downtime strategy: Expand-Contract, Strangler Fig, Saga | | `/dev:design-ux` | UX/UI design: interaction model, trust, AI features, anti-patterns | +| `/dev:design-llm` | LLM system: RAG, fine-tune vs. prompt, agents, evals, guardrails | +| `/dev:design-observability` | SLO/SLI, Golden Signals, tracing, alerting, incident response | +| `/dev:design-cicd` | CI/CD pipeline, deployment strategies (Blue-Green, Canary), DORA | +| `/dev:design-iac` | Infrastructure as Code: Terraform, GitOps, state management, drift detection | ### Review @@ -48,6 +53,7 @@ Start with `/dev:meta-help` — shows the full menu and launches any skill direc | `/dev:review-arch` | Coupling, anti-patterns, quality attributes, ADR recommendations | | `/dev:review-secure` | Crypto, injection, memory safety, GDPR / ISO 27001 / EU AI Act | | `/dev:review-ux` | UX audit based on HAX, PAIR, CHI 2024 and Nielsen Norman | +| `/dev:review-llm` | LLM audit: architecture, evals, prompt injection, OWASP LLM Top 10 | ### Tools @@ -56,24 +62,14 @@ Start with `/dev:meta-help` — shows the full menu and launches any skill direc | `/dev:tool-debug [error]` | Root-cause analysis with stack-aware fix suggestions | | `/dev:tool-test [focus]` | Write missing tests or design test strategy per test pyramid | | `/dev:tool-style [task]` | CSS solution matching your existing system (Tailwind, SCSS, …) | - -### Design (UX) - -| Skill | What it does | -|---|---| -| `/dev:design-ux` | UX/UI design: interaction model, trust, AI features, anti-patterns | - -### Review (UX) - -| Skill | What it does | -|---|---| -| `/dev:review-ux` | UX audit based on HAX, PAIR, CHI 2024 and Nielsen Norman | +| `/dev:tool-a11y` | Accessibility audit: WCAG 2.2, screen reader testing, EU Accessibility Act | +| `/dev:tool-perf [symptom]` | Performance engineering: USE Method, flame graph, bottleneck analysis, Bentley Rules | ### Meta | Skill | What it does | |---|---| -| `/dev:meta-help` | Navigation menu — shows all 18 skills, launches chosen one | +| `/dev:meta-help` | Navigation menu — shows all 24 skills, launches chosen one | | `/dev:meta-install` | Insert `essential-rules.md` into project `CLAUDE.md` (detects install vs. update) | | `/dev:meta-drift` | Compare installed rules block against current rule files | | `/dev:meta-sync` | Repo-internal: check if `claude/*.md` still reflects `reference/*.md` | @@ -146,6 +142,7 @@ Put rules that apply to every project in `~/.claude/CLAUDE.md`: ```text /dev:review-app → full audit /dev:review-secure → security code review +/dev:tool-a11y → accessibility check (EU Accessibility Act) ``` **During development:** @@ -156,6 +153,13 @@ Put rules that apply to every project in `~/.claude/CLAUDE.md`: /dev:tool-style [task] → CSS fix in your system's style ``` +**LLM / AI features:** + +```text +/dev:design-llm → RAG vs. fine-tune decision, agent architecture +/dev:review-llm → audit existing LLM system (OWASP LLM Top 10) +``` + **Keep rules up to date:** ```text diff --git a/docs/gap-analysis.md b/docs/gap-analysis.md index eaa91f5..7d16b55 100644 --- a/docs/gap-analysis.md +++ b/docs/gap-analysis.md @@ -28,9 +28,9 @@ Stand: 2026-06-08 | Zuletzt aktualisiert: 2026-06-08 | **Observability / SRE** | `design-observability` | Mittel | ✅ Erledigt | CMU 18-749; MIT 6.5840 | Google SRE Book (free); Site Reliability Workbook (free); "Observability Engineering" (Majors/Fong-Jones) | | **CI/CD Pipeline Design** | `design-cicd` | Mittel | ✅ Erledigt | CMU 17-636; Jez Humble (Berkeley) | "Continuous Delivery" (Humble/Farley); "Accelerate" (Forsgren/Humble/Kim); DORA Report 2024 (free) | | **Accessibility** | `tool-a11y` | Mittel | ✅ Erledigt | CMU HCII 05-332/632; W3C WAI Digital Foundations (edX) | WCAG 2.2 (normativ, free); EU EN 301 549 | -| **Infrastructure as Code** | `design-iac` | Niedrig | 🔲 Offen | NTNU IIKG3005 (einziger dedizierter Kurs weltweit) | "Infrastructure as Code" (Kief Morris); "Terraform: Up & Running" (Brikman) | -| **Performance Engineering** | `tool-perf` | Niedrig | 🔲 Offen | MIT 6.172 (vollständig auf OCW); CMU 15-721; UT Austin CS395T | "Systems Performance" (Brendan Gregg) — USE Method + Flamegraphs | -| **design-migration vertiefen** | `design-migration` | Niedrig | 🔲 Offen | Bereits: Fowler + MIT 6.5840 | Kleppmann "Designing Data-Intensive Applications" | +| **Infrastructure as Code** | `design-iac` | Niedrig | ✅ Erledigt | NTNU IIKG3005 (einziger dedizierter Kurs weltweit) | "Infrastructure as Code" (Kief Morris); "Terraform: Up & Running" (Brikman) | +| **Performance Engineering** | `tool-perf` | Niedrig | ✅ Erledigt | MIT 6.172 (vollständig auf OCW); CMU 15-721; UT Austin CS395T | "Systems Performance" (Brendan Gregg) — USE Method + Flamegraphs | +| **design-migration vertiefen** | `design-migration` | Niedrig | ✅ Erledigt | Bereits: Fowler + MIT 6.5840 | Kleppmann "Designing Data-Intensive Applications" | ### Korrekturen gegenüber erster Einschätzung diff --git a/plugins/dev/.claude-plugin/plugin.json b/plugins/dev/.claude-plugin/plugin.json index 85e5a35..6764cc5 100644 --- a/plugins/dev/.claude-plugin/plugin.json +++ b/plugins/dev/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "dev", - "version": "1.2.0", - "description": "22 Skills für Design (inkl. LLM-Engineering/RAG/Agents, Observability/SRE, CI/CD, UX/Human-AI Interaction), Security-Review (ISEC/Stanford/MIT, OWASP LLM Top 10), App-Audit (OWASP ASVS 5.0, DORA), Architektur-Review, Debug, Test, Styling, Accessibility (WCAG 2.2) und Skill-Erstellung.", + "version": "1.3.0", + "description": "24 Skills für Design (inkl. LLM-Engineering/RAG/Agents, Observability/SRE, CI/CD, IaC/GitOps, UX/Human-AI Interaction), Security-Review (ISEC/Stanford/MIT, OWASP LLM Top 10), App-Audit (OWASP ASVS 5.0, DORA), Architektur-Review, Debug, Test, Styling, Accessibility (WCAG 2.2), Performance Engineering (MIT 6.172, USE Method) und Skill-Erstellung.", "author": { "name": "Gerald" } } diff --git a/plugins/dev/commands/design-iac.md b/plugins/dev/commands/design-iac.md new file mode 100644 index 0000000..047407f --- /dev/null +++ b/plugins/dev/commands/design-iac.md @@ -0,0 +1,9 @@ +--- +description: Infrastructure as Code Design auf Basis von Kief Morris (O'Reilly 2021) und NTNU IIKG3005 — IaC-Prinzipien, Modul-Design, State Management, Drift Detection, GitOps. +argument-hint: "[optional: Kontext, z.B. 'Terraform fuer AWS EKS Cluster' oder 'bestehende manuelle Infra unter IaC bringen']" +--- + +Designe eine Infrastructure-as-Code-Architektur. +Folge exakt der Workflow-Definition in `${CLAUDE_PLUGIN_ROOT}/skills/design-iac/SKILL.md`. + +Kontext: $ARGUMENTS diff --git a/plugins/dev/commands/tool-perf.md b/plugins/dev/commands/tool-perf.md new file mode 100644 index 0000000..e4ff4d8 --- /dev/null +++ b/plugins/dev/commands/tool-perf.md @@ -0,0 +1,9 @@ +--- +description: Performance Engineering Workflow nach MIT 6.172 (Bentley Rules) und Brendan Gregg USE Method — systematische Bottleneck-Analyse mit Flamegraphs, Profiling und verifizierten Before/After-Benchmarks. +argument-hint: "[optional: Kontext, z.B. 'Python API p99 > 800ms' oder 'Node.js Memory-Leak in Produktion' oder 'DB-Queries zu langsam']" +--- + +Analysiere das Performance-Problem mit dem strukturierten Performance-Engineering-Workflow. +Folge exakt der Workflow-Definition in `${CLAUDE_PLUGIN_ROOT}/skills/tool-perf/SKILL.md`. + +Kontext: $ARGUMENTS diff --git a/plugins/dev/skills/design-iac/SKILL.md b/plugins/dev/skills/design-iac/SKILL.md new file mode 100644 index 0000000..d5d345a --- /dev/null +++ b/plugins/dev/skills/design-iac/SKILL.md @@ -0,0 +1,229 @@ +--- +name: design-iac +description: > + Infrastructure as Code Design grounded in "Infrastructure as Code" (Kief Morris, + O'Reilly 2021) und NTNU IIKG3005 (einziger dedizierter akademischer IaC-Kurs weltweit). + Deckt IaC-Prinzipien (Immutable Infrastructure, Idempotency, Single Source of Truth), + Modul-Design, State Management, Drift Detection, GitOps-Workflow und Testing ab. + Use this skill whenever the user wants to design or improve Infrastructure as Code, + set up Terraform/Pulumi/CDK, or establish a GitOps workflow. + Trigger: "Infrastructure as Code einrichten", "Terraform aufbauen", "IaC Design", + "Modul-Struktur fuer Terraform", "State Management", "GitOps einrichten", + "Drift Detection", "IaC testen mit Terratest", "Cloud-Infrastruktur versionieren", + "Immutable Infrastructure", "wir haben Config Drift", "IaC Best Practices". + Deckt ab: IaC-Prinzipien, Modul-Design, State Management (Remote Backend, Locking), + Drift Detection, GitOps-Workflow, Testing (Terratest, Static Analysis). +--- + +# Infrastructure as Code Design + +Entwirft eine IaC-Architektur von Modul-Design bis GitOps-Workflow — grounded in +Kief Morris "Infrastructure as Code" und NTNU IIKG3005. + +--- + +## Core Philosophy (Kief Morris) + +> "Treating infrastructure as code means applying software engineering practices — +> version control, testing, code review — to infrastructure definitions." +> — Kief Morris, Infrastructure as Code (2021) + +Immutable Infrastructure und Single Source of Truth eliminieren Config Drift. +GitOps macht jeden Infrastruktur-Zustand reproduzierbar, reviewbar und rollbackbar. + +--- + +## Schritt 0 — Kontext klären + +**Fragen:** +- Cloud-Provider: AWS / GCP / Azure / Multi-Cloud / On-Prem? +- IaC-Tool: Terraform / OpenTofu / Pulumi / CDK / Ansible? +- Team-Groesse und -Reife: IaC-Erfahrung vorhanden? +- Bestehendes Setup: manuell provisioniert / teilweise IaC / kein IaC? +- CI/CD: GitHub Actions / GitLab CI / Jenkins / Terraform Cloud? +- Compliance-Anforderungen: PCI-DSS, SOC2, ISO 27001? + +--- + +## Schritt 1 — IaC-Prinzipien verankern + +(→ `references/iac-patterns.md`) + +**1a — Immutable Infrastructure pruefen** + +Werden Server nach dem Provisionieren noch manuell geaendert? +→ Wenn ja: Snowflake Anti-Pattern — Plan fuer Immutability erstellen. + +**1b — Single Source of Truth definieren** + +- Wo lebt der IaC-Code? (Git-Repo-Struktur) +- Gibt es manuelle Aenderungen parallel? → stoppen +- Alles was Infra-Zustand definiert muss im Repo sein + +**1c — Anti-Patterns identifizieren** + +Checklist: Config Drift / Snowflake Server / Copy-Paste IaC / Monolithic Stack / lokaler State in Prod + +--- + +## Schritt 2 — Modul-Design + +**2a — Stack-Schichtung planen** + +```text +foundation/ # VPC, DNS, IAM Basis, Security Groups +platform/ # Kubernetes, Datenbanken, Queues, Caches +services/ # Applikations-Infra (pro Service oder Team) +``` + +Jede Schicht = eigener State, eigener Apply-Zyklus. + +**2b — Modul-Grenzen ziehen** + +Pro Modul: Single Responsibility (ein klar abgegrenzter Concern). +Inputs/Outputs explizit definieren — keine versteckten Abhaengigkeiten. + +**2c — Modul-Versionierung** + +Modules per Git-Tag referenzieren: +```text +source = "git::https://github.com/org/infra-modules//network?ref=v2.3.0" +``` +Kein `?ref=main` in Prod-Environments. + +--- + +## Schritt 3 — State Management + +(→ `references/state-management.md`) + +**3a — Remote Backend waehlen** + +AWS → S3 + DynamoDB. GCP → GCS. Azure → Blob Storage. Multi-Cloud → Terraform Cloud. +Niemals lokaler State in Staging oder Prod. + +**3b — State-Sicherheit** + +- Encryption at rest + in transit aktivieren +- Least Privilege: nur CI/CD Pipeline + Admins +- State-Locking aktivieren (verhindert parallele Applies) +- Versionierung im Backend (S3 Versioning, GCS Versioning) + +**3c — Workspace-Strategie** + +Empfehlung: Separate State-Pfade pro Environment: +```text +s3://infra-state/envs/dev/terraform.tfstate +s3://infra-state/envs/staging/terraform.tfstate +s3://infra-state/envs/prod/terraform.tfstate +``` + +--- + +## Schritt 4 — Drift Detection und Remediation + +**4a — Drift erkennen** + +`terraform plan` als Scheduled Job (taeglich) — Alert wenn Output != "No changes". +Tools: Driftctl, Terraform Cloud Drift Detection, AWS Config. + +**4b — Drift klassifizieren** (→ `references/iac-patterns.md`) + +Gewollter Drift (externe Aenderung beabsichtigt) vs. ungewollter Drift (manueller Eingriff). + +**4c — Prozess-Fix** + +Root Cause: Wer hat manuell geaendert und warum? +Losung: Break-Glass-Prozess fuer Notfaelle (erlaubt, aber dokumentiert und nachverfolgt). + +--- + +## Schritt 5 — GitOps-Workflow + +**5a — Branch-Strategie** + +```text +feature/* → main: PR mit Plan-Output als Comment +main → staging: automatisch (nach PR-Merge) +staging → prod: manuelles Approval-Gate +``` + +**5b — Plan-Output im PR** + +CI kommentiert `terraform plan` Diff in jeden PR. +Reviewer sehen exakt was sich aendert — kein Blind-Merge. + +**5c — Apply-Strategie** + +- Staging: automatisch nach Merge +- Prod: manuelles Approval (min. 1 Reviewer) + automatischer Apply +- Rollback: vorherigen Commit re-applyen (nicht `terraform destroy`) + +--- + +## Schritt 6 — Testing + +(→ `references/iac-patterns.md` fuer Drift-Tests) + +**6a — Static Analysis** + +- `terraform validate` — Syntaxfehler +- `terraform fmt --check` — Formatierung +- `tflint` — Best-Practice-Violations +- `checkov` / `tfsec` — Security Misconfigurations + +**6b — Unit-Tests (Terratest)** + +```go +// Beispiel: Terratest prueft ob S3-Bucket erstellt wurde +terraform.InitAndApply(t, terraformOptions) +bucketID := terraform.Output(t, terraformOptions, "bucket_id") +aws.AssertS3BucketExists(t, "us-east-1", bucketID) +``` + +**6c — Contract Tests** + +Outputs eines Moduls gegen erwartete Struktur pruefen. +Stellt sicher dass Downstream-Module nicht brechen. + +--- + +## Output — `iac-design.md` + +```markdown +# IaC Design — [Projekt-Name] + +## Stack-Schichtung +| Stack | Zweck | State-Pfad | +|---|---|---| +| foundation | VPC, IAM | s3://state/foundation/ | +| platform | K8s, DB | s3://state/platform/ | +| services | App-Infra | s3://state/services/ | + +## Module +| Modul | Inputs | Outputs | Version | +|---|---|---|---| +| network | cidr, region | vpc_id, subnet_ids | v1.2.0 | + +## State Backend +- Provider: [S3+DynamoDB / GCS / TF Cloud] +- Encryption: ja +- Locking: ja +- Workspace-Strategie: [separate Pfade / Workspaces] + +## GitOps-Workflow +- Plan im PR: ja +- Apply Staging: automatisch nach Merge +- Apply Prod: manuelles Approval + +## Testing +- Static: tflint + checkov +- Unit: Terratest +- Drift Detection: [taeglich / Terraform Cloud] +``` + +## Reference Files + +- `references/curriculum-mapping.md` — Concept → Kief Morris Kapitel + NTNU IIKG3005 +- `references/iac-patterns.md` — Core Patterns vs. Anti-Patterns, Modul-Design, Drift-Klassifikation +- `references/state-management.md` — Remote Backends, Security, Workspace-Strategie, Import-Workflow diff --git a/plugins/dev/skills/design-iac/references/curriculum-mapping.md b/plugins/dev/skills/design-iac/references/curriculum-mapping.md new file mode 100644 index 0000000..e413125 --- /dev/null +++ b/plugins/dev/skills/design-iac/references/curriculum-mapping.md @@ -0,0 +1,20 @@ +# Curriculum Mapping — design-iac + +| Concept | Reference | +|---|---| +| IaC Kernprinzipien | Kief Morris "Infrastructure as Code", Kap. 1: What Is Infrastructure as Code? | +| Immutable Infrastructure | Kief Morris, Kap. 5: Building Infrastructure Stacks | +| Single Source of Truth | Kief Morris, Kap. 2: Principles of Infrastructure as Code | +| Idempotency | Kief Morris, Kap. 2 | +| Modul-Design | Kief Morris, Kap. 16: Designing Modules | +| Stack-Komposition | Kief Morris, Kap. 15: Evolving Infrastructure Design | +| State Management | Kief Morris, Kap. 7: Managing State | +| Drift Detection | Kief Morris, Kap. 13: Discovering and Correcting Drift | +| Testing IaC | Kief Morris, Kap. 22: Testing Infrastructure Code | +| GitOps als operatives Pattern | Kief Morris, Kap. 19: GitOps | +| Terraform Modul-Design | Brikman "Terraform: Up & Running", Kap. 4: How to Create Reusable Infrastructure | +| Terraform State Management | Brikman, Kap. 3: How to Manage Terraform State | +| Terratest | Brikman, Kap. 9: How to Test Terraform Code | +| IaC-Konzepte und Cloud-Plattformen | NTNU IIKG3005: Infrastructure as Code — Learning Outcomes | +| DevOps-Philosophie | NTNU IIKG3005: DevOps-Kultur und -Prinzipien | +| Versionskontrolle fuer Infrastruktur | NTNU IIKG3005: Infrastruktur per versioniertem Repository | diff --git a/plugins/dev/skills/design-iac/references/iac-patterns.md b/plugins/dev/skills/design-iac/references/iac-patterns.md new file mode 100644 index 0000000..0c5c6a5 --- /dev/null +++ b/plugins/dev/skills/design-iac/references/iac-patterns.md @@ -0,0 +1,52 @@ +# IaC Patterns und Anti-Patterns + +Quelle: Kief Morris "Infrastructure as Code", O'Reilly 2021. + +## Core Patterns + +| Pattern | Beschreibung | Anti-Pattern | +|---|---|---| +| **Immutable Infrastructure** | Infra-Ressourcen nie aendern — immer neu provisionieren | Mutable: Server mit SSH patchen (Config Drift) | +| **Dynamic Infrastructure** | Ressourcen per API erzeugen/loeschen | Static: manuelles Setup, Snowflake Server | +| **Single Source of Truth** | Ein Repo definiert Soll-Zustand — kein manuelles Eingreifen | IaC + parallele manuelle Aenderungen | +| **Idempotent Apply** | Mehrfaches Apply → immer gleicher Zustand | Scripts mit Seiteneffekten bei Re-Run | +| **Small Focused Stacks** | Ein Stack pro Concern (Network / Compute / App) | Monolithic Stack (alles in einem) | +| **Composable Modules** | Module = wiederverwendbare Bausteine mit klaren Inputs/Outputs | Copy-Paste IaC | +| **GitOps** | Git = Single Source of Truth, Aenderungen nur per PR | Direkte CLI-Aenderungen in Prod | + +**Snowflake Anti-Pattern:** Jeder Server wurde durch manuelle Aenderungen einzigartig — nicht reproduzierbar, nicht skalierbar, nicht loeschbar ohne Angst. + +--- + +## Modul-Design Prinzipien + +| Prinzip | Beschreibung | +|---|---| +| Single Responsibility | Ein Modul = ein klar abgegrenzter Concern | +| Stabile Interfaces | Input-Variablen und Outputs aendern sich selten | +| Keine versteckten Abhaengigkeiten | Alles was ein Modul braucht, kommt als Input | +| Versionierung | Module per Git-Tag versionieren (kein `?ref=main` in Prod) | +| Minimale Outputs | Nur was Downstream-Module wirklich brauchen | + +--- + +## Stack-Schichtung (empfohlen) + +```text +foundation/ # VPC, DNS, Security Groups, IAM Basis +platform/ # Kubernetes, Datenbanken, Message Queues +services/ # Applikations-Infrastruktur (pro Service/Team) +``` + +Jede Schicht hat eigenen State. Services-Schicht referenziert Platform-Outputs via Remote State Read. + +--- + +## Drift-Klassifikation + +| Typ | Ursache | Massnahme | +|---|---|---| +| Config Drift | Manuelle Aenderung nach Apply | `terraform plan` zeigt Diff, dann Apply | +| Version Drift | Modul-Version in einer Env zu alt | Update + Apply in allen Envs | +| Secret Drift | Secrets direkt geaendert, nicht per IaC | Secrets in Secrets-Manager, Referenz in IaC | +| Resource Drift | Ressource manuell geloescht | Import oder neu provisionieren | diff --git a/plugins/dev/skills/design-iac/references/state-management.md b/plugins/dev/skills/design-iac/references/state-management.md new file mode 100644 index 0000000..bda3d25 --- /dev/null +++ b/plugins/dev/skills/design-iac/references/state-management.md @@ -0,0 +1,60 @@ +# State Management — IaC + +## Remote State Backends + +| Backend | Provider | Locking | Empfehlung | +|---|---|---|---| +| S3 + DynamoDB | AWS | DynamoDB Table | Standard fuer AWS | +| GCS + Firestore | GCP | Native GCS | Standard fuer GCP | +| Azure Blob + Storage Lock | Azure | Lease-basiert | Standard fuer Azure | +| Terraform Cloud / HCP Terraform | HashiCorp | Native | Cloud-agnostisch, Collaboration-Features | +| GitLab Managed Terraform | GitLab | Native | Bei GitLab CI/CD | + +**Niemals lokaler State in Prod.** Lokaler State: nur fuer lokale Entwicklung und Tests. + +--- + +## State-Security + +| Massnahme | Warum | +|---|---| +| Encryption at rest aktivieren | State kann Secrets enthalten (Passwoerter, Keys) | +| Encryption in transit (TLS) | State wird ueber Netzwerk uebertragen | +| Least Privilege Zugriff | Nur CI/CD Pipeline und Admins duerfen State lesen/schreiben | +| State-Locking | Verhindert parallele Applies (Race Conditions) | +| State-Backup | Versionierung im Backend aktivieren (S3 Versioning, GCS) | + +--- + +## Workspace-Strategie + +| Ansatz | Wann | Einschraenkung | +|---|---|---| +| **Workspace per Environment** | Gleicher Code, verschiedene Variablenwerte (dev/staging/prod) | Schlechte Isolation: ein Plan betrifft alle Envs | +| **Separate State-Pfade** | Verschiedene `backend` Konfigurationen pro Env | Mehr Komplexitaet, aber saubere Isolation | +| **Separate Repos** | Enterprise, strikte Isolation, verschiedene Teams pro Env | Hoechste Isolation, aber viel Overhead | + +Empfehlung fuer die meisten Teams: **Separate State-Pfade** (z.B. `s3://bucket/envs/prod/terraform.tfstate`). + +--- + +## State-Drift Workflow + +```text +1. terraform plan → zeigt Drift zwischen State und tatsaechlicher Infra +2. Entscheiden: + ├─ Drift gewollt? → terraform apply (State an Realitaet anpassen) + └─ Drift ungewollt? → manuelle Korrektur zuerst, dann apply +3. Root Cause: wer hat manuell geaendert? → Prozess verbessern +4. Drift-Detection automatisieren: plan im Schedule-Job, Alert bei Diff != 0 +``` + +--- + +## Import vs. Neu Provisionieren + +| Situation | Empfehlung | +|---|---| +| Bestehende Ressource soll unter IaC | `terraform import` — Ressource in State aufnehmen ohne Aenderung | +| Ressource nach manueller Loeschung neu | Neu provisionieren via `apply` | +| Migrationsprojekt: alles unter IaC bringen | Import-Strategie: eine Ressource nach der anderen, immer verifizieren | diff --git a/plugins/dev/skills/design-migration/SKILL.md b/plugins/dev/skills/design-migration/SKILL.md index dcfd0f7..c6bfad9 100644 --- a/plugins/dev/skills/design-migration/SKILL.md +++ b/plugins/dev/skills/design-migration/SKILL.md @@ -10,7 +10,12 @@ description: > the database without downtime", "blue-green deployment", "strangler fig", "how do I break this apart safely", "migration strategy". Always use this skill for migration planning — these decisions have high failure risk and must be - approached systematically. + approached systematically. Also grounded in Kleppmann "Designing Data-Intensive + Applications" Kap. 4 (Schema Evolution, Forward/Backward Compatibility) and + Kap. 11 (Dual-Write Problem, Change Data Capture, Event Log). + Additional triggers: "Schema Migration ohne Downtime", "CDC einrichten", + "Dual-Write Problem", "Debezium", "Schema Registry", "Expand-Contract Pattern", + "Forward Compatibility", "Schema versioning". --- # Migration Plan Skill @@ -141,4 +146,6 @@ Fowler patterns, MIT 6.5840, Richardson Saga: `references/curriculum-mapping.md` - `references/migration-patterns.md` — Strangler Fig, seam finding, zero-downtime DB migration, CAP theorem, consistency models, 2PC, Saga pattern +- `references/schema-evolution.md` — Forward/Backward Compatibility, Dual-Write, CDC (Debezium), + Avro Schema Registry, Expand-Contract Pattern (Kleppmann DDIA Kap. 4 + 11) - `references/curriculum-mapping.md` — Concept → course/blog link mapping diff --git a/plugins/dev/skills/design-migration/references/curriculum-mapping.md b/plugins/dev/skills/design-migration/references/curriculum-mapping.md index 14670c9..b735764 100644 --- a/plugins/dev/skills/design-migration/references/curriculum-mapping.md +++ b/plugins/dev/skills/design-migration/references/curriculum-mapping.md @@ -11,3 +11,8 @@ | CAP theorem | [MIT 6.5840 — Consistency](https://pdos.csail.mit.edu/6.824/) | | Saga pattern | [Richardson: Saga Pattern](https://microservices.io/patterns/data/saga.html) | | Event sourcing migration | [Fowler: EventSourcing](https://martinfowler.com/eaaDev/EventSourcing.html) | +| Schema Evolution (Forward/Backward Compatibility) | Kleppmann "Designing Data-Intensive Applications", Kap. 4: Encoding and Evolution | +| Dual-Write Pattern und Risiken | Kleppmann DDIA, Kap. 11: Stream Processing — Dual-Write Problem | +| Change Data Capture (CDC) | Kleppmann DDIA, Kap. 11: The Log as a Data Structure | +| Avro / Protobuf Schema Registry | Kleppmann DDIA, Kap. 4: Avro Schema Evolution | +| Event-Driven Migration (Outbox Pattern) | Kleppmann DDIA, Kap. 11 + Microservices.io: Transactional Outbox | diff --git a/plugins/dev/skills/design-migration/references/schema-evolution.md b/plugins/dev/skills/design-migration/references/schema-evolution.md new file mode 100644 index 0000000..d1409cb --- /dev/null +++ b/plugins/dev/skills/design-migration/references/schema-evolution.md @@ -0,0 +1,121 @@ +# Schema Evolution — Referenz + +Quelle: Kleppmann "Designing Data-Intensive Applications" (O'Reilly 2017), Kap. 4 + Kap. 11. + +## Forward vs. Backward Compatibility (Kleppmann Kap. 4) + +| Begriff | Definition | Konkret | +|---|---|---| +| **Backward Compatibility** | Neuer Code kann alte Daten lesen | Code v2 liest Daten die mit v1 geschrieben wurden | +| **Forward Compatibility** | Alter Code kann neue Daten lesen | Code v1 liest Daten die mit v2 geschrieben wurden | + +**Ziel bei Rolling Deployments:** Beides — neue und alte Code-Version laufen gleichzeitig. + +### Regeln fuer Schema-Aenderungen + +| Aenderung | Backward compat. | Forward compat. | Sicher? | +|---|---|---|---| +| Neues optionales Feld hinzufuegen | ✅ (Defaultwert) | ✅ (ignoriert) | ✅ Sicher | +| Pflichtfeld hinzufuegen | ❌ Alter Code hat kein Feld | ✅ | ❌ Gefaehrlich | +| Feld entfernen | ✅ | ❌ Alter Code erwartet Feld | ❌ Expand-Contract noetig | +| Typ aendern (int → string) | ❌ | ❌ | ❌ Breaking Change | +| Feld umbenennen | ❌ | ❌ | ❌ Breaking Change | +| Enum-Wert hinzufuegen | ✅ | ❌ Alter Code kennt Wert nicht | ⚠️ Pruefe alle Consumer | + +**Expand-Contract Pattern fuer Feld-Entfernung:** + +```text +Phase 1 — Expand: Neues Feld hinzufuegen, beide Felder parallel schreiben +Phase 2 — Migrate: Alte Daten in neues Feld migrieren, altes Feld nur noch lesen +Phase 3 — Contract: Altes Feld entfernen (kein Code liest es mehr) +``` + +--- + +## Dual-Write Problem (Kleppmann Kap. 11) + +Wenn zwei Stores gleichzeitig geschrieben werden (z.B. DB + Search Index): + +**Problem:** Kein atomares Commit ueber beide Systeme moeglich. + +| Szenario | Risiko | +|---|---| +| Write A erfolgreich, Write B fehlgeschlagen | Stores divergieren | +| Write B zuerst sichtbar (Reihenfolge) | Inkonsistenter Zustand | +| Fehler nach Write A, vor Write B | Partieller Zustand | + +**Loesungen nach Kleppmann:** + +1. **Change Data Capture (CDC):** Nur in DB schreiben, CDC liest Transaction Log und + aktualisiert Secondary Stores. Kausal korrekte Reihenfolge durch Log-Basis. + +2. **Outbox Pattern:** Schreibe Event + Daten in einer DB-Transaktion in Outbox-Tabelle. + Separater Processor liest Outbox und publiziert Events. + +3. **Event Log als Source of Truth:** Alle Schreiboperationen als Events in ordered Log + (Kafka). Alle Stores sind Read-Models die den Log konsumieren. + +--- + +## Change Data Capture (CDC) (Kleppmann Kap. 11) + +CDC liest den Transaction Log der Datenbank (binlog bei MySQL, WAL bei PostgreSQL). + +```text +Anwendung → DB (Write) → Transaction Log → CDC Connector → Event Stream → Consumer +``` + +**Vorteile gegenueber Dual-Write:** +- Kausal korrekte Reihenfolge (Log-Reihenfolge) +- Kein Auslassen von Aenderungen +- Low Latency (nahezu real-time) +- Kein Applikationscode-Aenderung noetig + +**CDC Tools:** +- **Debezium** (Open Source, Kafka Connect) — PostgreSQL, MySQL, MongoDB, SQL Server +- **AWS DMS** — managed CDC fuer AWS-Ziele +- **Google Datastream** — managed CDC fuer GCP + +**Migration via CDC (Zero-Downtime DB-Migration):** + +```text +1. CDC auf Quell-DB aktivieren (liest WAL/binlog ab Checkpoint) +2. Initial Snapshot in Ziel-DB laden +3. CDC streamt alle Delta-Aenderungen in Ziel-DB (Aufholen) +4. Lesen aus Ziel-DB aktivieren (Shadow Read) +5. Divergenz-Pruefung (Quelle vs. Ziel) +6. Schreiben auf Ziel umschalten (Dual-Write-Phase entfaellt) +7. Quelle abschalten nach Confidence-Periode +``` + +--- + +## Avro Schema Registry (Kleppmann Kap. 4) + +Fuer Event-Driven Architekturen: Schema-Version mit Event mitschicken. + +**Avro Schema Evolution Regeln:** +- Feld hinzufuegen: Default-Wert angeben → backward + forward compat +- Feld entfernen: Default-Wert in altem Schema angeben → backward + forward compat +- Kein Default: Breaking Change + +**Confluent Schema Registry Pattern:** +- Schema-ID im Message Header (`magic byte + schema ID`) +- Reader liest Schema-ID, holt Schema aus Registry, konvertiert +- Alte und neue Schemas koennen parallel existieren + +--- + +## Entscheidungsbaum: Welche Migration-Technik? + +```text +Muss altes System weiterlaufen waehrend neu deployed wird? +├─ Nein → Maintenance Window, Big Bang (nur bei kleinen/unkritischen Systemen) +└─ Ja → + Handelt es sich um Schema-Aenderung in DB? + ├─ Ja → Expand-Contract Pattern (Phasen: expand → migrate → contract) + └─ Nein (neues System / neuer Store) → + Ist Daten-Konsistenz zwischen Stores kritisch? + ├─ Ja → CDC (Debezium) + Divergenz-Pruefung + └─ Nein / OK mit eventual consistency → Dual-Write + Timeout-basierte Migration +``` diff --git a/plugins/dev/skills/meta-help/SKILL.md b/plugins/dev/skills/meta-help/SKILL.md index a5a593e..6dfd093 100644 --- a/plugins/dev/skills/meta-help/SKILL.md +++ b/plugins/dev/skills/meta-help/SKILL.md @@ -26,25 +26,27 @@ Welcher Skill soll starten? 7 design-llm LLM-System: RAG, Fine-tune, Agent, Eval-Strategie, Guardrails 8 design-observability Observability: SLO/SLI, Golden Signals, Tracing, Alerting, Incident Response 9 design-cicd CI/CD Pipeline: Deployment-Strategien, DORA-Metriken, Trunk-Based Dev + 10 design-iac Infrastructure as Code: Terraform, GitOps, State Management, Drift Detection 🔍 REVIEW - 10 review-app Vollaudit: Architektur, Security, Tests, CI/CD, Observability - 11 review-arch Architektur: Coupling, Anti-Patterns, Quality Attributes, ADR - 12 review-secure Security: Crypto, Injection, Memory Safety, GDPR/ISO/EU AI Act - 13 review-ux UX-Audit: AI Anti-Patterns, Dark Patterns, Trust Design - 14 review-llm LLM-Audit: Architektur, Evals, Prompt Injection, OWASP LLM Top 10 + 11 review-app Vollaudit: Architektur, Security, Tests, CI/CD, Observability + 12 review-arch Architektur: Coupling, Anti-Patterns, Quality Attributes, ADR + 13 review-secure Security: Crypto, Injection, Memory Safety, GDPR/ISO/EU AI Act + 14 review-ux UX-Audit: AI Anti-Patterns, Dark Patterns, Trust Design + 15 review-llm LLM-Audit: Architektur, Evals, Prompt Injection, OWASP LLM Top 10 🛠️ TOOLS - 15 tool-debug Stack-aware Root-Cause-Analyse mit Fix-Vorschlägen - 16 tool-test Tests schreiben, verbessern oder Strategie planen - 17 tool-style CSS / Design System + Visual Basics (Farbe, Typo, Spacing, Loading) - 18 tool-a11y Accessibility-Audit: WCAG 2.2, Screen Reader, EU Accessibility Act + 16 tool-debug Stack-aware Root-Cause-Analyse mit Fix-Vorschlägen + 17 tool-test Tests schreiben, verbessern oder Strategie planen + 18 tool-style CSS / Design System + Visual Basics (Farbe, Typo, Spacing, Loading) + 19 tool-a11y Accessibility-Audit: WCAG 2.2, Screen Reader, EU Accessibility Act + 20 tool-perf Performance Engineering: USE Method, Flamegraph, Bottleneck, Bentley Rules 📁 META - 19 meta-install Best-Practice-Regeln in Projekt-CLAUDE.md einbauen - 20 meta-drift Projekt-CLAUDE.md vs. aktuelle Rule-Files vergleichen - 21 meta-sync reference/*.md vs. claude/*.md synchron halten - 22 meta-create-skill Neuen Skill bauen: Recherche, Struktur, alle Dateien + 21 meta-install Best-Practice-Regeln in Projekt-CLAUDE.md einbauen + 22 meta-drift Projekt-CLAUDE.md vs. aktuelle Rule-Files vergleichen + 23 meta-sync reference/*.md vs. claude/*.md synchron halten + 24 meta-create-skill Neuen Skill bauen: Recherche, Struktur, alle Dateien → Zahl eingeben, oder direkt beschreiben was du brauchst. ``` @@ -60,4 +62,4 @@ Lade und folge exakt: `${CLAUDE_PLUGIN_ROOT}/skills//SKILL.md` ## Regeln - Menü sofort zeigen, kein Intro - Nach der Wahl direkt starten, nicht nochmals erklären oder nachfragen -- Nie alle 22 Skills gleichzeitig laden — immer nur den gewählten +- Nie alle 24 Skills gleichzeitig laden — immer nur den gewählten diff --git a/plugins/dev/skills/tool-perf/SKILL.md b/plugins/dev/skills/tool-perf/SKILL.md new file mode 100644 index 0000000..a8a0e20 --- /dev/null +++ b/plugins/dev/skills/tool-perf/SKILL.md @@ -0,0 +1,206 @@ +--- +name: tool-perf +description: > + Performance Engineering Workflow grounded in MIT 6.172 (Leiserson/Shun, + vollstaendig auf MIT OCW) und "Systems Performance" (Brendan Gregg, + Addison-Wesley 2020). Deckt USE Method (Utilization/Saturation/Errors), + Flamegraph-Analyse, Bottleneck-Identifikation, Bentley Rules und + messbares Before/After-Benchmarking ab. + Use this skill whenever the user has a performance problem, slow code, + high latency, CPU/memory spikes, or wants to optimize a system. + Trigger: "Performance-Problem", "langsame API", "hohe Latenz", "CPU-Spike", + "Memory-Leak", "Flamegraph analysieren", "Bottleneck finden", "Code optimieren", + "Profiling", "p99 zu hoch", "Throughput erhoehen", "USE Method", + "warum ist das so langsam", "Load Test zeigt Probleme". + Deckt ab: USE Method, Flamegraph-Analyse, CPU/Memory/I-O/Network Profiling, + Bentley Rules, Measurement und Benchmarking. +--- + +# Performance Engineering (tool-perf) + +Strukturierter Performance-Analyse-Workflow — von der Symptom-Beschreibung bis zum +verifizierten Fix. Grounded in MIT 6.172 und Brendan Gregg "Systems Performance". + +--- + +## Core Philosophy (MIT 6.172 + Brendan Gregg) + +> "Measure, don't guess." — Grundprinzip Performance Engineering +> +> "Never tune for performance without first having a performance target." +> — Brendan Gregg, Systems Performance + +Immer messen bevor optimiert wird. Ohne Profiling-Daten ist Optimierung Raten. +USE Method gibt den systematischen Rahmen — Flamegraphs zeigen WO die Zeit verbracht wird. + +--- + +## Schritt 0 — Scope und Symptom klären + +**Fragen:** +- Was ist das konkrete Symptom? (Hohe Latenz / hoher CPU / Memory-Wachstum / niedrige Throughput) +- Stack: Web-Service / CLI / Datenbank / Low-Level C/C++ / JVM / Python? +- Gibt es Metriken? (Prometheus, Datadog, APM-Tool, ab wann schlechter?) +- Gibt es ein Performance-Ziel? (p99 < 200ms, Throughput > 1000 req/s) +- Produktions-Problem oder pre-release Optimierung? + +→ Ohne konkrete Zahlen und Ziel ist Performance-Arbeit nicht abschliessbar. + +--- + +## Schritt 1 — USE Method: Bottleneck lokalisieren + +(→ `references/use-method.md` fuer vollstaendige Ressourcen-Checkliste) + +**Fuer jede relevante Ressource messen:** +- Utilization: Wie viel % der Kapazitaet wird genutzt? +- Saturation: Bilden sich Warteschlangen? +- Errors: Gibt es Fehler-Events? + +**Schnell-Diagnose nach Symptom:** + +| Symptom | Verdacht | Naechster Schritt | +|---|---|---| +| Hohe Latenz, niedrige CPU | I/O-bound | Disk-Queue, Network-Drops, DB-Latenz | +| Hohe CPU, skaliert mit Traffic | CPU-bound | CPU-Profiling, Flamegraph | +| Requests in Queue | Concurrency-Limit | Thread/Worker Pool Saturation | +| Memory steigt ueber Zeit | Memory-Leak | Heap Dump, Allocation Profiling | +| Sporadische Spikes | Lock Contention oder GC | Mutex Saturation, GC Logs | + +→ Den wahrscheinlichsten Bottleneck identifizieren, dann tiefer analysieren. + +--- + +## Schritt 2 — Profiling und Flamegraph + +**2a — Profiling-Tool waehlen (nach Stack)** + +| Stack | CPU Profiler | Memory Profiler | +|---|---|---| +| Linux (C/C++/Go) | `perf record + perf report` | Valgrind, heaptrack | +| JVM (Java/Kotlin/Scala) | async-profiler, JFR | JVM Heap Dump + Eclipse MAT | +| Python | `py-spy`, `cProfile` | memory-profiler, Tracemalloc | +| Node.js | `--prof`, Clinic.js | `--inspect` + Chrome DevTools | +| Go | `pprof` | `pprof` Heap Profile | +| Browser (JS) | Chrome DevTools Performance | Chrome DevTools Memory | + +**2b — Flamegraph erstellen und lesen** + +```text +perf record -F 99 -g -- +perf script | stackcollapse-perf.pl | flamegraph.pl > flamegraph.svg +``` + +Flamegraph lesen: +- X-Achse = Anteil der gesamten Sampling-Zeit (nicht Zeit-Verlauf) +- Y-Achse = Call Stack (unten = Entry Point, oben = wo Zeit verbracht wird) +- Breite eines Blocks = % Zeit in dieser Funktion + Callees +- Plateau (breiter flacher Block oben) = Hotspot — dort optimieren + +**2c — Top-Hotspot identifizieren** + +Den breitesten Block ganz oben im Flamegraph lokalisieren. +Das ist die Funktion die am meisten CPU-Zeit verbraucht. + +--- + +## Schritt 3 — Bottleneck-Analyse + +**CPU-bound:** +- Algorithmus-Komplexitaet (O(n²) wo O(n log n) moeglich?) +- Bentley Rules anwenden (→ `references/bentley-rules.md`) +- Cache-Effizienz: Memory-Access-Pattern pruefen (Row-major vs Column-major) +- Parallelisierung: Single-threaded Bottleneck → Multi-threading + +**Memory-bound:** +- Heap-Profiling: welche Allokationen dominieren? +- GC-Druck reduzieren: Object-Pooling, weniger kurzlebige Objekte +- Memory-Leak: Welche Objekte wachsen ueber Zeit? + +**I/O-bound:** +- DB-Queries: EXPLAIN ANALYZE, fehlende Indexe, N+1-Queries +- Disk: Async I/O, Batching, Sequential statt Random Access +- Network: Connection Pooling, Keep-Alive, Compression + +**Lock Contention:** +- Kritische Sektion minimieren +- Lock-freie Datenstrukturen wo moeglich +- Read-Write Lock statt exklusivem Mutex + +--- + +## Schritt 4 — Optimierung mit Bentley Rules + +(→ `references/bentley-rules.md` fuer vollstaendige Regeln) + +**Vor der Optimierung:** Baseline-Benchmark aufnehmen (exakte Zahlen). + +Prioritaet nach Hebelwirkung: +1. **Algorithmus/Datenstruktur** — groesste Wirkung (O(n²) → O(n log n)) +2. **Caching** — teure Berechnungen einmalig +3. **Loop-Optimierungen** — Hoisting, Fusion, Early Exit +4. **Memory-Zugriffspattern** — Cache-Freundlichkeit + +**Niemals ohne Messung optimieren** (Premature Optimization). + +--- + +## Schritt 5 — Measurement und Verification + +**5a — Benchmark aufnehmen** + +Immer: vor der Optimierung messen, nach der Optimierung messen. +Gleiche Bedingungen, ausreichend Durchlaeufe (Warmup + Messphase trennen). + +**5b — Benchmark-Tools** + +| Typ | Tool | +|---|---| +| Microbenchmark | JMH (Java), criterion (Rust), benchmark (Go), pytest-benchmark | +| HTTP Load Test | k6, wrk, hey, Apache Bench | +| Profiler-basiert | Flamegraph before/after vergleichen | +| System-Level | `perf stat` (CPU cycles, cache misses, instructions) | + +**5c — Ergebnis dokumentieren** + +| Metrik | Vorher | Nachher | Verbesserung | +|---|---|---|---| +| p50 Latenz | X ms | Y ms | Z% | +| p99 Latenz | X ms | Y ms | Z% | +| Throughput (req/s) | X | Y | Z% | +| CPU (%) | X | Y | Z% | + +--- + +## Output — `perf-findings.md` + +```markdown +# Performance Findings — [Service/Component] + +## Symptom +[Konkrete Beschreibung: p99 Latenz 800ms, Ziel < 200ms] + +## USE Method Ergebnis +| Ressource | U | S | E | Befund | +|---|---|---|---|---| +| CPU | 85% | Load 4 (2 Cores) | 0 | CPU-bound | +| Memory | 60% | 0 | 0 | OK | + +## Root Cause +[Flamegraph zeigt: 73% Zeit in `parseJson()` — ineffizienter Parser] + +## Massnahme +[Wechsel zu schnellerem JSON-Parser, Ergebnis cachen] + +## Messergebnis +| Metrik | Vorher | Nachher | +|---|---|---| +| p99 Latenz | 800ms | 120ms | +| CPU | 85% | 35% | +``` + +## Reference Files + +- `references/curriculum-mapping.md` — Concept → MIT 6.172 Lecture + Brendan Gregg Kapitel +- `references/use-method.md` — Ressourcen-Checkliste (U/S/E), Schnell-Diagnose, p99 vs. Average +- `references/bentley-rules.md` — Datenstruktur / Logik / Loop / Memory Optimierungsregeln diff --git a/plugins/dev/skills/tool-perf/references/bentley-rules.md b/plugins/dev/skills/tool-perf/references/bentley-rules.md new file mode 100644 index 0000000..a0eaaba --- /dev/null +++ b/plugins/dev/skills/tool-perf/references/bentley-rules.md @@ -0,0 +1,63 @@ +# Bentley Rules fuer Performance-Optimierung + +Quelle: MIT 6.172 Lecture 2. Aus Jon Bentley "Writing Efficient Programs" (1982), +destilliert von Charles Leiserson und Julian Shun. + +## Datenstrukturen + +| Regel | Technik | Beispiel | +|---|---|---| +| Augmentation | Zusaetzliche Info in Struktur cachen | Summe in BST-Knoten mitfuehren | +| Precomputing | Teure Ergebnisse vorab berechnen | Lookup-Tabelle fuer Sinus-Werte | +| Compile-Time Init | Konstanten zur Compile-Zeit | `constexpr`, statische Arrays | +| Caching | Haeufige Ergebnisse zwischenspeichern | Memoization, LRU-Cache | +| Lazy Evaluation | Erst berechnen wenn noetig | Iteratoren, Generator-Patterns | +| Coarsening Recursion | Basisfall frueher abbrechen | n < 16 → Insertion Sort statt Quicksort | + +## Logik + +| Regel | Technik | Beispiel | +|---|---|---| +| Constant Folding | Konstante Subexpressions vorab | `2 * 3.14159` zur Compile-Zeit | +| Common Subexpression | Gleiche Berechnung nur einmal | `len(arr)` aus dem Loop heraus | +| Algebraic Identities | Aequivalente guenstigere Op | Division durch 2 → Right-Shift | +| Short-Circuit Evaluation | Guenstige Bedingung zuerst | `if cheap_check && expensive_check` | +| Loop-Invariant Hoisting | Konstantes aus Loop | Array-Laenge vor Loop berechnen | +| Tail-Recursion | Tail Calls → Iteration | Kein Stack-Wachstum | + +## Loops + +| Regel | Technik | Wann | +|---|---|---| +| Hoisting | Invariante Berechnung vor Loop | Jede nicht-abhaengige Berechnung | +| Sentinels | Grenzwert als letztes Element | Erspart Bounds-Check | +| Unrolling | Mehrere Iter. pro Loop-Body | Wenn Branch-Prediction kostet | +| Fusion | Zwei Loops zu einem | Wenn beide ueber gleiche Daten | +| Early Exit | Break/Return bei erstem Fund | Search, Validation | + +## Funktionen + +| Regel | Technik | Wann | +|---|---|---| +| Inlining | Kleine Funktion direkt einbetten | Call-Overhead messbar | +| Tail-Call Optimization | Letzter Call ohne neuen Frame | Rekursive Funktionen | + +## Memory / Cache + +| Regel | Technik | Beispiel | +|---|---|---| +| Cache-Friendly Access | Row-major fuer 2D Arrays | `arr[i][j]` statt `arr[j][i]` | +| Struct Packing | Padding minimieren | Grosse Felder zuerst | +| Data Alignment | SIMD / Cache-Line Alignment | `__attribute__((aligned(64)))` | +| False Sharing vermeiden | Shared Cache-Lines zwischen Threads | Padding zwischen Thread-Daten | + +--- + +## Warnung: Premature Optimization + +> "The real problem is that programmers have spent far too much time worrying about +> efficiency in the wrong places and at the wrong times." +> — Donald Knuth + +**Vorgehen immer:** Messen → Bottleneck identifizieren → Optimieren → Messen. +Nie ohne Profiling-Daten optimieren. diff --git a/plugins/dev/skills/tool-perf/references/curriculum-mapping.md b/plugins/dev/skills/tool-perf/references/curriculum-mapping.md new file mode 100644 index 0000000..29eefc4 --- /dev/null +++ b/plugins/dev/skills/tool-perf/references/curriculum-mapping.md @@ -0,0 +1,18 @@ +# Curriculum Mapping — tool-perf + +| Concept | Reference | +|---|---| +| USE Method (Utilization/Saturation/Errors) | Brendan Gregg "Systems Performance", Kap. 2: Methodologies | +| Flamegraph erstellen und lesen | Brendan Gregg, Kap. 2 + github.com/brendangregg/FlameGraph | +| CPU Profiling (perf, gprof, async-profiler) | Brendan Gregg, Kap. 6: CPUs | +| Memory Profiling (heap, GC, leaks) | Brendan Gregg, Kap. 7: Memory | +| Disk I/O Analyse (iostat, blktrace) | Brendan Gregg, Kap. 9: Disks | +| Network Performance (netstat, ss, tcpdump) | Brendan Gregg, Kap. 10: Network | +| Linux perf Tools (perf stat, perf record) | Brendan Gregg, Kap. 13: perf | +| Measurement and Timing | MIT 6.172, Lecture 10: Measurement and Timing | +| Bentley Rules for Optimizing Work | MIT 6.172, Lecture 2 (aus Bentley "Writing Efficient Programs", 1982) | +| Caching und Cache-Efficient Algorithms | MIT 6.172, Lecture 14: Caching and Cache-Efficient Algorithms | +| Multicore und Parallelism | MIT 6.172, Lecture 6: Multicore Programming | +| Compiler-Optimierungen verstehen | MIT 6.172, Lecture 9: What Compilers Can and Cannot Do | +| Capacity Planning Methodik | John Allspaw "The Art of Capacity Planning", Kap. 1 | +| Query Performance (EXPLAIN, Index Analysis) | CMU 15-721, Lecture 4-5: Query Execution & Processing | diff --git a/plugins/dev/skills/tool-perf/references/use-method.md b/plugins/dev/skills/tool-perf/references/use-method.md new file mode 100644 index 0000000..955b75d --- /dev/null +++ b/plugins/dev/skills/tool-perf/references/use-method.md @@ -0,0 +1,56 @@ +# USE Method — Referenz + +Quelle: Brendan Gregg "Systems Performance", Kap. 2. Fuer jede Ressource pruefen: +- **U**tilization — % Zeit busy (oder Anteil genutzt) +- **S**aturation — Queue-Tiefe / wartende Arbeit +- **E**rrors — Fehler-Events oder -Raten + +## Ressourcen-Checkliste + +| Ressource | Utilization | Saturation | Errors | Tools | +|---|---|---|---|---| +| **CPU** | CPU% gesamt und pro Core | Load Average > Anzahl Cores | Machine Check Exceptions | `top`, `mpstat`, `pidstat` | +| **Memory** | Used / Total | Page Scan Rate (si/so in vmstat) | OOM-Kills (dmesg) | `free`, `vmstat`, `sar` | +| **Network Interface** | Bytes/s ÷ Link-Bandwidth | TX/RX Drops (netstat -s) | Interface Errors | `ip -s link`, `sar -n DEV` | +| **Disk I/O** | Device %util (iostat) | Disk Queue Length (avgqu-sz) | I/O Errors (dmesg) | `iostat -xz`, `iotop` | +| **CPU Scheduler** | — | Run Queue Length (vmstat r) | — | `vmstat`, `sar -q` | +| **File Descriptors** | Open FDs / Max (ulimit) | — | EMFILE Errors (strace) | `lsof`, `ss` | +| **Mutex / Lock** | % Zeit gelockt | Thread-Wartezeit auf Lock | Deadlocks | `perf lock`, Language Profiler | +| **Thread Pool / Worker** | Active Workers / Pool Size | Queue-Tiefe | Rejected Tasks | Application Metrics | +| **DB Connection Pool** | Active Connections / Pool Max | Requests warten auf Connection | Connection Errors | App Metrics, DB Stats | + +--- + +## Vorgehen + +```text +1. Alle relevanten Ressourcen auflisten (fuer den betroffenen Stack) +2. Pro Ressource: U, S, E messen (Tools aus obiger Tabelle) +3. Engpass identifizieren: + ├─ Utilization nahe 100% → Ressource ist saturiert + ├─ Saturation > 0 → Warteschlange bildet sich + └─ Errors > 0 → Sofort untersuchen +4. Ressource mit hoechster Saturation oder Errors = primaerer Bottleneck +5. Tiefer analysieren mit profilierungs-spezifischen Tools (Flamegraph) +``` + +--- + +## Schnell-Diagnose: Web-Service langsam + +| Symptom | Verdacht | USE-Check | +|---|---|---| +| Hohe Latenz, niedrige CPU | I/O-bound (DB, Disk, Network) | Disk: %util, avgqu-sz; Network: Drops | +| Hohe CPU, viele Requests | CPU-bound | CPU: %usr, %sys; Scheduler: Run Queue | +| Requests stehen in Queue | Concurrency-Problem | Thread/Worker Pool: Saturation | +| Speicherlecks (Anstieg ueber Zeit) | Memory-bound | Memory: Used/Total, Page Scans, OOM | +| Sporadische Spikes | Lock Contention oder GC Pauses | Mutex Saturation, GC Logs | + +--- + +## p99 vs. Average — Warum Average luegt + +Durchschnittliche Latenz kann gut aussehen waehrend p99 katastrophal ist. +Immer Percentiles messen: p50 (median), p95, p99, p999. + +Faustregel: p99 ist der "worst normal case" — was erleben 1 von 100 Nutzern?