Communitygithub.com

Medev/skills

Escribe y afina trabajos de PySpark: estrategias de join, límites de broadcast, tamaño de particiones de shuffle, diagnóstico y corrección de skew, evitación de UDF, caché y diseño de archivos de salida. Úsalo cuando te pregunten

¿Qué es skills?

Esta skill está diseñada para ayudar a desarrolladores que trabajan con PySpark a diagnosticar y optimizar trabajos lentos, con uso intensivo de memoria o sesgados. Proporciona un procedimiento operativo paso a paso que comienza con la recopilación de información (código del trabajo, plan de ejecución, UI de Spark, tamaños de datos y configuración del clúster) para diagnosticar el cuello de botella antes de sintonizar. La skill se enfoca en las tres causas principales de lentitud: shuffles evitables, claves con sesgo (skew) y el uso de UDF de Python que procesan fila por fila. Ofrece estrategias concretas como la difusión (broadcast) de tablas pequeñas, el uso de UDF vectorizados de Pandas, el salting de claves calientes, y la configuración adecuada de `spark.sql.shuffle.partitions` para objetivos de 100-200 MB por partición. La skill aplica a plataformas como Spark/PySpark y es ideal tanto para trabajos nuevos como para ajustes de rendimiento. Incluye ejemplos prácticos de joins buenos y malos, y un entregable claro: código revisado más una nota de ajuste con evidencia de tamaño, estrategia de join, manejo de skew, decisiones de caché y expectativas de archivos de salida. No debe usarse para diseño de pipelines de streaming (usar kafka-pipelines) ni para DataFrames pequeños que quepan en memoria de una sola máquina (usar pandas-expert).

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/SkillMedev/skills/tree/HEAD/skills/spark-jobs

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Spark & PySpark

Casi todo trabajo lento de Spark lo es por una de tres razones: un shuffle evitable, una clave con sesgo (skew), o filas que pasan por Python una a una. El error costoso es ajustar el tamaño del clúster antes de leer el plan: pagar por más ejecutores para ejecutar el mismo DAG ineficiente más rápido.

Procedimiento operativo

Paso 1: Recopilar información

  1. El código del trabajo y, para un trabajo lento, la vista de la UI de Spark de la etapa lenta (distribución de duración de tareas, tamaños de lectura/escritura de shuffle) y la salida de df.explain(True).
  2. Tamaño y formato de los datos de entrada, y los tamaños de ambos lados de cada join.
  3. Configuración del clúster: número de ejecutores, núcleos y memoria.
  4. Si el trabajo es una nueva creación o un pase de ajuste; para ajuste, diagnosticar desde el plan antes de tocar el código.

Paso 2: Comenzar con una sesión adecuada

from pyspark.sql import SparkSession
from pyspark.sql import functions as F

spark = (
    SparkSession.builder
    .appName("etl")
    .config("spark.sql.shuffle.partitions", "200")
    .config("spark.sql.adaptive.enabled", "true")
    .getOrCreate()
)

Habilitar Adaptive Query Execution (AQE); fusiona particiones de shuffle y cambia estrategias de join en tiempo de ejecución. Luego dimensionar spark.sql.shuffle.partitions deliberadamente: apuntar a 100-200 MB por partición de shuffle, así que particiones ≈ tamaño de datos de shuffle ÷ 128 MB, y al menos 2-3 veces el total de núcleos de ejecutores para que ningún núcleo esté inactivo.

Paso 3: Permanecer en la API de DataFrame y fuera de Python

Las operaciones de DataFrame pasan por Catalyst y Tungsten, lo que proporciona optimización de consultas y memoria fuera del heap. Pasar a RDDs solo cuando no exista un primitivo de DataFrame. Las UDF de Python serializan cada fila al worker de Python y viceversa, rompiendo la generación de código. Orden de preferencia:

  1. Funciones integradas de pyspark.sql.functions (ej. F.regexp_extract, F.when).
  2. UDF de Pandas (vectorizadas) cuando Python sea inevitable.
  3. UDF escalares de Python solo como último recurso.
from pyspark.sql.functions import pandas_udf

@pandas_udf("double")
def normalize(s):
    return (s - s.mean()) / s.std()

Paso 4: Elegir la estrategia de join por tamaño

  • Hacer broadcast del lado más pequeño cuando quepa en memoria. Spark emite broadcast automáticamente por debajo de spark.sql.autoBroadcastJoinThreshold (por defecto 10 MB); hacer broadcast explícitamente de tablas de hasta unos pocos cientos de MB cuando la memoria del ejecutor lo permita, y considerar ~1 GB como el límite práctico: broadcast copia la tabla a cada ejecutor y provoca OOM en el trabajo si se juzga mal.
from pyspark.sql.functions import broadcast
result = large.join(broadcast(small), "key")
  • Filtrar y proyectar columnas antes de unirse para reducir el shuffle; cada columna y fila eliminada son bytes de shuffle ahorrados.
  • Dos tablas grandes → aceptar el sort-merge join, pero verificar primero si hay skew (Paso 5).

Paso 5: Diagnosticar y corregir el skew

Síntomas de skew: la etapa está completa excepto por una o dos tareas; la duración máxima de la tarea supera ~3-5 veces la mediana; una partición de lectura de shuffle es mucho más grande que el resto en la UI de Spark. El manejo de skew de AQE divide una partición cuando es más de 5 veces el tamaño de partición mediana y más de 256 MB (los valores predeterminados); verificar que se activó en el plan. Cuando AQE no puede ayudar (ej. agregación sesgada), aplicar salting a las claves calientes: agregar un sufijo aleatorio 0..N a la clave en el lado grande, explotar el lado pequeño en todos los N sufijos, unir y luego quitar la sal. Elegir N ≈ el factor de skew (una clave 20 veces la mediana obtiene N=20).

Paso 6: Controlar la partición y el diseño de salida

  • repartition(n, col) hace un shuffle completo para equilibrar los datos; usar antes de escrituras amplias.
  • coalesce(n) reduce las particiones sin shuffle; usar para evitar archivos de salida pequeños.
  • Apuntar a archivos de salida de 128 MB-1 GB; miles de archivos pequeños perjudican a todos los lectores downstream.
  • Particionar la salida solo por columnas de baja cardinalidad (fecha, región: docenas a cientos de valores, nunca IDs):
df.write.partitionBy("dt").mode("overwrite").parquet("/data/out")

Paso 7: Cachear solo lo que se reutiliza

Cachear solo cuando un DataFrame se use múltiples veces en el DAG, materializarlo y despersistir al terminar:

df.cache()
df.count()  # materializar
# ... reutilizar df ...
df.unpersist()

Cachear un DataFrame usado una sola vez desperdicia memoria y puede desalojar datos que sí importaban.

Paso 8: Verificar con el plan

Volver a ejecutar df.explain(True) y confirmar que aparezca la estrategia deseada (BroadcastHashJoin, filtros empujados, sin Exchange donde se eliminó uno). Leer formatos columnares (Parquet, ORC) para que funcione el pushdown de predicados, nunca hacer collect() de datos grandes al driver, y preferir referencias F.col sobre cadenas de columnas al encadenar.

Ejemplo práctico: join malo vs bueno

Malo: una tabla de eventos de 2 TB unida a una dimensión de 200 MB, ancho completo, UDF de Python para analizar:

result = (events.join(dims, "store_id")          # sort-merge: shufflea todos los 2 TB
    .withColumn("region", parse_region_udf("meta"))  # Python fila por fila
    .filter(F.col("dt") == "2024-06-01"))            # filtrar DESPUÉS del join

El plan muestra un Exchange en ambos lados (2 TB shuffleados), y la UDF bloquea la generación de código.

Bueno: filtrar y proyectar primero, hacer broadcast de la dimensión, usar una función integrada:

result = (events
    .filter(F.col("dt") == "2024-06-01")              # podar a ~30 GB primero
    .select("store_id", "amount", "meta")
    .join(broadcast(dims.select("store_id", "region_code")), "store_id")
    .withColumn("region", F.regexp_extract("meta", r"region=(\w+)", 1)))

El plan ahora muestra BroadcastHashJoin sin Exchange del lado grande: ~30 GB escaneados, cero shuffle de la tabla grande, sin límite de Python.

Entregable

Producir el código del trabajo revisado más una nota de ajuste que indique: la estrategia de join para cada join con la evidencia de tamaño, la configuración de las particiones de shuffle con su cálculo, cualquier skew encontrado (relación de tarea máxima vs mediana) y la corrección aplicada, decisiones de caché, expectativas de tamaño de archivos de salida y los deltas de explain antes y después para un pase de ajuste.

NO hacer

  • NO hacer broadcast de una tabla que no se haya medido; un broadcast mal calculado provoca OOM en todos los ejecutores a la vez.
  • NO escribir una UDF de Python antes de verificar pyspark.sql.functions; casi toda la lógica de cadenas, fechas y condicionales tiene una función integrada.
  • NO hacer collect() o toPandas() de un DataFrame grande; canaliza los datos del clúster a través de un solo driver.
  • NO particionar la salida por una columna de alta cardinalidad: millones de directorios, una fila cada uno.
  • NO agregar ejecutores a un trabajo cuya etapa lenta es una tarea sesgada; más núcleos no pueden dividir una partición.
  • NO cachear por reflejo; cachear solo DataFrames reutilizados downstream, y despersistirlos.

Nivel de calidad

Un trabajo terminado pasa solo cuando: cada join nombra su estrategia y la evidencia de tamaño para ella; spark.sql.shuffle.partitions se deriva del tamaño de los datos, no se deja en un valor por costumbre; la UI de Spark no muestra ninguna tarea por encima de ~3x la duración mediana en etapas de shuffle (o el skew está explicado y corregido); no sobrevive ninguna UDF escalar de Python donde exista una función integrada; los archivos de salida caen en el rango de 128 MB-1 GB; y el explain final confirma el plan previsto.

Individual skills in this repo

This repo contains 19 individual skills — each has its own dedicated page.

SkillMedev/skills

Designs REST API surfaces - resource naming, HTTP method and status-code semantics, error shapes, pagination, and filtering - and delivers an endpoint spec a consumer can build against without asking questions. Use when someone asks "how should I name this endpoint", "what status code should this return", "should this be PUT or PATCH", "how do I paginate this list", or is reviewing an API before it ships to external consumers. Do NOT use for planning breaking-change rollouts and deprecation windows - use api-versioning-strategist instead; for GraphQL type and resolver design - use graphql-schema instead; for generating client SDKs from an existing spec - use api-client-generator instead; for designing inbound webhook endpoints - use webhook-receiver-hardener instead.

SkillMedev/skills

Produce an accurate, properly timed caption track (SRT or WebVTT) from a video's audio - transcribing or aligning to the voiceover script, timing cues to speech, and enforcing line-length and reading-speed rules so captions are readable and in sync. Use when someone says "generate captions", "make subtitles from the audio", "transcribe and caption this", "export an SRT or VTT", "the captions are out of sync", or "the subtitles flash by too fast to read". Do NOT use to burn-in, style, reframe, or position an existing caption track for a platform (9:16, brand styling, safe areas) - that is social-video-formatter; do NOT use to animate text word-by-word as a motion graphic - that is kinetic-typography; do NOT use to write the spoken script in the first place - that is narration-script.

SkillMedev/skills

Turns data and charts into a decision-driving narrative structured as headline finding, trend, implication, and recommended action - with finding-led chart titles, context for every number, annotation guidance, and honest flags on any conclusion the data cannot support. Use when someone says "turn these numbers into a story", "what's the takeaway from this data", "help me present these results to leadership", or has charts but no narrative. Do NOT use for compressing a long document into a one-pager - use executive-summary instead - or for running the analysis that produces the findings - use eda-playbook instead.

SkillMedev/skills

Use when a task needs live or historical money data - "convert USD to EUR", "current/past exchange rate", "FX rate on this date / over this range", or "current price of Bitcoin/Ethereum, market cap, 24h change". Frankfurter (ECB reference rates, no key) is the FX default; CoinGecko's free keyless tier covers crypto. Do NOT use for stock quotes or equities - no keyless stock API survives verification, say so instead of guessing; do NOT use for country economic indicators like GDP or inflation series - use government-open-data instead; if the request is a vague "I need live data", route through public-data-api-picker.

SkillMedev/skills

Builds a driver-based FP&A operating model linking business inputs to P&L, balance sheet, and cash flow outputs. Use when building an annual plan, preparing investor materials, running scenario analysis, or stress-testing the business.

SkillMedev/skills

Use when a task needs live geographic lookups - "geocode this address", "what's at these coordinates" (reverse geocoding), "lat/lon for this city", "which country/state is this ZIP or postal code in", or "country facts: capital, currency, population, flag". Nominatim (OpenStreetMap) is the geocoding default; Zippopotam for postal codes; APICountries for country facts. All keyless. Do NOT use for weather at a location - use weather-climate instead; do NOT use for country-level statistics over time (GDP, population trends) - use government-open-data instead; if the request is a vague "I need live data", route through public-data-api-picker.

SkillMedev/skills

Runs the full Getting Things Done loop - capture, clarify, organize, reflect, engage - building a trusted system of context lists, a projects list with defined next actions, and a weekly review habit. Use when someone says "I'm overwhelmed and things are slipping through the cracks", "set up GTD for me", "help me do a brain dump and organize it", or "my to-do list is a mess". Do NOT use for just running the weekly review ritual itself - use weekly-review instead - or for clearing an email backlog - use inbox-zero.

SkillMedev/skills

Processes any email backlog to zero using the 4Ds - Delete, Delegate, Defer, Do - with a mass-archive strategy for the obvious, a touch-each-email-once discipline, and a keep-it-clear system of batched processing windows, ruthless unsubscribing, filters, and a minimal folder setup. Use when someone says "I have 5,000 unread emails", "help me get to inbox zero", "email is eating my whole day", or treats their inbox as a to-do list. Do NOT use for drafting the reply emails themselves or prioritization rules for an ongoing support queue - use email-triage instead - or for protecting focus time around the email windows - use deep-work-planner instead.

SkillMedev/skills

Write landing-page copy section by section - hero, social proof, features-as-benefits, objections, CTA - leading with one promise and proving it down the page. Use when someone asks "write my landing page", "improve my hero headline", "what should the homepage say", "turn these features into benefits", or is shipping a new page for a launch or campaign. Do NOT use for testing and optimizing an existing page's conversion rate - use landing-page-cro instead; for the one-line claim itself use positioning-statement; for the full message ladder use messaging-hierarchy.

SkillMedev/skills

Improves an existing landing page's conversion rate through evidence-first CRO - audit heatmaps and recordings, write structured hypotheses, prioritize with ICE scoring, and run one-variable tests to statistical significance. Use when someone asks "why isn't my landing page converting", "audit this page before we scale spend", "which A/B test should we run first", or after a CVR drop or ahead of a paid-traffic push. Do NOT use for writing a new landing page from scratch - use landing-page-copy instead. Do NOT use for auditing the ad accounts sending the traffic - use paid-acquisition-audit instead. Do NOT use for reading the results of a finished experiment - use ab-test-analyzer instead.

SkillMedev/skills

Runs structured coaching sessions using values clarification and the GROW model, ending every session with one committed action, a deadline, and an if-then plan for the likely obstacle. Use when someone says "I feel stuck in my life", "help me figure out what I want", "hold me accountable to my goals", or "coach me through this decision". Do NOT use for building a stress toolkit - use stress-management instead - or a journaling practice - use journal-framework; for a standing goal-tracking system, use goals-accountability. Coaching, not therapy: signs of clinical distress route to a licensed professional.

SkillMedev/skills

Adapts English content for a target language and region - swapping idioms, setting the right formality register, replacing cultural references, converting dates, units, and currency - and delivers the localized text with a notes column explaining each adaptation and flagging what needs a native reviewer. Use when someone asks "localize this copy for the Japanese market", "adapt our marketing copy for the Mexican market", "make this translation sound native instead of literal", or a literal translation reads foreign, stiff, or risky. Do NOT use for auditing in-product UI text quality - use ux-writing-audit instead.

SkillMedev/skills

Turns a natural-language video brief into a complete, ready-to-preview Remotion composition - extracts duration, scenes, brand colors, aspect ratio, and real copy; plans the frame budget; and writes data-driven React/TypeScript using useCurrentFrame, interpolate, spring, AbsoluteFill, and Sequence, registered in Root.tsx. Use when someone says "build a 20-second product demo video", "animate a feature walkthrough", "write the Remotion code for this marketing clip", or wants a scene-by-scene composition they can scrub in Studio. Do NOT use for rendering, iterating, or batching the finished MP4 - use remotion-render instead - or for installing and scaffolding the project - use remotion-setup instead.

SkillMedev/skills

Scaffolds a new Remotion video project wired for Claude Code Agent Skills - Node check, create-video scaffold, skills install, folder conventions, Google Fonts, and a smoke-test render. Use whenever someone wants to start making videos with Remotion and Claude, even just "make product videos with Claude.

SkillMedev/skills

Classifies incident severity (SEV1-4) using impact, scope, and urgency signals and decides who to page. Use when an alert fires or a report comes in and a severity call must be made quickly.

SkillMedev/skills

Use the Skill Me catalog from inside any conversation - discover, install, and manage Claude skills through the Skill Me MCP, and load installed skills automatically each session.

SkillMedev/skills

Write one platform-native caption from a topic and brand voice, with a front-loaded hook, native length, and a single earned CTA. Use when the user gives a topic (and optionally brand voice or a described image/video) and asks for an Instagram, LinkedIn, X/Twitter, or TikTok caption. Do NOT use when the user wants a dedicated standalone LinkedIn post - use linkedin-post-writer instead; or a multi-post X thread - use tweet-thread-builder instead; or to adapt one existing piece of content into versions for several channels - use cross-platform-reformatter instead.

SkillMedev/skills

Reframe and export a finished video for social platforms - 9:16 ↔ 16:9 cropping, burned-in captions, a platform-native first frame, loop design, and per-platform specs (aspect, length, safe areas) for TikTok, Reels, Shorts, X, and LinkedIn. Use when someone says "make this vertical", "crop to 9:16", "format for TikTok/Reels/Shorts", "add captions/subtitles", "why is my video cut off on mobile", "resize for Instagram", or "export for social". Do NOT use when the question is about the storyboard or shot order before any video exists (use video-storyboard); the animation craft of how elements move (use motion-design-principles); animated word-by-word caption styling (use kinetic-typography); palette, contrast, or lighting (use motion-color-and-light); directing the product-demo content and screen choreography (use product-demo-director); or scoring, beat-syncing, or audio (use sound-and-music-sync) - this is the craft layer that decides WHAT to format for the feed, then hands a concrete spec to remotion-compo...

SkillMedev/skills

Builds clean, performant, accessible SwiftUI views with correct state ownership, scoped invalidation, and smooth list scrolling, and reviews existing SwiftUI code against a concrete frame-time and re-render budget. Use when someone asks "why does my SwiftUI list stutter", "should this be @State or @Observable", "my whole screen re-renders when one row changes", "how do I animate this transition", or wants a SwiftUI view built or refactored. Do NOT use for cross-platform React Native apps - use react-native-pro instead; do NOT use for Flutter widget trees - use flutter-widget-architect instead; do NOT use for Android Compose UIs - use jetpack-compose-builder instead.

Skills relacionados