Logo de Optimize Spark Sql Plan

Optimize Spark Sql Plan

Organização
contrastdata
optimize-spark-sql-plan

Optimize Apache Spark SQL and DataFrame queries using the final Adaptive Query Execution plan and runtime statistics rather than source code alone. Use to reduce runtime, shuffle, spill, scan cost, skew, join amplification, Python UDF overhead, poor partitioning, or unnecessary work while preserving query semantics.

Visão geral

Publicado porcontrastdata
Repositóriospark-observability-skills
Nome da habilidadeoptimize-spark-sql-plan
Estrelas
54
Forks
13
Arquivos incluídos
1
LicençaApache-2.0
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    As habilidades de IA são escritas em Markdown simples, não em código específico de um provedor. Por isso, funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Arquivos incluídos: 1

    Scripts, templates e referências que o modelo pode ler enquanto trabalha. Os arquivos são somente para leitura e nunca são executados.

  • Código aberto

    Publicada por contrastdata no GitHub. Leia os arquivos da habilidade antes de instalá-la.

Instalação

Instale a habilidade de IA Optimize Spark Sql Plan no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL abaixo, que aponta para a pasta da habilidade, e confirme.
    https://github.com/contrastdata/spark-observability-skills/tree/main/skills/optimize-spark-sql-plan
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Adicionar habilidade → Via URL do GitHub. Depois, cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/contrastdata/spark-observability-skills.git /tmp/spark-observability-skills
mkdir -p .claude/skills
cp -r /tmp/spark-observability-skills/skills/optimize-spark-sql-plan .claude/skills/optimize-spark-sql-plan
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Optimize Spark Sql Plan em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Optimize Spark Sql Plan automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Optimize Spark Sql Plan não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Optimize a Spark SQL plan

Find the highest-impact improvement supported by the executed plan and its runtime metrics. Work from the final adaptive plan (isFinalPlan=true), not source code or the initial plan: AQE may already have broadcast, coalesced, or split what you were about to recommend.

Get the evidence

bash
export SPARK_HISTORY_URL="https://history.example.com"
python3 scripts/spark_history_api.py sql-list --app-id <application-id>
python3 scripts/spark_history_api.py sql --app-id <application-id> --execution-id <execution-id> > /tmp/spark-sql.json

Run from this skill directory. If SPARK_HISTORY_URL is unset, find the server before asking the user: try http://localhost:18080, a running application's UI on http://localhost:4040, and the history-server or eventLog settings in the local Spark config; ask only when nothing responds. Authentication comes from SPARK_HISTORY_AUTHORIZATION, SPARK_HISTORY_COOKIE, or SPARK_HISTORY_HEADERS_JSON; never ask for credentials in chat and never disable TLS verification (--ca-file for a private CA).

The snapshot's layout: sqlExecution.planDescription is the executed plan text, sqlExecution.nodes[].metrics carry per-operator counters with edges giving parent-child links, jobs[].stageIds tie the execution to stages, longestStages[] holds each stage with its taskSummary quantiles (arrays align with quantiles; middle is median, last is max), and environment.sparkProperties is the effective configuration. For data beyond the profile, other subcommands (slow, failure, applications) and the raw $SPARK_HISTORY_URL/api/v1 endpoints (/stages/{stage}/{attempt}/taskSummary, /allexecutors, /environment) are available with the same auth. If the API omits the plan, recover it from the driver log or generate explain(mode="formatted") from the deployed code yourself. Get the deployed query code too: the plan tells you what ran, the code tells you what was intended.

Highest-impact opportunities, in order, and how to check each

  1. Cardinality blowup. Join output far exceeding both inputs is usually an unintended many-to-many:

    bash
    jq '.sqlExecution.nodes[] | select(.nodeName | test("Join")) | {nodeId, nodeName, rows: [.metrics[] | select(.name | test("output rows"))]}' /tmp/spark-sql.json

    Compare each join's rows against its children's (follow edges). Fix keys or deduplicate first; it dominates every downstream metric.

  2. Pruning. Scans reading far more than the query uses:

    bash
    jq '.sqlExecution.nodes[] | select(.nodeName | startswith("Scan")) | {nodeName, metrics}' /tmp/spark-sql.json

    Compare files and bytes read against rows output, and check the pushed/partition filters on the scan in planDescription.

  3. Broadcast. A SortMergeJoin whose smaller side is observed (not estimated) to be broadcastable:

    bash
    jq -r '.sqlExecution.planDescription' /tmp/spark-sql.json | grep -n 'SortMergeJoin\|BroadcastHashJoin'

    Read the smaller side's "data size" metric from its node, and spark.sql.autoBroadcastJoinThreshold from environment.sparkProperties. Stale statistics are the usual reason AQE missed it; confirm executor memory headroom before recommending.

  4. Unnecessary shuffles. Exchanges whose partitioning an upstream operation already satisfies, or repartitions the query does not need:

    bash
    jq -r '.sqlExecution.planDescription' /tmp/spark-sql.json | grep -n 'Exchange'

    Every exchange should map to a semantic requirement; look for back-to-back exchange/sort pairs and matching partitioning expressions above and below.

  5. Skewed joins and aggregations. One partition dominating a join or aggregate stage:

    bash
    jq '{jobStages: [.jobs[] | {jobId, stageIds}], stages: [.longestStages[] | {id: .stage.stageId, run: .taskSummary.executorRunTime, shuffleRead: .taskSummary.shuffleReadMetrics.readBytes}]}' /tmp/spark-sql.json

    Max many times median on the join's stage is skew; check planDescription for skewed=true and, if AQE did not handle it, why. Re-run with a higher --stage-limit if the stage is missing.

  6. Partition count. Uniformly oversized shuffle partitions with spill: grep -n 'AQEShuffleRead' <(jq -r '.sqlExecution.planDescription' /tmp/spark-sql.json) for coalescing, stage numTasks from longestStages[].stage, and spill from the check below. Raise spark.sql.shuffle.partitions or AQE targets before adding explicit repartitions, which can insert redundant exchanges.

  7. Excess spill in stateful operators. Aggregates, sorts, and windows spilling:

    bash
    jq '.sqlExecution.nodes[] | select(.nodeName | test("Aggregate|Sort|Window")) | {nodeName, spill: [.metrics[] | select(.name | test("spill"))]}' /tmp/spark-sql.json

    Reduce state (partial aggregation, narrower rows, fewer window columns) before adding memory.

  8. Python UDF boundaries. Serialization often costs more than the function itself:

    bash
    jq '.sqlExecution.nodes[] | select(.nodeName | test("Python")) | {nodeName, metrics}' /tmp/spark-sql.json

    Weigh node time against rows processed; a native expression removes the boundary.

  9. Caching. jq -r '.sqlExecution.planDescription' /tmp/spark-sql.json | grep -c 'InMemoryTableScan': a cached result scanned once wastes memory, and a subtree recomputed under several plan branches wants a cache.

The commands above are starting points, not limits: compose your own jq, call the REST API directly, or pull logs, code, and platform state when a question needs it. Rule each candidate in or out with evidence, and when a signal is suggestive but not conclusive, go a level deeper (more task samples, the exact log lines, the executed plan) until you are confident it is or is not the cause. Do not settle for the first plausible explanation.

An Exchange is not automatically waste, a sort-merge join is not automatically wrong, a broadcast is not automatically safe, and a Python UDF is not automatically material: tie every recommendation to the node's runtime metrics, and check whether Catalyst or AQE already applied it.

Changes must preserve semantics: row counts, join cardinality, null behavior, duplicates, and ordering assumptions. Changing partitioning can alter low-order bits of floating-point aggregations.

Report

State the highest-impact change with its plan node, runtime evidence, and expected effect; why Spark did not already do it; correctness risks; and any remaining smaller findings. Do not apply hints, code, or configuration changes to production without approval.

Arquivos incluídos

O modelo lê esses arquivos sob demanda enquanto a habilidade está carregada. Eles são disponibilizados para leitura e nunca são executados.

Perguntas frequentes

O que a habilidade de IA Optimize Spark Sql Plan faz?

Optimize Apache Spark SQL and DataFrame queries using the final Adaptive Query Execution plan and runtime statistics rather than source code alone. Use to reduce runtime, shuffle, spill, scan cost, skew, join amplification, Python UDF overhead, poor partitioning, or unnecessary work while preserving query semantics.

Por que usar Optimize Spark Sql Plan no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. A habilidade Optimize Spark Sql Plan é escrita em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. No TypingMind, você usa suas próprias chaves de API e paga diretamente aos provedores, em vez de pagar uma assinatura por licença de usuário. Suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Optimize Spark Sql Plan no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/contrastdata/spark-observability-skills/tree/main/skills/optimize-spark-sql-plan. O TypingMind lê o arquivo SKILL.md, reúne os arquivos da habilidade e a instala para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Optimize Spark Sql Plan?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Optimize Spark Sql Plan?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Optimize Spark Sql Plan com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Optimize Spark Sql Plan é gratuita?

Sim. A habilidade é publicada no GitHub por contrastdata sob a licença Apache-2.0. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, templates ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas que ele pode acionar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA dá ao modelo o conhecimento e as orientações de que ele precisa: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver lista completa

Crie seu próprio espaço de trabalho com IA agora

Inscreva-se na nossa newsletter para receber avisos sobre novos recursos e futuros sorteios 👇