Metadata-Version: 2.4
Name: lakehouse-doctor
Version: 1.0.0
Summary: Offline schema-aware SQL auditor, column impact analyzer, Query Profile analyzer, and stdio MCP server for Apache Doris & StarRocks (with Paimon DDL checks).
Author-email: tolgerx <tlge@mail.ustc.edu.cn>
License: MIT
Project-URL: Homepage, https://github.com/tolgerx/lakehouse-doctor
Project-URL: Repository, https://github.com/tolgerx/lakehouse-doctor
Project-URL: Issues, https://github.com/tolgerx/lakehouse-doctor/issues
Keywords: apache-doris,starrocks,apache-paimon,lakehouse,sql-linter,data-lineage,sqlglot
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: sqlglot<31.0,>=30.0
Requires-Dist: rich>=13.7
Requires-Dist: tomli>=2.0; python_version < "3.11"
Provides-Extra: online
Requires-Dist: pymysql>=1.1; extra == "online"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Dynamic: license-file

# Lakehouse Doctor (`lh-doctor`)

[![CI](https://github.com/tolgerx/lakehouse-doctor/actions/workflows/ci.yml/badge.svg)](https://github.com/tolgerx/lakehouse-doctor/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/lakehouse-doctor.svg)](https://pypi.org/project/lakehouse-doctor/)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)

**简体中文** | [English](README_EN.md)

**面向 Apache Doris 与 StarRocks 的离线湖仓诊断工具，兼顾 Paimon DDL 检查，提供 CLI 与只读 stdio MCP Server。**

无需连接生产集群，直接在本地或 CI 中完成 Schema-Aware SQL 静态审计、列级血缘影响分析与 Query Profile 文本排障。

![Lakehouse Doctor Demo](assets/demo-overview.svg)

---

## 快速开始

### 命令行安装

```bash
pip install lakehouse-doctor

# 可选：启用只读 FE 元数据回填与 EXPLAIN 校验（--dsn / --explain）
pip install "lakehouse-doctor[online]"
```

```bash
# 1. 离线诊断 Query Profile 文本（支持对比优化前后的两份 Profile）
lh-doctor profile slow_profile.txt
lh-doctor profile slow_profile.txt --format ai-json
lh-doctor profile before.txt --diff after.txt

# 2. 对 SQL 文件或目录运行 Schema-Aware 静态审计
lh-doctor audit ./sql --fail-on none

# 3. 存量仓库建立基线后，仅审计增量改动及其跨层下游文件并导出 SARIF
lh-doctor audit ./sql --write-baseline .lh-baseline.json
lh-doctor audit ./sql --since origin/main --baseline .lh-baseline.json --format json --sarif-out lh-audit.sarif
```

### 接入 Coding Agent（stdio MCP + Skills）

将 `lh-doctor mcp`（或 `uvx lakehouse-doctor mcp`）写入支持 stdio MCP 的编程助手配置（示例见 [`examples/mcp_config.json`](examples/mcp_config.json)）：

```json
{
  "mcpServers": {
    "lakehouse-doctor": {
      "command": "uvx",
      "args": ["lakehouse-doctor", "mcp"]
    }
  }
}
```

仓库同时提供 4 套 [`skills/`](skills) 与 [`.claude/commands/`](.claude/commands)，对应内置的只读工具（`audit_sql`、`inspect_catalog`、`trace_impact`、`analyze_profile`、`compare_profiles`、`generate_dqc`）与 `rules/catalog` 资源。

### 运行内置示例

```bash
git clone https://github.com/tolgerx/lakehouse-doctor.git
cd lakehouse-doctor

lh-doctor audit examples/ecommerce_lakehouse --fail-on none
lh-doctor impact examples/ecommerce_lakehouse --column ods_orders.pay_amount
lh-doctor lineage examples/ecommerce_lakehouse --format html --output lineage.html
lh-doctor profile examples/profiles/doris_skewed_broadcast_join.txt
lh-doctor profile examples/profiles/doris_skewed_broadcast_join.txt --diff examples/profiles/doris_skewed_broadcast_join_tuned.txt
```

---

## 核心功能

### 1. Schema-Aware 离线审计与表目录（`audit` / `catalog`）

- **离线元数据目录**：扫描项目内 `CREATE TABLE`、CTAS、`ALTER TABLE` 以及 `USE CATALOG` / `USE` / `SWITCH` 会话上下文构建内存表目录；若表定义不在 Git 仓库中，可传入只读测试库 `--dsn` 自动回填缺失表结构。
- **规则检测与 Jinja 多分支展开**：覆盖 19 条语法、建模与查询规则（`LH001`、`LH101`–`LH106`、`LH201`–`LH212`），展开 Jinja 条件分支（`{% if / elif / else %}`）并分别审计，同时处理 `${var}`、`#{var}`、`$[...]` 与 `{{ ref(...) }}` 常见调度占位符。
- **覆盖率报告（`coverage`）**：审计结果显式返回 `complete`、缺失表、歧义表、重复 DDL 冲突（`schema_conflicts`）、语法降级计数、行内豁免计数及未能静态展开的模板块（`for` / `macro` / 超过 16 组合）；默认输出建议结果，传入 `--strict-coverage` 时只要 `coverage.complete` 为 `false` 即返回非零退出码。
- **增量重审与基线过滤**：`--since` 与 `--changed-files` 在重建全仓表目录的基础上，仅对变更文件及其受 DDL 影响的下游文件输出诊断；`--baseline` 按语句上下文指纹过滤存量已确认项。

### 2. Query Profile 离线诊断与 Diff（`profile`）

- 直接解析 Doris（2.x/3.x/4.x）或 StarRocks 3.x 导出的 Profile 文本，识别算子数据倾斜（`LP001`）、耗时瓶颈（`LP002`）、大表低过滤率（`LP003`）、`BROADCAST` Join 内存膨胀（`LP004`）、峰值内存与磁盘 Spill（`LP005`）、Shuffle 流量（`LP006`）、Pipeline 等待（`LP007`）、Hash Join Build/Probe 颠倒（`LP008`）以及低效预聚合（`LP009`）。
- `--diff` 对比优化前后的两份 Profile；若两侧引擎不同或无重叠算子，自动置 `comparable = false` 并清空不可靠的对比指标。
- `--format ai-json` 按字符预算自动裁剪冗余字段，方便在 Agent 上下文中消费长 Profile。

### 3. 列级血缘与影响分析（`lineage` / `impact`）

- 追踪多文件间的表级依赖、视图透传与 `DIRECT` / `DERIVED` / `FILTER` 列级边，支持向上游溯源（`--upstream`）或向下游评估删改列的影响范围。
- 输出支持终端文本、JSON、Mermaid 及单文件离线交互式 HTML；遇到分支列数不一致的 `UNION`、列数不匹配的 `INSERT`、分歧的条件 DDL 或缺失源表的 `SELECT *` 时跳过不可靠列边并在 `warnings` 中明确标出。

### 4. 单表 DQC SQL 模板（`dqc`）

- 按已解析的表结构、主键与分区字段生成单表基础校验 SQL（分区行数鲜度、主键重复、`NOT NULL` 与金额/数量非负校验），作为后续接入质量平台的起步模板。

---

## 输出示例

### `lh-doctor audit examples/ecommerce_lakehouse --fail-on none`

```text
Lakehouse Doctor Audit  (files: 8, catalog tables: 5)
Summary: 3 CRITICAL | 9 WARNING | 1 INFO
Coverage: clean=8, normalized=0, parse_errors=0, missing_tables=0, ambiguous=0, suppressed=0, indeterminate=0

[CRITICAL] LH203 dml/01_dwd_load_order_detail.sql:13 - Implicit type cast in JOIN/WHERE comparison
  SQL:  ON o.user_id = u.id
  Why:  Implicit cast in `o.user_id = u.id`: `ods_orders.user_id` (VARCHAR(64)) vs `ods_users.id` (BIGINT).
  Fix:  Align column types in DDL or explicitly `CAST(o.user_id AS BIGINT)` before joining.

[CRITICAL] LH201 dml/01_dwd_load_order_detail.sql:15 - Partition pruning disabled by function wrap
  SQL:  WHERE DATE_FORMAT(o.dt, '%Y-%m') = '2026-11'
  Why:  Partition column `o.dt` is wrapped in `TIME_TO_STR(CAST(o.dt AS TIMESTAMP), '%Y-%m')`, disabling partition pruning.
  Fix:  Rewrite using a half-open range predicate directly on `o.dt` (e.g. `o.dt >= '2026-11-01' AND o.dt < '2026-12-01'`).

[CRITICAL] LH202 dml/03_ads_gmv_report.sql:4 - Missing partition filter on partitioned table
  SQL:  SELECT * FROM dws_user_order_1d
  Why:  Partitioned table `dws_user_order_1d` (partitioned by `dt`) is scanned without a partition predicate.
  Fix:  Add a filter on `dt` in `WHERE` (or `JOIN ... ON` for outer-joined tables).
```

### `lh-doctor impact examples/ecommerce_lakehouse --column ods_orders.pay_amount`

```text
Impact Analysis (downstream): ods_orders.pay_amount -> 3 affected target(s)

  [Hop 1 | DWD] dwd_order_detail.pay_amount [DIRECT]
    Path: ods_orders.pay_amount -> dwd_order_detail.pay_amount
  [Hop 2 | DWS] dws_user_order_1d.total_gmv [DERIVED]
    Path: ods_orders.pay_amount -> dwd_order_detail.pay_amount -> dws_user_order_1d.total_gmv
  [Hop 3 | ADS] ads_gmv_dashboard.total_gmv [DERIVED]
    Path: ods_orders.pay_amount -> dwd_order_detail.pay_amount -> dws_user_order_1d.total_gmv -> ads_gmv_dashboard.total_gmv
```

### `lh-doctor profile examples/profiles/doris_skewed_broadcast_join.txt`

```text
Lakehouse Doctor Query Profile  (engine: DORIS, total: 14.82s, operators: 5, findings: 6)
Query ID: 9f4c2b8a-7e11-4d3a-9c52-88a1e72b1104

[CRITICAL] LP001 Fragment 1 / HASH_JOIN_OPERATOR (id=4) - Severe instance data skew
  Why: Operator `HASH_JOIN_OPERATOR (id=4)` exhibits 7.9x time skew (max=9820ms vs avg=1240ms) and 8.7x row skew.
[CRITICAL] LP002 Fragment 1 / HASH_JOIN_OPERATOR (id=4) - Dominant execution bottleneck operator
  Why: Operator `HASH_JOIN_OPERATOR (id=4)` accounts for 64.8% of operator max time (max=9820ms).
[CRITICAL] LP004 Fragment 1 / HASH_JOIN_OPERATOR (id=4) - Heavy BROADCAST join memory/fan-out risk
  Why: BROADCAST join `HASH_JOIN_OPERATOR (id=4)` reached 2.85 GB peak memory and processed 84.5M probe/read rows.
```

---

## 规则清单

| 规则编号 | 级别 | 范围 | 说明 |
| :--- | :--- | :--- | :--- |
| `LH001` | `CRITICAL` | 语法 | SQL 语法解析失败、未知列类型或无法识别的语句结构 |
| `LH101` | `WARNING` | DDL (Doris/SR) | `UNIQUE KEY` 表未开启 `enable_unique_key_merge_on_write = "true"` |
| `LH102` | `WARNING` | DDL (Doris/SR) | `BUCKETS > 64` 或非维表使用 `BUCKETS 1` |
| `LH103` | `WARNING` | DDL | 分层表（`ods_`/`dwd_`/`dws_`/`ads_`）缺失分区定义 |
| `LH104` | `WARNING` | DDL (Paimon) | 缺失 `changelog-producer` 或 `snapshot.time-retained` / `snapshot.num-retained.max` |
| `LH105` | `INFO` | DDL | 缺失表注释或超过 50% 字段缺失 `COMMENT` |
| `LH106` | `WARNING` | DDL (Doris/SR) | `DISTRIBUTED BY HASH(...)` 仅使用分区/日期/低基数列 |
| `LH201` | `CRITICAL` | DML | `WHERE` / `JOIN ON` 中对分区字段套用函数或算术运算 |
| `LH202` | `CRITICAL` | DML | 扫描已注册分区表时未包含任何分区裁剪谓词 |
| `LH203` | `CRITICAL` | DML | `WHERE` / `JOIN ON` / `HAVING` / `IN` / `BETWEEN` 中的列或字面量类型不兼容 |
| `LH204` | `WARNING` | DML | ETL 查询中使用 `SELECT *`（不含 `COUNT(*)`） |
| `LH205` | `WARNING` | DML | `INSERT INTO` / `INSERT OVERWRITE` 未显式指定目标列名 |
| `LH206` | `CRITICAL` | DML | 无约束 `CROSS JOIN`、缺失 `ON`/`USING` 或 `ON 1 = 1` |
| `LH207` | `WARNING` | DML | 顶层 `ORDER BY` 未配合 `LIMIT` |
| `LH208` | `WARNING` | DML | 单条 `SELECT` 中包含多个 `COUNT(DISTINCT ...)` |
| `LH209` | `INFO` | DML | 前导通配符 `LIKE '%...'` |
| `LH210` | `CRITICAL` | DML | 引用了表目录中不存在的列名 |
| `LH211` | `CRITICAL`/`WARNING` | DML | `INSERT` 目标列缺失、`SELECT`/`UNION` 列数不匹配、按位类型冲突或数值精度收缩 |
| `LH212` | `WARNING` | DML | 对分区表执行 `INSERT OVERWRITE` 但未指定 `PARTITION (...)` |
| `LP001` | `CRITICAL`/`WARNING` | Profile | 实例间时间或行数倾斜度 `>= 3x` |
| `LP002` | `CRITICAL`/`WARNING` | Profile | 主导耗时瓶颈算子（耗时占比 `>= 40%` 或 `>= 5s`） |
| `LP003` | `WARNING` | Profile | 大表 Scan 过滤保留率过低（`< 20%` 且读取 `>= 10M` 行） |
| `LP004` | `CRITICAL`/`WARNING` | Profile | `BROADCAST` Join 内存膨胀或探测行数过高 |
| `LP005` | `CRITICAL`/`WARNING` | Profile | 算子峰值内存过高（`>= 1.5 GB`）或发生磁盘 Spill |
| `LP006` | `WARNING` | Profile | 网络 Shuffle / Exchange 流量或耗时过高 |
| `LP007` | `CRITICAL`/`WARNING` | Profile | Pipeline 依赖或 Runtime Filter 等待阻塞 |
| `LP008` | `CRITICAL`/`WARNING` | Profile | Hash Join Build/Probe 大小表颠倒 |
| `LP009` | `CRITICAL`/`WARNING` | Profile | 预聚合裁剪率过低（`AGG` 输入 `>= 1M` 行且输出保留率 `>= 80%`） |
| `LE001` | `CRITICAL` | 在线 EXPLAIN | 启用 `--dsn --explain` 时未通过 FE 只读 `EXPLAIN` 优化器校验 |

---

## 配置与集成

- **配置文件**：运行 `lh-doctor init` 生成 `.lh-doctor.toml`（参考 [`.lh-doctor.toml.example`](examples/.lh-doctor.toml.example)），可配置方言、规则开关、级别覆盖、分桶阈值及排除路径。
- **行内豁免**：使用 `-- lh-doctor: disable=LH203 -- reason: <说明>`、`-- lh-doctor: disable-next-line=...`、`-- lh-doctor: disable-file=...` 或 `-- noqa`。
- **GitHub Actions 模板**：参考 [`.github/workflows/sql-guard-template.yml`](.github/workflows/sql-guard-template.yml) 在 PR 中运行增量审计、更新评论并上传 SARIF。

## 适用边界

- **定位**：离线静态 SQL 审计与 Profile 初诊工具，适合本地开发自查、Coding Agent 取证与 PR 建议评论；严格门禁需按需开启 `--strict-coverage` 并确保仓库/测试库覆盖完整表目录。
- **缓存与增量机制**：解析缓存位于单次/MCP 进程内存中，无磁盘持久化缓存；`--since` / `--changed-files` 每次执行仍会扫描项目 DDL 构建完整目录，再限定只审变更文件与下游关联文件。
- **Paimon DDL 与在线校验**：Paimon DDL 通过 Spark/Hive 方言回退解析表结构属性，不做 Flink Watermark 或物理执行计划校验；如需要完整优化器校验，配合只读 FE `--dsn --explain` 使用（审计报告 `coverage.online_explain` 会记录成功计划与未渲染跳过项）。

---

## 开源协议

[MIT](LICENSE)
