clickhouse-autoresearch-campaign
Что он делает
Этот скилл проводит агента через структурированную работу по ускорению одного запроса к базе данных ClickHouse. Он нужен инженерам, которые хотят безопасно проверить много изменений запроса с записью результатов по ходу работы.
Когда использовать
- ✓Когда вы хотите ускорить один запрос ClickHouse через повторяющиеся измерения.
- ✓Когда вы хотите, чтобы каждый эксперимент с запросом хранился в отдельной git-ветке.
- ✓Когда вы хотите вести запись исходных замеров времени и проверок корректности изменений запроса.
Ссылка на скилл
https://github.com/PostHog/posthog/blob/master/tools/query-performance-ai/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/skills/clickhouse-autoresearch-campaign/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Запрос к нашему дашборду ClickHouse слишком медленный. Можешь провести кампанию по оптимизации в отдельной ветке и вести запись каждой попытки?”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Агент создает отдельную ветку и рабочее пространство, измеряет исходную точку и пробует разные идеи по одной. Он проверяет, что результаты остаются правильными, и отслеживает серии попыток, которые перестали давать улучшение.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
ClickHouse Autoresearch Campaign
This skill packages the orchestration for optimizing one ClickHouse query on one git branch.
Required reads
Before taking action, read orchestration.md (sibling of this file) completely. Treat it as the operating contract.
Preconditions
This skill assumes:
pi-autoresearchis installed and its tools are available- the current directory is a git repository
- you have a target query or enough context to identify one
- the operator will provide or help configure
.clickhouse-autoresearch/adapter.json
Branch rule
One campaign = one git branch.
If the current branch is not a dedicated campaign branch yet, create one before initializing the workspace.
Workspace rule
Use a single workspace at:
.clickhouse-autoresearch/
The branch is the campaign boundary. The workspace is just the artifact layout.
If autoresearch.config.json exists in the current working directory, read its workingDir field and use that path as the workspace instead of the default above. Automated orchestrators (for example PostHog's run_campaign.py) initialize the workspace at /tmp/autoresearch-campaign/ and write the config alongside it.
Pre-initialized workspace detection
Before doing anything in the Setup sequence, check whether the workspace has already been prepared by an external orchestrator. If the resolved workspace contains all of:
adapter.jsonbaseline/metrics.jsonquery/original.sql
…then the workspace is pre-initialized. In that case:
- Skip the entire Setup sequence (steps 1–6). Do not ask the operator for a target query, connection details, or anything else — the orchestrator has already supplied them.
- Jump directly to step 7 of the Setup sequence (read the baseline and seed the first lanes and hypotheses), then continue with steps 8–9 and the normal campaign loop.
- Operate headlessly: at no point prompt the operator for input. If a decision requires judgment, apply the skill's default guidance and record the choice in
state.json/autoresearch.md.
Only fall back to the interactive Setup sequence below when the workspace is empty or partially initialized.
Adapter capabilities (what you can and cannot run)
Campaign queries flow through the adapter configured in adapter.json. Every campaign script (ch_capture_baseline.py, ch_run_candidate.py, any ad-hoc probe) ultimately submits SQL through this adapter, and the adapter enforces what ClickHouse sees.
When adapter.json has type: "coordinator", your SQL is routed to whichever ClickHouse the host-side coordinator is pointed at — typically a read-only test cluster or a local dev ClickHouse. Either way the cluster runs SQL under a profile that pins readonly = 2, so writes (INSERT, ALTER, CREATE, OPTIMIZE, SYSTEM, TRUNCATE, DROP, ATTACH, DETACH) will fail with a ClickHouse error. Read GET /v1/info (or check autoresearch.md — the coordinator's prompt addendum is prepended there) before issuing any predicate that depends on a specific team_id: the prompt addendum tells you which team_id the target cluster has data for, and you must rewrite team_id predicates to match it. For experiments treat every read-only statement form as available:
SELECT …— arbitrary subqueries, CTEs, joinsWITH … SELECT …EXPLAIN …— every variant ClickHouse supports. Use them before proposing rewrites:EXPLAIN SELECT …(default: PLAN)EXPLAIN AST SELECT …EXPLAIN SYNTAX SELECT …EXPLAIN QUERY TREE SELECT …(post-analyzer logical tree; invaluable on modern ClickHouse)EXPLAIN PIPELINE SELECT …— processor-level pipeline, headers, expressionsEXPLAIN ESTIMATE SELECT …— per-part row/mark estimates before executionEXPLAIN PLAN indexes = 1, actions = 1, json = 1 SELECT …— primary-key and skip-index use, JSON for machine parsingEXPLAIN TABLE OVERRIDE …
SHOW …—SHOW CREATE TABLE events,SHOW COLUMNS FROM events,SHOW INDEX FROM events,SHOW SETTINGS ILIKE '%mark_cache%', etc.DESCRIBE/DESC …
Timeout: every submission is wrapped with SETTINGS max_execution_time = 60. Keep ad-hoc probes short. If the target query itself routinely exceeds 60s, use range narrowing (see Setup step 6) and only then start the campaign.
Cluster scoping: depends on the coordinator's target. The prompt addendum prepended to autoresearch.md tells you which team_id the target cluster has data for and ask
Частые вопросы
Нужна ли ему собственная git-ветка?
Да. Каждая кампания работает в одной выделенной git-ветке, и она задает границы работы.
Проверяет ли он, что результаты запроса остаются верными?
Да. Проверки корректности идут вместе с тестами времени, поэтому более быстрый запрос все равно должен возвращать верные ответы.
На какие инструменты он опирается?
На установленные инструменты pi-autoresearch и файл конфигурации для целевого адаптера.
Подробности
Оригинальное описание автора
Run a ClickHouse query optimization campaign on one git branch using pi-autoresearch, dynamic lanes and hypotheses, baseline result capture, correctness checks, and stagnation-aware lane/campaign review.
repo: PostHog/posthog
Популярность
- Звёзды на GitHub
- 41k
- Место в рейтинге
- #6984
- Лицензия
- —
- Обновлён
- 02.11.2026
Комментарии
- …
Другие скиллы из этого репозитория
depot-ci
41kПомогает агенту настроить и запускать workflow в Depot CI, альтернативе GitHub Actions, включая перенос существующих workflow и чтение логов запусков.
depot-container-builds
41kПомогает агенту собирать Docker-образы на удалённых сборщиках Depot, включая мультиплатформенные образы, отправку в реестры и исправление ошибок сборки.
depot-github-runners
41kПомогает агенту переносить задачи GitHub Actions на раннеры Depot: выбирать размер и метки раннера и устранять проблемы настройки.
editing-agents-md
41kПомогает агенту решить, нужно ли правило в файле AGENTS.md или CLAUDE.md, и записать его так, чтобы оно работало, не раздувая файл.
Похожие скиллы
api-connector-builder
280kАгент создаёт новые подключения к API по существующему шаблону. Используйте, когда нужна ещё одна интеграция без нового способа делать то же самое.
api-design
280kПомогает агенту проектировать REST API по лучшим практикам: как API общаются, как показываются ошибки и как организовать данные.
backend-patterns
280kПомогает агенту с архитектурными паттернами серверной части и оптимизацией баз данных. Полезен при создании и проверке серверного кода.