# https://github.com/apache/hamilton 项目说明书

生成时间：2026-06-24 21:43:59 UTC

## 目录

- [核心驱动引擎与 DAG 模型](#page-1)
- [函数修饰器与 DAG 定义](#page-2)
- [生命周期钩子、缓存与并行执行](#page-3)
- [Hamilton UI、SDK、插件生态与开发工具](#page-4)

<a id='page-1'></a>

## 核心驱动引擎与 DAG 模型

### 相关页面

相关主题：[函数修饰器与 DAG 定义](#page-2), [生命周期钩子、缓存与并行执行](#page-3)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [hamilton/driver.py](https://github.com/apache/hamilton/blob/main/hamilton/driver.py)
- [hamilton/async_driver.py](https://github.com/apache/hamilton/blob/main/hamilton/async_driver.py)
- [hamilton/graph.py](https://github.com/apache/hamilton/blob/main/hamilton/graph.py)
- [hamilton/node.py](https://github.com/apache/hamilton/blob/main/hamilton/node.py)
- [hamilton/base.py](https://github.com/apache/hamilton/blob/main/hamilton/base.py)
- [hamilton/graph_types.py](https://github.com/apache/hamilton/blob/main/hamilton/graph_types.py)
- [ui/sdk/src/hamilton_sdk/api/clients.py](https://github.com/apache/hamilton/blob/main/ui/sdk/src/hamilton_sdk/api/clients.py)
- [ui/backend/server/trackingserver_template/models.py](https://github.com/apache/hamilton/blob/main/ui/backend/server/trackingserver_template/models.py)
- [ui/backend/server/trackingserver_template/migrations_sqlite/0001_initial.py](https://github.com/apache/hamilton/blob/main/ui/backend/server/trackingserver_template/migrations_sqlite/0001_initial.py)
- [examples/lineage/README.md](https://github.com/apache/hamilton/blob/main/examples/lineage/README.md)
- [README.md](https://github.com/apache/hamilton/blob/main/README.md)
</details>

# 核心驱动引擎与 DAG 模型

## 概览

Apache Hamilton 的核心驱动引擎（`Driver`）是整个框架的中枢。它以 Python 函数为基本单元构建有向无环图（Directed Acyclic Graph, DAG），通过函数签名自动推导节点依赖关系，并将声明式的数据流定义转化为可执行的计算图。`Driver` 负责解析模块、构建图、按依赖顺序执行节点、收集结果，并对外暴露血统（lineage）查询、可视化与适配器（Adapter）扩展点。

DAG 模型则描述了从单个 `Node` 到整个计算图的层级结构。`Driver` 在执行前会先把模块中的函数编译为节点集合，再依据参数名映射依赖边，最终形成一张可追溯、可测试、可静态分析的数据流图。这种"以函数为节点、以参数名为边"的建模方式，让数据 pipeline 具备了软件工程意义上的模块化与可读性。`资料来源：[README.md:1-50]()`， `资料来源：[examples/lineage/README.md:1-40]()`

## DAG 节点与图模型

每个 Python 函数在 Apache Hamilton 中都被视作 DAG 中的一个 `Node`。节点携带类型、依赖列表、输出类型、文档字符串与 `tags` 等元数据，并可附加 `@check_output` 之类的校验装饰器对输出做静态检查。`Node` 之间的依赖由函数参数名自动推导——若函数 A 的形参名与函数 B 的返回值名相同，便自然形成一条从 B 到 A 的有向边。多个节点汇聚成 `Graph`，而 `Graph` 又可通过 `GraphAdapter` 投影到不同的执行后端。

图构建完成后，`Driver` 会保存三件关键信息用于后续追溯：

- **DAG 哈希（dag_hash）**：对节点集合与配置进行 Merkel 哈希，保证结构一致性；
- **代码哈希（code_hash）**：对实际源码做指纹，用于追溯到具体的代码版本；
- **代码制品（code_artifacts）**：记录代码文件路径、行号范围与 URL，便于在 UI 中定位源码。

`资料来源：[ui/backend/server/trackingserver_template/models.py:1-80]()`

在节点分类上，跟踪服务器的迁移文件为 `NodeTemplate` 定义了五种角色：`transform`、`data_saver`、`data_loader`、`input`、`placeholder`，分别对应转换、写库、读库、输入占位与待定占位语义。`资料来源：[ui/backend/server/trackingserver_template/migrations_sqlite/0001_initial.py:1-60]()`

## Driver 核心执行器

`Driver` 类是用户与框架交互的主要入口。典型用法如下：

```python
from hamilton import base, driver
import data_loading, features, model_pipeline, sets

config = {}
adapter = base.DefaultAdapter()
dr = driver.Driver(
    config, data_loading, features, sets, model_pipeline, adapter=adapter
)

# 可视化子图
dr.visualize_execution(
    [features.encoders], "encoder_lineage", {"format": "png"}, inputs=inputs
)

# 查询上游节点
upstream_nodes = dr.what_is_upstream_of("fit_random_forest")
```

`资料来源：[examples/lineage/README.md:40-90]()`

`Driver` 通过 `adapter` 抽象屏蔽底层执行后端（如 pandas、polars、Spark、Ibis）。调用 `execute()` 或 `materialize()` 时，它按拓扑序运行节点，并把结果收集到 dict 中返回。`base.DefaultAdapter` 等内置适配器负责类型与协议的转换，使同一份函数定义可在不同执行引擎间迁移。`资料来源：[hamilton/base.py]()`， `资料来源：[hamilton/graph.py]()`， `资料来源：[hamilton/node.py]()`

```mermaid
graph LR
    A[Python 模块/函数] --> B[Node 解析]
    B --> C[Graph 构建]
    C --> D[Driver 执行]
    D --> E[结果收集]
    D --> F[血统/可视化]
    D --> G[适配器 Adapter]
    G --> H[pandas / Spark / Polars / ...]
```

对于 I/O 密集或并发场景，框架提供 `AsyncDriver` 以协程方式调度节点。社区正在讨论扩展 `TaskExecutionHook`，以支持多级进度条与更细粒度的并行生命周期事件（见 Issue #1196 "Expanding Lifecycle Adapters for Dynamic DAGs / Parallel Execution"）。`资料来源：[hamilton/async_driver.py]()`， `资料来源：Issue #1196]()`

## DAG 注册、版本化与追踪

Apache Hamilton UI 通过 SDK 将本地构建的 DAG 注册到后端服务，实现持久化、版本化与可观测性。SDK 客户端主要暴露两个抽象方法：

| 方法 | 作用 | 返回值 |
|---|---|---|
| `register_project_version(...)` | 注册一个 DAG 模板（含 `dag_hash`、`code_hash`、节点列表、代码制品） | `template_id: int` |
| `create_and_start_dag_run(...)` | 基于已有模板发起一次运行（携带 `inputs`、`outputs` 与标签） | `run_id: int` |

`资料来源：[ui/sdk/src/hamilton_sdk/api/clients.py:1-80]()`

后端模型 `DAGTemplate` 维护名称、类型、配置、`dag_hash`、`is_active`、`tags` 与代码日志存储（`s3` / `local` / `none`）等字段，配套 `VersionInfo` 区分 `git` 与 `ad_hoc` 来源；这样便把 Hamilton 的函数级声明式建模与生产环境的资产治理衔接起来。`资料来源：[ui/backend/server/trackingserver_template/models.py:40-90]()`， `资料来源：[ui/backend/server/trackingserver_base/models.py:1-80]()`

## See Also

- [为什么选择 Apache Hamilton？](https://hamilton.apache.org/get-started/why-hamilton/)
- [Apache Hamilton UI 文档](https://hamilton.apache.org/hamilton-ui/ui/)
- [DAG 血统与可视化示例](https://github.com/apache/hamilton/tree/main/examples/lineage)
- [异步与并行任务示例](https://github.com/apache/hamilton/tree/main/examples/LLM_Workflows/scraping_and_chunking)

---

<a id='page-2'></a>

## 函数修饰器与 DAG 定义

### 相关页面

相关主题：[核心驱动引擎与 DAG 模型](#page-1), [生命周期钩子、缓存与并行执行](#page-3)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [hamilton/function_modifiers/__init__.py](https://github.com/apache/hamilton/blob/main/hamilton/function_modifiers/__init__.py)
- [hamilton/function_modifiers/base.py](https://github.com/apache/hamilton/blob/main/hamilton/function_modifiers/base.py)
- [hamilton/function_modifiers/configuration.py](https://github.com/apache/hamilton/blob/main/hamilton/function_modifiers/configuration.py)
- [hamilton/function_modifiers/dependencies.py](https://github.com/apache/hamilton/blob/main/hamilton/function_modifiers/dependencies.py)
- [hamilton/function_modifiers/expanders.py](https://github.com/apache/hamilton/blob/main/hamilton/function_modifiers/expanders.py)
- [hamilton/function_modifiers/macros.py](https://github.com/apache/hamilton/blob/main/hamilton/function_modifiers/macros.py)
</details>

# 函数修饰器与 DAG 定义

## 1. 概述与定位

Apache Hamilton 的核心思想是"以函数为节点、以参数依赖为边"声明式地描述数据流。普通 Python 函数经过 `@function`（或 `@parametrize` 等）系列**函数修饰器**装饰后，会被 Driver 在构建阶段解析为 DAG 中的节点（Node）。函数修饰器不仅是元数据标注，更承担着**DAG 拓扑变换**的职责——同一份源码可以被修饰器改写、复制或拆分，从而衍生出多个节点或子图。

资料来源：[hamilton/function_modifiers/base.py:1-30]()

修饰器体系按职责分为三大类，统一从 `hamilton.function_modifiers` 导出：[`__init__.py`](https://github.com/apache/hamilton/blob/main/hamilton/function_modifiers/__init__.py) 汇总了 `configuration`、`dependencies`、`expanders`、`macros`、`schema` 等子模块；其中 `schema` 相关条目在最新版本中以 `check_output` 方式呈现。

## 2. 修饰器分类与职责

| 类别 | 代表修饰器 | 主要作用 |
|------|------------|----------|
| 配置型 (`configuration`) | `config.when`, `config.when_not`, `config.param`, `config.inject` | 根据运行期配置决定节点是否启用、覆盖参数取值 |
| 依赖型 (`dependencies`) | `depends_on`, `value`, `source`, `group` | 显式声明函数签名之外的额外输入或来源 |
| 扩展型 (`expanders`) | `parametrize`, `expand`, `collect` | 一份函数源码衍生出多条平行节点（如 map / collect 模式） |

### 2.1 配置型修饰器

`config.when(...)` 与 `config.when_not(...)` 用于条件裁剪：当 Driver 传入的 `config` 字典满足（或不满足）指定条件时，被修饰函数才被纳入 DAG，否则视为不存在。`config.param` 则从全局配置中按 key 取值并作为参数注入。资料来源：[hamilton/function_modifiers/configuration.py:1-50]()

```python
from hamilton.function_modifiers import config

@config.when(env="prod")
def model_path() -> str:
    return "s3://prod-bucket/model.pkl"
```

### 2.2 依赖型修饰器

`depends_on` 允许在不修改函数签名的情况下追加上游依赖；`value(...)` 把一个常量值作为隐式输入注入；`source` 标识某个上游节点为当前节点的"数据源"。这些修饰器对 Hamilton 的 DAG **前向推断**机制是补充，常用于解耦函数声明与运行环境。资料来源：[hamilton/function_modifiers/dependencies.py:1-60]()

### 2.3 扩展型修饰器

`@parametrize(...)` 是最常用的"一份函数，多个节点"工具：同一函数体根据不同的参数组合展开成若干命名节点。`expand`/`collect` 进一步支持 `Parallelizable` 容器，可在运行时把列表拆开并行执行，再由 collect 节点合并。资料来源：[hamilton/function_modifiers/expanders.py:1-80]()

```python
from hamilton.function_modifiers import parametrize

@parametrize(
    fit_intercept=[True, False],
    normalize=[True, False],
)
def logistic_regression_params(fit_intercept: bool, normalize: bool) -> dict:
    return {"fit_intercept": fit_intercept, "normalize": normalize}
```

## 3. 修饰器 → DAG 的构建流程

下图给出 Hamilton Driver 在执行 `execute()` 之前将带修饰器函数转化为节点集合的简化流程：

```mermaid
flowchart TD
    A[用户定义模块<br/>含 @parametrize/@config.when 等] --> B[Driver.collect_modules]
    B --> C[解析函数签名<br/>提取参数名]
    C --> D[应用修饰器 resolve<br/>生成若干 Node 候选]
    D --> E{是否满足 config 条件?}
    E -- 否 --> F[丢弃节点]
    E -- 是 --> G[展开 parametrize/expand<br/>复制为多节点]
    G --> H[构建 DAG<br/>按依赖关系拓扑排序]
    H --> I[执行 execute()/visualize_execution]
```

核心抽象由 [`base.py`](https://github.com/apache/hamilton/blob/main/hamilton/function_modifiers/base.py) 中的 `NodeTransformer` / `NodeExpander` 基类承担：前者只改写单个节点（如 `depends_on`），后者把一个函数节点复制成多个（如 `parametrize`）。两类都对外暴露 `transform_node(...)` 或 `generate_nodes(...)` 接口，供 Driver 在 DAG 构建阶段调用。资料来源：[hamilton/function_modifiers/base.py:30-120]()

`macros.py` 提供了更高级的"复合修饰器"机制——即 `@macros(...)` 可以同时包含多个原子修饰器，等价于对函数依次施加多层变换。该机制常被用于在企业内部封装 Hamilton 风格。资料来源：[hamilton/function_modifiers/macros.py:1-60]()

## 4. 常见用法与社区关注点

- **生命周期与动态 DAG**：社区 issue #1196 反映了 `TaskExecutionHook` 在动态并行 DAG 中仅在任务起点触发，难以精细化呈现进度条等交互。社区讨论推动 Hamilton 在 `base.py` 中持续强化 `NodeLifecycleAdapter` 的可扩展点，鼓励用户通过自定义 `BaseLifecycleAdapter` 接入 `rich` 等第三方库。
- **条件裁剪顺序**：`config.when` 与 `parametrize` 同时使用时，Driver 会先按 parametrize 展开，再按 config 过滤；若配置条件与展开后的某个分支冲突，该分支会整体被裁剪。建议在使用前先用 `dr.display_all_functions(...)` 校验最终节点集合。
- **避免签名歧义**：被修饰函数的原始参数名仍需遵循 Hamilton 命名约定（即参数名 == 上游节点名）。`depends_on` 引入的额外依赖不应与签名冲突，否则会在拓扑排序阶段抛出异常。资料来源：[hamilton/function_modifiers/dependencies.py:60-110]()

## 5. 小结

函数修饰器是 Hamilton 把"函数式声明"升格为"可编排数据流"的关键装置：通过 `configuration` 决定**是否构建节点**，通过 `dependencies` 决定**节点依赖哪些上游**，通过 `expanders` 决定**节点如何复制与并行**，再由 `base.py` 中的 `NodeTransformer`/`NodeExpander` 抽象统一调度。对于需要复用同一份函数定义在 batch / streaming / online 三种上下文中执行特征工程的场景，掌握修饰器组合尤为关键。资料来源：[hamilton/function_modifiers/base.py:120-180]()

## See Also

- [Apache Hamilton 官方文档：节点与修饰器概念](https://hamilton.apache.org/concepts/node/)
- [examples/feature_engineering/feature_engineering_multiple_contexts](https://github.com/apache/hamilton/tree/main/examples/feature_engineering/feature_engineering_multiple_contexts) — 演示同一函数定义在多种上下文下的复用方式。
- [examples/LLM_Workflows/scraping_and_chunking](https://github.com/apache/hamilton/tree/main/examples/LLM_Workflows/scraping_and_chunking) — 展示 `@parametrize` 与 `Parallelizable` 的典型用法。

---

<a id='page-3'></a>

## 生命周期钩子、缓存与并行执行

### 相关页面

相关主题：[核心驱动引擎与 DAG 模型](#page-1), [函数修饰器与 DAG 定义](#page-2), [Hamilton UI、SDK、插件生态与开发工具](#page-4)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [hamilton/lifecycle/__init__.py](https://github.com/apache/hamilton/blob/main/hamilton/lifecycle/__init__.py)
- [hamilton/lifecycle/api.py](https://github.com/apache/hamilton/blob/main/hamilton/lifecycle/api.py)
- [hamilton/lifecycle/base.py](https://github.com/apache/hamilton/blob/main/hamilton/lifecycle/base.py)
- [hamilton/lifecycle/default.py](https://github.com/apache/hamilton/blob/main/hamilton/lifecycle/default.py)
- [hamilton/caching/__init__.py](https://github.com/apache/hamilton/blob/main/hamilton/caching/__init__.py)
- [hamilton/caching/adapter.py](https://github.com/apache/hamilton/blob/main/hamilton/caching/adapter.py)
- [examples/LLM_Workflows/scraping_and_chunking/README.md](https://github.com/apache/hamilton/blob/main/examples/LLM_Workflows/scraping_and_chunking/README.md)
- [ui/sdk/src/hamilton_sdk/api/clients.py](https://github.com/apache/hamilton/blob/main/ui/sdk/src/hamilton_sdk/api/clients.py)
</details>

# 生命周期钩子、缓存与并行执行

## 概述

Apache Hamilton 提供了一套围绕 DAG 执行生命周期的扩展机制，使开发者能够在节点执行、任务执行、DAG 整体生命周期等不同阶段介入。`hamilton.lifecycle` 子包定义了钩子接口与默认实现，`hamilton.caching` 子包提供结果缓存适配器，二者协同支撑"任务级并行执行 + 缓存复用 + 生命周期观测"的典型工作流。社区中 Issue #1196 即针对"任务型并行 DAG 下 `TaskExecutionHook` 仅在执行前触发"提出扩展诉求，反映了该套机制在实际多级进度条场景下的关键作用。资料来源：[hamilton/lifecycle/__init__.py:1-40]()、[hamilton/caching/__init__.py:1-20]()。

## 生命周期钩子

### 钩子分层

Hamilton 的生命周期钩子按照作用对象分为多个层级，包括节点级（Node 级）、任务级（Task 级）以及图级（DAG 级）。每类钩子都通过抽象基类声明前后回调签名，便于第三方实现自定义观测、校验或副作用逻辑。资料来源：[hamilton/lifecycle/api.py:1-120]()。

- **节点生命周期钩子**：在单个节点计算前后触发，适合做单点日志、指标打点。
- **任务生命周期钩子**（`TaskExecutionHook`）：在基于 `Parallelizable`/收集器展开后的并行任务前后触发，是并行场景下观测进度的核心。资料来源：[hamilton/lifecycle/base.py:1-160]()。
- **图级钩子**：在 DAG 整体构建、执行前后介入，常用于环境初始化或资源释放。

### 默认实现

`hamilton.lifecycle.default` 模块提供了开箱即用的钩子实现，例如默认日志、Schema 校验等，开发者可以直接在 `Driver(..., adapters=[...])` 中启用。资料来源：[hamilton/lifecycle/default.py:1-80]()。

### 自定义模式

开发者通过继承抽象基类并实现 `pre_*` / `post_*` 方法即可注入自定义逻辑；多个钩子可以通过 `L

ifecycleAdapter` 串联，形成责任链式的执行观测栈。

```mermaid
flowchart LR
    A[DAG 构建] --> B[图级 pre 钩子]
    B --> C[节点计算]
    C --> D[节点 pre/post 钩子]
    D --> E[Task 展开]
    E --> F[TaskExecutionHook]
    F --> G[并行执行任务]
    G --> H[Task post 钩子]
    H --> I[结果收集]
    I --> J[图级 post 钩子]
```

> 注：上图描述 Hook 在并行执行中的串联顺序，仅用于说明钩子分层关系。具体签名请参考 [hamilton/lifecycle/api.py](https://github.com/apache/hamilton/blob/main/hamilton/lifecycle/api.py)。

## 缓存机制

`hamilton.caching.adapter` 提供了将节点计算结果落地到缓存层的适配器接口，允许在重新执行 DAG 时复用上一次的结果，避免对相同输入的重复计算。资料来源：[hamilton/caching/adapter.py:1-80]()。

- **缓存键**：通常由节点名、依赖值（或其哈希）组合而成，确保相同输入能命中相同缓存。
- **生命周期整合**：缓存命中或失效事件可以与生命周期钩子联动，统一上报。
- **使用方式**：通过 `Driver(config, ..., adapter=SomeCacheAdapter())` 注入，缓存条目在 `execute()` 调用前后由驱动装配。

社区中也有用户希望在并行 DAG 中更细粒度地控制缓存粒度，目前可通过自定义 `CacheAdapter` 子类来满足。资料来源：[hamilton/caching/__init__.py:1-20]()。

## 并行执行与动态 DAG

### Parallelizable 模式

Hamilton 通过 `Parallelizable[T]` 标注 + `@parameterize`/`@collect` 等装饰器实现函数级的并行展开：上游返回 `Parallelizable`，Hamilton 会在内部将下游节点并行地按每个输入值执行一次。例如 `scraping_and_chunking` 示例中：

```python
def url(urls_from_sitemap: list[str], max_urls: int = 1000) -> Parallelizable[str]:
    ...
```

下游函数 `article_text(url: str, ...)` 会被映射执行 N 次，最终结果自动聚合。资料来源：[examples/LLM_Workflows/scraping_and_chunking/README.md:1-60]()。

### 任务级钩子与缓存协同

当 Parallelizable 展开为多个任务时，`TaskExecutionHook` 可用于跟踪每个子任务的开始与结束；结合缓存适配器，重复输入可命中缓存、跳过执行。这也是 Issue #1196 中讨论的"多级进度条"和"动态 DAG"扩展点的基础。

### UI 跟踪集成

Hamilton UI 后端通过 `hamilton_sdk.api.clients.BaseHamiltonClient` 抽象与生命周期/缓存元数据进行对接，将 DAG 模板、节点模板、代码 artifact 等上报到跟踪服务器，便于在 UI 中回放并行执行的进度与缓存命中情况。资料来源：[ui/sdk/src/hamilton_sdk/api/clients.py:1-120]()。

## 常见失败模式

| 现象 | 排查方向 |
|---|---|
| 钩子未触发 | 确认是否在 `Driver(..., adapters=[...])` 中注册，或子类未覆盖抽象方法 |
| 并行任务重复执行 | 检查缓存键是否覆盖全部依赖输入，或 `Parallelizable` 标注缺失 |
| UI 启动 `ConfigError`（Issue #1457） | 该问题与 `django-ninja` 版本相关，不在本页机制范围内，建议参考 release notes 中依赖升级说明 |

## See Also

- 节点与 DAG 基础概念
- Apache Hamilton UI 与跟踪服务器
- Parallelizable 与 `@collect` 装饰器

---

<a id='page-4'></a>

## Hamilton UI、SDK、插件生态与开发工具

### 相关页面

相关主题：[核心驱动引擎与 DAG 模型](#page-1), [生命周期钩子、缓存与并行执行](#page-3)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/apache/hamilton/blob/main/README.md)
- [scripts/README.md](https://github.com/apache/hamilton/blob/main/scripts/README.md)
- [ui/backend/server/trackingserver_base/models.py](https://github.com/apache/hamilton/blob/main/ui/backend/server/trackingserver_base/models.py)
- [ui/sdk/src/hamilton_sdk/api/clients.py](https://github.com/apache/hamilton/blob/main/ui/sdk/src/hamilton_sdk/api/clients.py)
- [ui/frontend/package.json](https://github.com/apache/hamilton/blob/main/ui/frontend/package.json)
- [dev_tools/vscode_extension/package.json](https://github.com/apache/hamilton/blob/main/dev_tools/vscode_extension/package.json)
- [examples/lineage/README.md](https://github.com/apache/hamilton/blob/main/examples/lineage/README.md)
- [examples/LLM_Workflows/scraping_and_chunking/README.md](https://github.com/apache/hamilton/blob/main/examples/LLM_Workflows/scraping_and_chunking/README.md)
- [examples/feature_engineering/feature_engineering_multiple_contexts/README.md](https://github.com/apache/hamilton/blob/main/examples/feature_engineering/feature_engineering_multiple_contexts/README.md)
- [examples/ibis/feature_engineering/README.md](https://github.com/apache/hamilton/blob/main/examples/ibis/feature_engineering/README.md)
</details>

# Hamilton UI、SDK、插件生态与开发工具

## 一、概述与定位

Apache Hamilton 的核心是一个函数式、声明式的数据流建模库，但它同时围绕一个完整的生态来交付工程化能力：[README.md](https://github.com/apache/hamilton/blob/main/README.md) 明确指出，Hamilton 可以"自动填充数据目录，提供 lineage/tracing，并提供执行可观测性"——这些能力由 Hamilton UI、SDK 与一组开发工具共同承担。

根据 [scripts/README.md](https://github.com/apache/hamilton/blob/main/scripts/README.md) 的描述，Apache Hamilton 由 5 个独立版本化的子包构成：

| 子包 | Key | 路径 | 说明 |
|---|---|---|---|
| `apache-hamilton` | hamilton | 根目录 | 核心库（必须最先发布）|
| `apache-hamilton-sdk` | sdk | `ui/sdk` | 追踪 SDK |
| `apache-hamilton-contrib` | contrib | `contrib` | 社区数据流 |
| `apache-hamilton-ui` | ui | `ui/backend` | Web UI 服务端 |
| `apache-hamilton-lsp` | lsp | `dev_tools/language_server` | 语言服务器 |

核心包必须最先发布，其余四个依赖核心但彼此互不依赖，这种分层为插件化扩展提供了清晰的发布契约。

## 二、Hamilton UI 架构

Hamilton UI 由后端 Django 服务与前端 React 应用共同组成。[README.md](https://github.com/apache/hamilton/blob/main/README.md) 提到 UI 既可作为本地服务运行，也可以用 Docker 部署。追踪后端采用 `trackingserver_base/models.py` 中定义的可插拔数据模型：所有 Hamilton 节点属性都以通用 `BaseHamiltonNode` 抽象基类承载，并通过 `ArrayField` 抽象类在 PostgreSQL（原生数组）与 SQLite（JSON 序列化文本）之间自适应切换。资料来源：[ui/backend/server/trackingserver_base/models.py:42-78]()

```mermaid
flowchart LR
    A[Hamilton 用户代码] -->|调用 Driver| B[hamilton_sdk]
    B -->|HTTP 批量上报| C[trackingserver_base/api.py]
    C --> D[(Django ORM + ArrayField)]
    D --> E[DRF/Ninja API]
    E --> F[ui/frontend React 应用]
    F -->|渲染 DAG/Lineage| G[浏览器]
```

社区最近反馈了启动期错误（Issue #1457）：新装 `hamilton ui` 后，django-ninja 抛 `ConfigError: The use of Config class is removed for ModelSchema, use 'Meta' instead`，说明 UI 后端在 Schema 元数据迁移上仍有兼容工作要做——若在升级后遇到相同报错，需要在 `trackingserver_base/api.py` 中把 `Config` 子类改写为 `Meta`。

## 三、Hamilton SDK 与追踪

SDK 的核心入口位于 [ui/sdk/src/hamilton_sdk/api/clients.py](https://github.com/apache/hamilton/blob/main/ui/sdk/src/hamilton_sdk/api/clients.py)。其中定义了 `ResourceDoesNotExistException`、`UnauthorizedException` 等业务异常，并通过 `create_batch()` 将来自客户端的 `attributes` 与 `task_updates` 聚合到 `dag_run_id` 维度：先按节点名归并，再以 `functools.reduce` 合并 `task_updates`，保证不会重复上报同一更新。资料来源：[ui/sdk/src/hamilton_sdk/api/clients.py:21-58]()

前端 [ui/frontend/package.json](https://github.com/apache/hamilton/blob/main/ui/frontend/package.json) 使用 React 19 + Vite 6 + `dagre`（用于 DAG 自动布局）+ `react-syntax-highlighter`（用于代码高亮），开发期通过 ESLint 9 与 Husky+lint-staged 强制规范代码风格；生产构建目标为 Chrome/Firefox/Safari 最新版。这一组合保证 UI 既能在本地以 `npm run dev` 启动，也能产出优化的静态产物供 Docker 镜像消费。

## 四、插件生态与开发工具

### 4.1 Contrib 与集成示例

Apache Hamilton 的扩展面覆盖数据库（Ibis）、LLM、特征工程等领域。[examples/ibis/feature_engineering/README.md](https://github.com/apache/hamilton/blob/main/examples/ibis/feature_engineering/README.md) 演示了在表级和列级粒度下用 Ibis + IbisML 表达特征流；[examples/ibis/jaffle_shop/README.md](https://github.com/apache/hamilton/blob/main/examples/ibis/jaffle_shop/README.md) 则把 dbt 的 jaffle_shop 用 Hamilton 复刻，去掉 `.yaml`/`.md` 文档堆积，让 docstring 与类型注解替代之。

### 4.2 Lineage 与 @tag 元数据

[examples/lineage/README.md](https://github.com/apache/hamilton/blob/main/examples/lineage/README.md) 给出"lineage as code"的标准配方：在函数上装饰 `@tag(owner=..., importance=..., artifact=...)`，通过 `Driver.visualize_execution()` 与 `Driver.what_is_upstream_of()` 提问 DAG。这让 lineage 信息天然落在 Git 历史里，而不是外挂文档系统。

### 4.3 并行执行与生命周期钩子

[examples/LLM_Workflows/scraping_and_chunking/README.md](https://github.com/apache/hamilton/blob/main/examples/LLM_Workflows/scraping_and_chunking/README.md) 演示了"Parallelizable + collect"模式：在 DAG 任意位置用 `Parallelizable[T]` 标记输入，用 `Collect[T]` 标记汇总节点即可并行。社区 Issue #1196 指出当前 `TaskExecutionHook` 仅在任务执行前触发，无法呈现多级进度条；这意味着构建基于 `rich` 的进度生命周期适配器时，需要监听更多 hook 或改用自定义适配器。

### 4.4 VSCode 扩展与 LSP

[dev_tools/vscode_extension/package.json](https://github.com/apache/hamilton/blob/main/dev_tools/vscode_extension/package.json) 描述了 `hamilton-vsc` 扩展：注册语言 `python` 激活，提供 "Rotate dataflow" / "Show Output" 等命令，并以 `webview` 形式呈现 DAG。它依赖 Cytoscape.js、d3-graphviz 与 wasm 渲染引擎。配套的 `dev_tools/language_server` 提供 LSP 实现，使 IDE 能够理解 `@tag`、`@config.when` 等装饰器语义。

### 4.5 多上下文特征工程

[examples/feature_engineering/feature_engineering_multiple_contexts/README.md](https://github.com/apache/hamilton/blob/main/examples/feature_engineering/feature_engineering_multiple_contexts/README.md) 展示了 batch/offline 与 online/streaming 共用一套 DAG 定义的方案——这正是 Hamilton 插件化的目标：让"同一份数据流"在 ETL、模型训练、实时推理之间无缝复用。

## 五、See Also

- 核心 Driver 与 DAG 概念：`hamilton.driver.Driver`、`@config.when`、`@check_output`
- 贡献流程与发布脚本：[scripts/README.md](https://github.com/apache/hamilton/blob/main/scripts/README.md)
- 已知问题追踪：Issue #1457（UI 启动错误）、Issue #1196（生命周期钩子覆盖度）
- 版本说明：`apache-hamilton-v1.90.0-incubating` 已弃用 Python 3.9 并新增 3.13 支持

---

<!-- evidence_pipeline_checked: true -->
<!-- evidence_injected: true -->

---

## Doramagic 踩坑日志

项目：apache/hamilton

摘要：发现 8 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：能力坑 - 来源证据：Improving documentation structure。

## 1. 能力坑 · 来源证据：Improving documentation structure

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个能力理解相关的待验证问题：Improving documentation structure
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/apache/hamilton/issues/1043 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 2. 安装坑 · 来源证据：Hamilton local ui fails with ImportError

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Hamilton local ui fails with ImportError
- 对用户的影响：可能影响升级、迁移或版本选择。
- 证据：community_evidence:github | https://github.com/apache/hamilton/issues/1649 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 3. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 证据：capability.assumptions | https://github.com/apache/hamilton | README/documentation is current enough for a first validation pass.

## 4. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 证据：evidence.maintainer_signals | https://github.com/apache/hamilton | last_activity_observed missing

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 证据：downstream_validation.risk_items | https://github.com/apache/hamilton | no_demo; severity=medium

## 6. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 证据：risks.scoring_risks | https://github.com/apache/hamilton | no_demo; severity=medium

## 7. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 证据：evidence.maintainer_signals | https://github.com/apache/hamilton | issue_or_pr_quality=unknown

## 8. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 证据：evidence.maintainer_signals | https://github.com/apache/hamilton | release_recency=unknown

<!-- canonical_name: apache/hamilton; human_manual_source: deepwiki_human_wiki -->
