Communitygithub.com

Spark & PySpark

PySparkジョブの作成とチューニングを行います。結合戦略、ブロードキャストサイズ制限、シャッフルパーティション調整、スキュー診断とソルティング、UDF回避、キャッシング、出力ファイルレイアウトを具体的なサイズ・スキュー閾値とともに扱います。

Spark & PySpark とは?

このスキルは、Spark/PySparkジョブのパフォーマンス問題を診断し、修正するための専門知識を提供します。主に、遅いジョブの原因特定(不要なシャッフル、キーのスキュー、Python UDFによる行単位の処理)、適切な結合戦略の選択(ブロードキャスト結合 vs ソートマージ結合、サイズ基準に基づく)、シャッフルパーティション数の最適化(データサイズから導出)、データスキューの診断と修正(AQEの活用、ソルティング)、Python UDFの回避(ビルトイン関数やベクトル化UDFの優先)、キャッシュ戦略、および出力ファイルレイアウトの制御(適切なファイルサイズ、パーティショニング)をカバーします。このスキルは、Claude Code, Cursor, CodexなどのAIエージェント上で、特定のサイズ・スキュー閾値を用いた実践的なアドバイスを提供します。具体的な閾値(ブロードキャストの実用上限約1GB、シャッフルパーティションターゲットサイズ128MB、スキュー検出条件など)に基づき、Spark UIやExplain Planを読み解きながら、コード修正からチューニングノートの作成までを行います。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Spark & PySpark は何をしますか?

遅いSparkジョブのほとんどは、回避可能なシャッフル、スキューしたキー、またはPythonが1行ずつデータを処理することの3つの原因のいずれかによって遅くなっています。よくある間違いは、実行計画を読む前にクラスターサイズを調整することです。より多くのエグゼキュータにお金を払って同じ無駄の多いDAGをより速く実行することになります。

運用手順

ステップ1: 入力を収集する

  1. ジョブコード、および遅いジョブの場合はSpark UIの遅いステージのビュー(タスク期間分布、シャッフル読み取り/書き込みサイズ)と df.explain(True) の出力。
  2. 入力データのサイズと形式、およびすべての結合の両側のサイズ。
  3. クラスターの形状:エグゼキュータ数、コア数、メモリ。
  4. ジョブが新規作成かチューニングパスか - チューニングの場合は、コードに触れる前に実行計画から診断する。

ステップ2: 適切なセッションから始める

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()
)

Adaptive Query Execution (AQE) を有効にします。これにより、実行時にシャッフルパーティションが統合され、結合戦略が切り替わります。次に spark.sql.shuffle.partitions を意図的に設定します:シャッフルパーティションあたり100〜200 MBを目標とし、パーティション数 ≈ シャッフルデータサイズ ÷ 128 MB、かつ合計エグゼキュータコアの少なくとも2〜3倍にすることで、どのコアもアイドル状態になりません。

ステップ3: DataFrame API内に留まり、Pythonを避ける

DataFrame操作はCatalystとTungstenを通過するため、クエリ最適化とオフヒープメモリが利用できます。DataFrameのプリミティブが存在しない場合にのみRDDにフォールバックします。Python UDFは各行をPythonワーカーにシリアライズして返すため、コード生成を阻害します。優先順位:

  1. 組み込みの pyspark.sql.functions(例:F.regexp_extract、F.when)。
  2. Pythonが避けられない場合のPandas(ベクトル化)UDF。
  3. スカラーPython UDFは最後の手段としてのみ。
from pyspark.sql.functions import pandas_udf

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

ステップ4: サイズに基づいて結合戦略を選択する

  • 小さい方のテーブルがメモリに収まる場合はブロードキャストします。Sparkは spark.sql.autoBroadcastJoinThreshold(デフォルト10 MB)未満を自動ブロードキャストします。エグゼキュータメモリが許せば、最大数百MBのテーブルを明示的にブロードキャストします。実用的な上限は約1 GBと見なしてください - ブロードキャストはテーブルをすべてのエグゼキュータにコピーするため、誤判断するとジョブがOOMになります。
from pyspark.sql.functions import broadcast
result = large.join(broadcast(small), "key")
  • 結合前に列をフィルタリングおよび射影してシャッフルを減らします。削除されたすべての列と行は節約されたシャッフルバイトです。
  • 2つの大きなテーブル → ソートマージ結合を受け入れますが、最初にスキューを確認します(ステップ5)。

ステップ5: スキューを診断して修正する

スキューの症状:1つまたは2つのタスクを除いてステージが完了している。最大タスク期間が中央値の約3〜5倍を超えている。Spark UIで1つのシャッフル読み取りパーティションが他のパーティションよりもはるかに大きい。AQEのスキュージョイン処理は、パーティションが中央値の5倍を超え、かつ256 MBを超える場合(デフォルト)にパーティションを分割します - 実行計画で実際に発動したことを確認します。AQEが役に立たない場合(例:スキューした集約)、ホットキーにソルトを適用します。大きい側のキーにランダムなサフィックス0..Nを追加し、小さい側をすべてのNサフィックスに展開し、結合してからソルトを取り除きます。N ≈ スキュー係数(中央値の20倍のキーにはN=20)を選択します。

ステップ6: パーティショニングと出力レイアウトを制御する

  • repartition(n, col) はデータのバランスをとるためにフルシャッフルを実行します。ワイド書き込みの前に使用します。
  • coalesce(n) はシャッフルなしでパーティション数を減らします。小さな出力ファイルを避けるために使用します。
  • 出力ファイルのサイズは128 MB〜1 GBを目標にします。数千の小さなファイルはすべての下流リーダーに悪影響を及ぼします。
  • 出力はカーディナリティの低い列(日付、地域 - 数十から数百の値、IDは不可)でのみパーティション分割します:
df.write.partitionBy("dt").mode("overwrite").parquet("/data/out")

ステップ7: 再利用されるものだけをキャッシュする

DataFrameがDAG内で複数回使用される場合にのみキャッシュし、マテリアライズして、使用が終わったらアンペアします:

df.cache()
df.count()  # マテリアライズ
# ... dfを再利用 ...
df.unpersist()

一度しか使用しないDataFrameをキャッシュするとメモリを浪費し、重要なデータを追い出す可能性があります。

ステップ8: 実行計画で確認する

df.explain(True) を再実行し、意図した戦略が表示されていることを確認します(BroadcastHashJoin、プッシュダウンされたフィルター、削除された Exchange がないこと)。列形式(Parquet、ORC)を読み取り、述語プッシュダウンが機能するようにします。決して大きなデータを collect() してドライバに送らないでください。チェーンする際は、文字列の列参照よりも F.col 参照を優先します。

実例:悪い結合と良い結合

悪い例 - 2 TBのイベントテーブルと200 MBのディメンションを、全幅で、Python UDFで解析:

result = (events.join(dims, "store_id")          # ソートマージ:2 TBすべてをシャッフル
    .withColumn("region", parse_region_udf("meta"))  # 行単位のPython
    .filter(F.col("dt") == "2024-06-01"))            # 結合後にフィルター

実行計画は両側に Exchange(2 TBシャッフル)を示し、UDFがコード生成をブロックします。

良い例 - 最初にフィルターと射影を行い、ディメンションをブロードキャストし、組み込み関数を使用:

result = (events
    .filter(F.col("dt") == "2024-06-01")              # まず約30 GBに絞る
    .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)))

実行計画は BroadcastHashJoin を示し、大きな側の Exchange はありません:約30 GBがスキャンされ、大きなテーブルのシャッフルはゼロ、Pythonの境界もありません。

成果物

修正されたジョブコードと、次の内容を含むチューニングノートを作成します:各結合の結合戦略とそのサイズ根拠、シャッフルパーティション設定とその計算根拠、発見されたスキュー(最大対中央値タスク比率)と適用された修正、キャッシュ判断、出力ファイルサイズの期待値、およびチューニングパスの場合は修正前後の explain の差分。

やってはいけないこと

  • サイズを確認していないテーブルをブロードキャストしてはいけません。誤判断したブロードキャストはすべてのエグゼキュータを一度にOOMにします。
  • pyspark.sql.functions を確認せずにPython UDFを作成してはいけません。ほとんどの文字列、日付、条件ロジックには組み込み関数があります。
  • 大きなDataFrameで collect() または toPandas() を使用してはいけません。クラスターのデータを1つのドライバーに集約します。
  • カーディナリティの高い列で出力をパーティション分割してはいけません。何百万ものディレクトリにそれぞれ1行ずつ格納されることになります。
  • 遅いステージが1つのスキューしたタスクであるジョブにエグゼキュータを追加してはいけません。より多くのコアでも1つのパーティションを分割できません。
  • 反射的にキャッシュしてはいけません。下流で再利用されるDataFrameのみをキャッシュし、アンペアします。

品質基準

完了したジョブは、次のすべてを満たした場合にのみ合格とします:すべての結合がその戦略とサイズ根拠を明示していること。spark.sql.shuffle.partitions がデータサイズから導出されており、習慣的な値のままになっていないこと。Spark UIで、シャッフルステージのどのタスクも中央値の約3倍を超える期間になっていないこと(またはスキューが説明され修正されていること)。組み込み関数が存在する場所にスカラーPython UDFが残っていないこと。出力ファイルが128 MB〜1 GBの範囲にあること。そして最終的な explain が意図した実行計画を確認していること。

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.

関連スキル