diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 0589777..f5831af 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -574,6 +574,26 @@ ], "formatNotes": "All three. Point the tool at the Deployment/StatefulSet manifest or Helm chart + values file, the HPA or KEDA ScaledObject, and the namespace's ResourceQuota/LimitRange. Copilot: aks-hpa-requests-limits path instructions plus those files in agent mode. Claude Code: the aks-hpa-requests-limits-guardrails skill plus the manifests. Codex: AGENTS.md autoscaling section, then the diff.", "body": "Task: Review and tune resource requests/limits and HorizontalPodAutoscaler settings for the AKS workload I specify. Produce a small, reviewable YAML or Helm values diff with the reasoning behind every number.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Workload: {{WORKLOAD}} (Deployment/StatefulSet name)\n- Namespace: {{NAMESPACE}}\n- Manifest path: {{MANIFEST_PATH}} (raw YAML, kustomize overlay, or Helm chart + values file)\n- Scaling metric: {{METRIC}} (cpu | memory | custom | keda)\n- Target: {{TARGET}} (e.g. 70% CPU, 200 RPS per pod, 50 messages per replica)\n- Min replicas: {{MIN_REPLICAS}}\n- Max replicas: {{MAX_REPLICAS}}\n- Cluster Autoscaler on node pool: {{HAS_CLUSTER_AUTOSCALER}} (yes + min/max nodes | no | unknown)\n- Evidence available: {{EVIDENCE}} (load test | VPA recommendation | p95 from Container Insights/Prometheus | none)\n\nRequirements:\n\n1. Inventory\n - Every container in {{WORKLOAD}} (app, sidecars, init): current requests, limits, and resulting QoS class\n - Existing HPA / KEDA ScaledObject for {{WORKLOAD}}: metric, target, min/max, `behavior`\n - PodDisruptionBudget, LimitRange, and ResourceQuota in {{NAMESPACE}}\n - Any VPA object targeting {{WORKLOAD}} and its `updateMode`\n - Whether metrics-server (resource metrics) or the custom/external metrics adapter needed for {{METRIC}} is present\n\n2. Design\n - Add missing requests first; HPA utilization is a percentage of requests\n - Propose requests/limits from {{EVIDENCE}}; if none, give conservative starting values and say they must be validated\n - State the chosen QoS class (Burstable by default; Guaranteed only with a latency/noisy-neighbor reason)\n - {{METRIC}}=cpu: start {{TARGET}} in the 60–80% band unless evidence says otherwise\n - {{METRIC}}=custom or keda: name the metric/scaler and confirm only one autoscaler owns the Deployment\n - Check `{{MAX_REPLICAS}} × per-pod requests` against ResourceQuota and node pool capacity; with {{HAS_CLUSTER_AUTOSCALER}}=yes, check against max nodes and note scale-up lag\n - Prod: `{{MIN_REPLICAS}} >= 2` and consistent with the PDB\n - Add `behavior.scaleDown` stabilization and policies to stop flapping\n - Flag VPA in update mode on the same metrics as a conflict; recommend `updateMode: \"Off\"`\n\n3. Author artifacts\n - Minimal diff to {{MANIFEST_PATH}} (values file for Helm; keep template defaults safe)\n - Inline comments recording where each number came from\n - Do not change Cluster Autoscaler, node pool, or quota settings unless I ask — list recommended changes separately\n\n4. Verification\n - `kubectl apply --dry-run=server -f …` (or `helm template … | kubectl apply --dry-run=server -f -`)\n - `kubectl -n {{NAMESPACE}} describe hpa {{WORKLOAD}}` shows real targets, not ``\n - `kubectl -n {{NAMESPACE}} top pods -l app={{WORKLOAD}}` during a ramp\n - `kubectl -n {{NAMESPACE}} describe quota` and pending-pod events after scale-up\n\nConstraints:\n- Match existing manifest/Helm style; no unrelated refactors.\n- Do not invent metric names, cluster sizes, or quota values — use placeholders if unknown.\n- Do not rewrite probes; reference the probes skill if they block readiness.\n- Optimize for GitHub Copilot, Claude Code, and Codex — concrete YAML and a checklist.\n\nOutput format:\n1. Summary table: container | old req/lim | new req/lim | QoS | rationale; plus HPA old vs new (metric, target, min, max, behavior)\n2. Patch (YAML or values diff)\n3. Risks: VPA/KEDA conflicts, missing metrics pipeline, quota or Cluster Autoscaler limits\n4. Verification commands and expected output\n\nStart from {{MANIFEST_PATH}}. Add missing requests before touching HPA targets.\n" + }, + { + "id": "tune-spark-job-performance", + "title": "Tune a Spark Job From Its Plan and Metrics", + "whenToUse": "Take a slow or costly Spark/PySpark job, diagnose its hotspots from the physical plan and Spark UI metrics, and produce a minimal code/config diff with a before/after comparison.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "spark", + "pyspark", + "databricks", + "performance", + "data-platform", + "sql" + ], + "formatNotes": "All three. Point the tool at the job entrypoint, the job/cluster config, and any saved `explain` output or Spark UI stage metrics (paste the top slow stages if logs are not in the repo). Copilot: spark-job-tuning path instructions plus those files in agent mode. Claude Code: the spark-job-tuning-guardrails skill plus the job file. Codex: AGENTS.md Spark performance section, then the diff.", + "body": "Task: Diagnose and tune the Spark job I specify. Work from the physical plan and run metrics, apply the smallest set of changes that measurably helps, and give me a before/after comparison I can paste into the PR.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Job entrypoint: {{JOB_PATH}} (PySpark/Scala file, notebook, or SQL file)\n- Platform: {{PLATFORM}} (databricks | synapse | hdinsight | spark-on-k8s | other)\n- Spark version: {{SPARK_VERSION}}\n- Inputs: {{INPUTS}} (tables/paths with approximate size and format)\n- Output: {{OUTPUT}} (table/path, format, partition columns)\n- Symptom: {{SYMPTOM}} (sla-miss | straggler-tasks | spill | small-files | oom | cost)\n- Evidence available: {{EVIDENCE}} (spark-ui | event-logs | explain-output | run-history | none)\n- Cluster definition: {{CLUSTER}} (path to job/cluster config, or \"unknown\")\n- Target: {{TARGET}} (e.g. under 30 min, 40% less cost, no spill)\n\nRequirements:\n\n1. Inventory\n - Read {{JOB_PATH}} end to end: sources, filters, joins, aggregations, window functions, UDFs, `cache`/`persist`, `collect`/`toPandas`, and the final write\n - Current Spark configs set in code, job JSON, or {{CLUSTER}} (AQE flags, shuffle partitions, broadcast thresholds, memory)\n - {{OUTPUT}} layout: partition columns, typical file count and size, compaction schedule if any\n - Whether table statistics exist for {{INPUTS}}\n\n2. Diagnose\n - Produce or request `explain(mode=\"formatted\")` for the heaviest query; list each Exchange, join strategy, and whether pushdown/pruning reached the scan\n - From {{EVIDENCE}}: top three slowest stages with shuffle read/write, spill, task count, and max vs p75 task duration\n - Classify each hotspot: excess data read, wrong join strategy, skew, bad partition sizing, spill, small files, driver bottleneck, or Python UDF overhead\n - If {{EVIDENCE}}=none, say which metrics to capture first and give a ranked hypothesis list instead of tuning blindly\n\n3. Fix (one change per hotspot, in this order)\n - Prune columns and filter before joins/aggregations\n - Choose join strategy: broadcast only a reliably small side; align key types to avoid casts\n - Skew: rely on AQE skew-join first; for aggregations or hot keys AQE cannot split, use pre-aggregation, hot-key isolation, or salting — name the hot keys\n - Partition sizing: keep AQE on; set an initial partition count high enough for coalescing; target roughly 100–200 MB per shuffle partition\n - Writes: `REBALANCE`/`repartition` by output partition columns; no high-cardinality partition columns; add or note compaction\n - Remove unneeded `cache()`, unbounded `collect()`/`toPandas()`, and replace row-at-a-time Python UDFs with built-ins or pandas UDFs\n - Change cluster size only after the above, and only with metrics showing the job is resource-bound\n\n4. Verification\n - Re-run on representative data (same skew and file layout as prod); fill the before/after table\n - Show the new plan excerpt proving the intended join/shuffle change\n - Confirm output row counts and checksums match the baseline run\n - Note behavior under 2× input growth (broadcast size, partition count)\n\nConstraints:\n- Minimal diff; match the repo's existing job structure and config style.\n- Keep AQE enabled; every config added gets a comment with its evidence.\n- Do not invent table names, cluster IDs, workspace URLs, or data sizes — use placeholders if unknown.\n- Do not change business logic or output schema; correctness beats speed.\n- Optimize for GitHub Copilot, Claude Code, and Codex — concrete code/config diffs and a checklist.\n\nOutput format:\n1. Hotspot table: stage | symptom | root cause | fix | expected impact\n2. Patch (job code + config diff)\n3. Before/after metrics: wall time, shuffle bytes, spill, max task time, output file count/size, cost if known\n4. Risks and follow-ups (data growth, stats refresh, compaction schedule)\n\nStart from {{JOB_PATH}}. Read the plan before changing any config.\n" } ] } diff --git a/skillbook/skills.json b/skillbook/skills.json index 14a38ac..18d021d 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -572,6 +572,26 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/aks-hpa-requests-limits.instructions.md` with applyTo for Deployment/HPA/Helm globs (`**/k8s/**/*.yaml`, `**/manifests/**/*.yaml`, `**/charts/**/templates/**/*.yaml`, `**/*hpa*.yaml`) (optional `.github/skills/aks-hpa-requests-limits-guardrails/SKILL.md`). Claude Code: `.claude/skills/aks-hpa-requests-limits-guardrails/SKILL.md` plus a one-line CLAUDE.md fact that HPA targets assume every container sets requests. Codex: an autoscaling section in root `AGENTS.md` or linked `docs/agents/aks-hpa-requests-limits.md`. Pair with k8s-probes-graceful-shutdown-guardrails for readiness/termination and aks-workload-hardening for security context — this skill covers sizing and autoscaling only.", "body": "# Skill: AKS HPA Requests & Limits Guardrails\n\n## Goal\nMake AKS Deployments scale predictably: every container has honest CPU/memory requests, limits are chosen on purpose, and the HorizontalPodAutoscaler reacts to the signal that actually tracks load — without flapping, starving the node pool, or fighting other autoscalers.\n\n## When to apply\n- Adding or editing a Deployment, StatefulSet, Helm values block, or `HorizontalPodAutoscaler` (`autoscaling/v2`)\n- HPA shows `` targets, never scales, or scales up and down every few minutes\n- Pods stuck `Pending` (insufficient cpu/memory) or `OOMKilled` / CPU-throttled under normal traffic\n- Namespace ResourceQuota rejections or LimitRange defaults silently changing pod specs\n- Right-sizing after a load test, incident, or cost review on AKS node pools\n\n## Baseline rules\n1. **Requests on every container.** Set `resources.requests.cpu` and `resources.requests.memory` on app containers, sidecars, and init containers. HPA resource metrics are computed as a percentage of the **request**, so a missing request means the HPA cannot compute utilization (or uses a LimitRange default that nobody chose). Treat a missing request as a bug, not a style nit.\n2. **Pick the QoS class deliberately.**\n - **Burstable** (requests < limits) is the default for most HTTP APIs and workers: it packs nodes efficiently and absorbs short spikes. Keep the memory limit close to the request (memory is not compressible — overshoot means OOMKill), and give CPU modest headroom or omit the CPU limit if the platform policy allows it.\n - **Guaranteed** (requests == limits for both CPU and memory) only for latency-critical or noisy-neighbor-sensitive workloads. It buys stable scheduling and eviction priority at the cost of idle reserved capacity and CFS throttling at the limit.\n - Write the chosen class and the reason in a manifest comment or values file.\n3. **No BestEffort in prod.** Pods with no requests/limits are evicted first and break ResourceQuota accounting. Namespaces with quotas should reject them; do not work around it by deleting the quota.\n4. **HPA only where horizontal scaling is real.** The workload must be mostly stateless (or shard-aware), tolerate extra replicas, and start fast enough to matter. For prod set `minReplicas >= 2` (pair with a PodDisruptionBudget) and set `maxReplicas` with headroom you have actually checked against node pool size, Cluster Autoscaler max node count, subnet/IP limits (Azure CNI), and downstream connection limits such as database pools.\n5. **Start CPU targets around 60–80%.** `averageUtilization` in that band leaves room for the scale-up lag (metrics scrape + pod start + readiness). Go lower for spiky traffic or slow-starting JVMs, higher for smooth batch-like load. Memory-based scaling is rarely a good primary signal for runtimes that do not release heap — prefer it only as a secondary metric.\n6. **Use the real signal when CPU is not it.** If queue depth, consumer lag, or requests-per-second drives load, scale on custom/external metrics (Prometheus adapter, Azure Monitor) or KEDA scalers (Service Bus, Event Hubs, Kafka, HTTP). KEDA owns the HPA it creates — do not also hand-write an HPA for the same Deployment.\n7. **Do not let VPA and HPA fight.** Never run VPA in `Auto`/`Recreate`/`InPlace` update mode on the same CPU/memory metrics an HPA scales on. VPA in `updateMode: \"Off\"` (recommendation-only) is fine and a good input for request sizing.\n8. **Probes gate useful capacity.** New replicas only help once they are Ready. Wire readiness and startup probes correctly — follow `k8s-probes-graceful-shutdown-guardrails` rather than re-deriving probe rules here.\n9. **Tune scale behavior to avoid flapping.** Use `behavior.scaleDown.stabilizationWindowSeconds` (default 300s; raise for bursty traffic) and `scaleDown.policies` that cap how many pods or what percent can go per period. Allow faster `scaleUp` with a short or zero window. Scale-up lag on AKS includes node provisioning when Cluster Autoscaler must add nodes — budget minutes, not seconds.\n10. **Respect ResourceQuota and LimitRange.** Check the namespace's quota (`requests.cpu`, `requests.memory`, `limits.*`, pod count) against `maxReplicas × per-pod requests`. Know what LimitRange defaults and min/max apply so manifest values are not silently overridden or rejected at admission.\n11. **Document where the numbers came from.** Record the evidence next to the values: load-test result, VPA recommendation, or observed p95 CPU/memory from Container Insights / Prometheus over a representative window. \"Copied from another service\" is not evidence.\n12. **Keep Helm and raw manifests in sync.** Resources and HPA settings live in values (per environment) with sane chart defaults; templates must not drop requests when a value is unset.\n\n## Workflow\n1. Inventory: containers (incl. sidecars/init), current requests/limits, QoS class, HPA spec/behavior, PDB, LimitRange, ResourceQuota, node pool SKU and autoscaler bounds.\n2. Measure: `kubectl top pods`, Container Insights or Prometheus p95/p99 over at least a week of normal traffic, plus a load test where possible.\n3. Size requests from steady-state p95 plus small headroom; set memory limit from peak plus safety margin; decide CPU limit by policy.\n4. Choose metric and target; set min/max with quota and node capacity math shown.\n5. Add `behavior` for scale-down stabilization; verify with a load ramp and `kubectl describe hpa`.\n\n## Anti-patterns\n- HPA on a Deployment whose containers have no CPU request\n- Sidecar with no requests making utilization math wrong for the whole pod\n- `maxReplicas: 100` with a 3-node pool and no Cluster Autoscaler\n- `minReplicas: 1` for a prod API with a PDB of `minAvailable: 1`\n- CPU limit equal to a tiny request on a JVM service (throttling at startup, slow readiness)\n- Memory limit far above request (\"burst\" that ends in node-pressure eviction)\n- VPA `Auto` mode plus CPU HPA on the same workload\n- Hand-written HPA alongside a KEDA ScaledObject for the same target\n- Scaling on memory for a heap-retaining runtime and never scaling down\n- Deleting or inflating ResourceQuota to make a rollout pass\n\n## Tool placement notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/aks-hpa-requests-limits.instructions.md` with `applyTo` covering `**/k8s/**/*.yaml`, `**/manifests/**/*.yaml`, `**/charts/**/templates/**/*.yaml`, `**/charts/**/values*.yaml`, and `**/*hpa*.yaml`.\n- Optional `.github/skills/aks-hpa-requests-limits-guardrails/SKILL.md` for agent mode.\n\n### Claude Code\n- Procedure in `.claude/skills/aks-hpa-requests-limits-guardrails/SKILL.md`.\n- One CLAUDE.md fact: \"HPA utilization targets assume every container sets CPU/memory requests; never add an HPA without them.\"\n\n### Codex\n- An autoscaling section in root `AGENTS.md`, or `docs/agents/aks-hpa-requests-limits.md` linked from it, listing the request/limit policy, target band, and verification commands.\n\nPair with `k8s-probes-graceful-shutdown-guardrails` (readiness/termination) and `aks-workload-hardening` (security context, pod security) — this skill covers sizing and autoscaling only.\n\n## Review checklist\n- [ ] Every container (incl. sidecars/init) has CPU and memory requests\n- [ ] QoS class is intentional and documented; no BestEffort in prod\n- [ ] Memory limit set from observed peak; CPU limit follows platform policy\n- [ ] HPA metric matches the real load signal (CPU, custom, or KEDA)\n- [ ] `minReplicas >= 2` in prod; `maxReplicas` fits quota, node pool, and CA bounds\n- [ ] No VPA update mode on the same metrics; KEDA and HPA not doubled up\n- [ ] Scale-down stabilization/policies set; ramp test shows no flapping\n- [ ] Evidence for the numbers recorded in the PR or values comments\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: aks-hpa-requests-limits-guardrails\ndescription: Use when adding or tuning AKS Deployments and HPAs — requests on every container, deliberate QoS, CPU target 60–80% or custom/KEDA metrics, scale-down stabilization, quota and node pool math, no VPA update mode on the same metrics.\n---\n\nFollow AKS HPA Requests & Limits Guardrails: requests everywhere, evidence-based sizing, intentional QoS, minReplicas >= 2 in prod, maxReplicas within quota and autoscaler bounds, and stabilized scale-down.\n```\n" + }, + { + "id": "spark-job-tuning-guardrails", + "title": "Spark Job Performance Tuning Guardrails", + "whenToUse": "Reviewing or tuning Spark, PySpark, or Spark SQL batch jobs that miss their SLA, spill, show straggler tasks, write small files, or add large joins and aggregations.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "spark", + "pyspark", + "databricks", + "performance", + "data-platform", + "sql" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/spark-job-tuning.instructions.md` with applyTo for job code and job configs (`**/jobs/**/*.py`, `**/src/**/*.scala`, `**/*.sql`, `**/notebooks/**/*.py`, `**/databricks.yml`, `**/resources/**/*.yml`) (optional `.github/skills/spark-job-tuning-guardrails/SKILL.md`). Claude Code: `.claude/skills/spark-job-tuning-guardrails/SKILL.md` plus a one-line CLAUDE.md fact that Spark tuning is baseline → plan → one change at a time with AQE on. Codex: a Spark performance section in root `AGENTS.md` or a nested `AGENTS.md` under the jobs directory. Pair with data-platform-pipeline-review for contracts, idempotency, and PII — this skill covers runtime performance only.", + "body": "# Skill: Spark Job Performance Tuning Guardrails\n\n## Goal\nMake Spark / PySpark / Spark SQL batch jobs faster and cheaper by fixing what the physical plan and Spark UI actually show — shuffle volume, skew, spill, join strategy, and file layout — instead of guessing at cluster size or pasting config snippets.\n\n## When to apply\n- A job breaches its SLA, runs noticeably slower after a data-volume jump, or costs more than its peers\n- Spark UI shows one or two straggler tasks, heavy spill, huge shuffle read/write, or thousands of tiny tasks\n- Reviews of new joins, aggregations, window functions, UDFs, or `MERGE`/upsert logic on large tables\n- Jobs that write many small files or one giant file per partition\n- Someone proposes \"just double the workers\" or adds `.cache()` / `.repartition()` without evidence\n\n## Baseline rules\n1. **Measure before tuning.** Capture a baseline run: wall time, stage durations, input/shuffle/spill bytes, task-duration distribution (median vs max), and cluster cost. Every change is compared to that baseline on representative data — same volume, skew, and file layout as production.\n2. **Read the plan first.** Use `df.explain(mode=\"formatted\")` (or `EXPLAIN FORMATTED` / `EXPLAIN COST`) and the SQL tab of the Spark UI. Find each `Exchange` (shuffle), the join type chosen (`BroadcastHashJoin`, `SortMergeJoin`, `ShuffledHashJoin`), and whether filters and column pruning reach the scan.\n3. **Keep AQE on.** Adaptive Query Execution (default since Spark 3.2) coalesces small post-shuffle partitions, converts eligible sort-merge joins to broadcast at runtime, and splits skewed join partitions. Do not disable it to \"stabilize\" a job; tune its thresholds instead (`advisoryPartitionSizeInBytes`, skew factor and threshold).\n4. **Shrink data early.** Filter and project before joins and aggregations; read only needed columns from columnar formats; make sure partition filters and predicate pushdown appear in the scan node. Avoid `select *` across big tables and avoid exploding arrays before filtering.\n5. **Pick the join strategy deliberately.** Broadcast only a side that is reliably small after filtering (and within executor/driver memory) — use a `broadcast()` hint when the size is known and stable. Never broadcast a table that grows with business volume. For large–large joins, align keys and types so Spark does not add casts or extra shuffles.\n6. **Treat skew explicitly.** Confirm skew in the stage view (max task time or shuffle read far above the 75th percentile). Let AQE skew-join handling cover sort-merge joins first; for skew it cannot see (aggregations, broadcast joins, sub-threshold hot keys) use pre-aggregation, isolating hot keys, or salting — and document the hot keys.\n7. **Size partitions by bytes, not habit.** Aim for roughly 100–200 MB of input per shuffle partition; let AQE coalesce from a deliberately high initial partition count rather than hard-coding `spark.sql.shuffle.partitions=200` forever. Use `repartition` only when you need a key-based distribution; use `coalesce` to reduce partitions without a full shuffle.\n8. **Spill is a signal.** Large memory or disk spill means partitions are too big or rows too wide. Fix partitioning or row width first; raise executor memory only when the data per task is already sensible.\n9. **Cache only reused results.** `cache()`/`persist()` a DataFrame only when it is reused by more than one action and fits comfortably; `unpersist()` when done. Never cache \"just in case\" and never cache before a filter.\n10. **Prefer built-ins over Python UDFs.** Use Spark SQL functions first; if Python logic is unavoidable use pandas/Arrow UDFs instead of row-at-a-time UDFs. No `collect()`/`toPandas()` on unbounded data, and no driver-side loops that trigger one job per item.\n11. **Write files of healthy size.** Control output layout so files land roughly in the 128 MB–1 GB range: use the `REBALANCE` hint or `repartition` by the write partition columns, avoid high-cardinality partition columns, and schedule compaction (`OPTIMIZE` / auto-compaction or the table format's equivalent) for incrementally written tables.\n12. **Keep statistics fresh.** Run `ANALYZE TABLE … COMPUTE STATISTICS` (or rely on the table format's stats) so the optimizer's size estimates — and therefore join choices — are realistic.\n13. **Config changes live in code, scoped and explained.** Set tuning configs in the job definition (session config, job JSON, or asset bundle) with a comment stating the evidence. No cluster-wide overrides to fix a single job; no copy-pasted config blocks with unknown origin.\n\n## Workflow\n1. Inventory: job entrypoint, input tables and sizes, output table and its partitioning, cluster/pool definition, current Spark configs, last few run durations.\n2. Baseline run on representative data; save the plan and the top three slowest stages with their metrics.\n3. Diagnose each slow stage: shuffle bytes, skew (max vs p75), spill, task count, scan pruning.\n4. Apply one change at a time in priority order: prune/filter → join strategy → skew handling → partition sizing → write layout → caching → cluster size.\n5. Re-run, compare against baseline, and keep only changes that measurably help.\n6. PR notes: before/after metrics table, plan excerpts, configs added with rationale, residual risks (data growth, broadcast size drift).\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/spark-job-tuning.instructions.md` with `applyTo` for job code and configs (for example `**/jobs/**/*.py`, `**/src/**/*.scala`, `**/*.sql`, `**/notebooks/**/*.py`, `**/databricks.yml`, `**/resources/**/*.yml`).\n- Always-on line in `.github/copilot-instructions.md`: \"Spark changes need a plan excerpt and before/after stage metrics; keep AQE on; no unbounded `collect()`/`toPandas()`.\"\n- Optional `.github/skills/spark-job-tuning-guardrails/SKILL.md` for agent mode.\n\n### Claude Code\n- Procedure in `.claude/skills/spark-job-tuning-guardrails/SKILL.md`.\n- CLAUDE.md fact: \"Spark tuning is evidence-based: baseline → plan → one change at a time; AQE stays enabled; configs are set per job with a comment.\"\n- Before claiming done, show the `explain` output for the changed query and the before/after metrics.\n\n### Codex\n- A Spark performance section in root `AGENTS.md`, or nested `AGENTS.md` under the jobs directory (or linked `docs/agents/spark-job-tuning.md`).\n- State: how to run a job locally or on a dev cluster, where plans and run metrics are saved, banned patterns (row UDFs, unbounded collect, blanket cache), and the config-in-code rule.\n\n## Anti-patterns\n- Doubling cluster size before reading the plan\n- Disabling AQE or hard-coding `spark.sql.shuffle.partitions` without measuring\n- Broadcasting a dimension table that quietly grows past memory\n- Salting every join \"for safety\" when there is no skew\n- `.cache()` sprinkled across a pipeline with no `unpersist()`\n- Row-at-a-time Python UDFs where a built-in function exists\n- `collect()`/`toPandas()` on full tables inside production jobs\n- Partitioning output by a high-cardinality column (user id, timestamp) and creating millions of tiny files\n- Benchmarking on a tiny sample whose skew and file layout look nothing like production\n\n## Verification checklist\n- [ ] Baseline and post-change metrics captured on representative data\n- [ ] Plan reviewed: shuffles, join strategies, and scan pruning explained\n- [ ] AQE enabled; any threshold changes justified\n- [ ] Skew confirmed (or ruled out) from stage metrics, with the fix documented\n- [ ] Spill eliminated or explained\n- [ ] No unbounded `collect()`/`toPandas()` and no avoidable Python row UDFs\n- [ ] Output files in a healthy size range; compaction plan in place\n- [ ] Configs live in the job definition with comments\n- [ ] PR includes before/after table and residual risks\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spark-job-tuning-guardrails\ndescription: Use when a Spark, PySpark, or Spark SQL job is slow, spills, has straggler tasks, writes small files, or a review touches large joins and aggregations. Tune from the plan and Spark UI metrics with AQE on, one change at a time.\n---\n\nFollow Spark Job Performance Tuning Guardrails: baseline first, read the physical plan, keep AQE on, prune early, choose joins deliberately, handle skew explicitly, size partitions by bytes, cache only reused data, prefer built-ins over Python UDFs, write healthy file sizes, and keep tuning configs in code with evidence.\n```\n" } ] }