Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

tidb-query-tuning

БесплатноБез исполняемых скриптовНе проверен

Diagnose and optimize slow TiDB queries using optimizer hints, session variables, join strategy selection, subquery optimization, and index tuning. Use when a…

pingcapот pingcap★ 27 звёзд на GitHub

Об этом скилле

TiDB Query Tuning

Use this skill to diagnose and resolve TiDB query performance issues. It follows a rigorous workflow from symptom identification to verified solution.


Workflow

  1. Capture the current plan & clues:

    • Run EXPLAIN ANALYZE <query> to get actual execution stats.
    • Compare estRows vs actRows — large divergence means stale or missing statistics.
    • Note the most expensive operators (wall time, memory, rows processed).
    • Use PLAN REPLAYER: Run PLAN REPLAYER DUMP EXPLAIN [ANALYZE] <query>; to export comprehensive on-site information (version, config, stats, plan) to a ZIP file.
    • Use Debug API: Use TiDB HTTP API (port 10080) to pull runtime info: /debug/pprof, /stats/dump/{db}/{table}, or /schema/{db}/{table}.
    • Check Bindings: Run SHOW GLOBAL BINDINGS; to see if existing plan baselines are affecting the query.
  2. Check statistics health:

    • SHOW STATS_HEALTHY WHERE Db_name = '<db>' AND Table_name = '<table>';
    • If health < 80 or actRows diverges significantly from estRows, run ANALYZE TABLE <table>; (or with ALL COLUMNS if @@tidb_analyze_column_options is not ALL) and re-check the plan.
    • For specific indexes: ANALYZE TABLE <table> INDEX <index_name>;
  3. Identify the bottleneck pattern:

    • Bad join order or strategy → see references/join-strategies.md
    • IndexJoin/IndexHashJoin picked the wrong probe index → see references/join-strategies.md, references/index-selection.md, and references/slow-plan-optimization/cases/use-correct-probe-index-for-index-join.md
    • Subquery not handled well → see references/subquery-optimization.md
    • Wrong or missing index → see references/index-selection.md
    • Optimizer choosing a suboptimal plan despite good stats → see references/optimizer-hints.md and references/session-variables.md
    • Stats are stale or auto analyze cannot keep up → see references/stats-health-and-auto-analyze.md
    • Plans change after restart or sync stats loading times out → see references/stats-loading-and-startup.md
    • Need to tune analyze version, column coverage, or memory-heavy stats collection → see references/stats-version-and-analyze-configuration.md
    • Need a matching field incident, workaround, or fixed-version precedent → search references/optimizer-oncall-experiences-redacted/
    • Need recent customer issue precedents with linked PRs and merge timestamps → search references/tidb-customer-planner-issues/
  4. Reproduce & Investigate locally:

    • Local Reproduction: Use tiup playground and PLAN REPLAYER LOAD to reproduce the issue locally. See references/plan-replayer-testing.md.
    • Test Versions: Verify the fix in newer stable versions or nightly.
    • Deep Code Analysis: If the cause is still unclear, clone pingcap/tidb and analyze the source code. Read AGENTS.md and .agents/skills in the TiDB repo first.
  5. Apply the fix:

    • Prefer the least invasive change: refresh stats → add index → SQL Binding → hint → session variable.
    • SQL Binding: Fix plans without code changes: CREATE GLOBAL BINDING FOR <stmt> USING <hinted_stmt>;.
    • Validate index-based join probe paths: When the plan uses IndexJoin or IndexHashJoin, inspect the probe-side access object, pushed conditions, and whether the path is covering. Do not assume the chosen probe index is correct just because the join type is index-based. If another existing index better matches join keys, selective filters, or covering needs, compare it with USE_INDEX/IGNORE_INDEX and stabilize the winner with a hint or SQL binding.
    • Binding cleanup safety: TiDB currently has no batch-delete API for global bindings. Do not run DELETE on mysql.bind_info directly. Use DROP GLOBAL BINDING ... for each target binding instead.
    • If direct delete was already executed: ADMIN RELOAD BINDINGS may still leave stale entries in the in-memory binding cache. In this case, restart the TiDB server to fully clear and rebuild binding cache state.
    • See references/optimizer-oncall-experiences-redacted/direct-delete-bind-info-leaves-stale-binding-cache.md for a full reproduction and recovery checklist.
    • Hints & Variables: Use hints when the fix is query-specific; use session variables when it applies to a workload pattern.
    • Bug Report: If it's a confirmed bug, follow the workflow in references/bug-report.md. Anonymize all sensitive data before reporting.
  6. Verify the improvement:

    • Re-run EXPLAIN ANALYZE with the fix applied.
    • Confirm actRows and execution time improved.
    • If the fix is a hint, document it in a SQL comment so future readers understand why.

High CPU Workflow

When the customer reports high TiDB CPU usage, use the following workflow before jumping to optimizer conclusions:

  1. Treat clinic-api as the default entry point. If `
Полный SKILL.md на GitHub

Установить tidb-query-tuning в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

AGENTS.mdreferences/bug-report.mdreferences/clues.mdreferences/explain-patterns.mdreferences/index-selection.mdreferences/join-strategies.mdreferences/optimizer-cost-factors.mdreferences/optimizer-fix-controls.mdreferences/optimizer-hints.mdreferences/optimizer-oncall-experiences-redacted/analyze-jobs-run-too-long-or-too-hot.mdreferences/optimizer-oncall-experiences-redacted/binding-cache-quota-blocks-baselines.mdreferences/optimizer-oncall-experiences-redacted/binding-digest-truncated-by-stmt-summary-limit.mdreferences/optimizer-oncall-experiences-redacted/bindings-for-single-and-multi-value-in-lists-do-not-match.mdreferences/optimizer-oncall-experiences-redacted/cost-model-v1-picks-the-wrong-engine.mdreferences/optimizer-oncall-experiences-redacted/ddl-owner-memory-leak-from-internal-session-pool.mdreferences/optimizer-oncall-experiences-redacted/direct-delete-bind-info-leaves-stale-binding-cache.mdreferences/optimizer-oncall-experiences-redacted/empty-range-seeks-cause-tikv-cpu-spikes.mdreferences/optimizer-oncall-experiences-redacted/force-init-stats-leaves-pseudo-stats-after-restart.mdreferences/optimizer-oncall-experiences-redacted/gc-stw-causes-simple-query-latency-jitter.mdreferences/optimizer-oncall-experiences-redacted/global-bindings-override-hints.mdreferences/optimizer-oncall-experiences-redacted/huge-in-list-falls-back-to-index-full-scan.mdreferences/optimizer-oncall-experiences-redacted/new-tidb-instance-starts-without-stats.mdreferences/optimizer-oncall-experiences-redacted/order-by-limit-picks-the-ordering-index.mdreferences/optimizer-oncall-experiences-redacted/parallel-join-query-oom-on-tidb.mdreferences/optimizer-oncall-experiences-redacted/partial/analyze-retry-stuck-when-global-time-zone-differs.mdreferences/optimizer-oncall-experiences-redacted/partial/disable-outer-join-reorder-after-upgrade.mdreferences/optimizer-oncall-experiences-redacted/partial/dp-join-reorder-can-trigger-cant-find-column.mdreferences/optimizer-oncall-experiences-redacted/partial/enable-advanced-join-hint-only-in-query-scope.mdreferences/optimizer-oncall-experiences-redacted/partial/exchange-partition-can-duplicate-rowid-and-skip-updates.mdreferences/optimizer-oncall-experiences-redacted/partial/force-engine-with-hints-or-spm.mdreferences/optimizer-oncall-experiences-redacted/partial/manual-analyze-as-emergency-plan-stabilizer.mdreferences/optimizer-oncall-experiences-redacted/partial/point-get-plan-cache-may-return-zero-or-one-row.mdreferences/optimizer-oncall-experiences-redacted/partial/rc-plus-forced-mpp-on-batch-point-get-can-error.mdreferences/optimizer-oncall-experiences-redacted/partial/read-from-storage-with-virtual-column-cannot-build-plan.mdreferences/optimizer-oncall-experiences-redacted/partial/reduce-analyze-concurrency-or-sample-rate.mdreferences/optimizer-oncall-experiences-redacted/partial/regexp-or-rlike-on-information-schema-can-be-wrong.mdreferences/optimizer-oncall-experiences-redacted/partial/switch-cost-model-v2-to-correct-engine-choice.mdreferences/optimizer-oncall-experiences-redacted/plan-cache-memory-growth-from-varying-parameter-shapes.mdreferences/optimizer-oncall-experiences-redacted/plan-cache-skipped-by-short-circuit-predicates.mdreferences/optimizer-oncall-experiences-redacted/stale-stats-after-bulk-data-change.md

FAQ

Что делает скилл tidb-query-tuning?

Diagnose and optimize slow TiDB queries using optimizer hints, session variables, join strategy selection, subquery optimization, and index tuning. Use when a query is slow, produces a bad plan, or needs performance guidance on TiDB.

Как установить скилл tidb-query-tuning?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл tidb-query-tuning запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить tidb-query-tuning с