> ## Documentation Index
> Fetch the complete documentation index at: https://ahvn.top/llms.txt
> Use this file to discover all available pages before exploring further.

# 哈希

> 用于标识符、分桶与指纹的确定性哈希辅助工具。

<Note>
  *「万物皆数。」——毕达哥拉斯*
</Note>

当你需要为标量、集合、Python 对象、callable 及其他 HeavenBase 值提供单一哈希入口时使用这些 helper。

<br />

## 1. 为何需要统一哈希

HeavenBase 会从多种值类型派生 ID、分桶、缓存键与指纹——int、字符串、列表、字典、dataclass 行、Python 函数、capsule、MCP 工具等。若没有共享编码器层，每个调用点都会各自实现序列化规则：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Anti-pattern: one-off encoders per value kind
import hashlib
import json

def make_id(value):
    if isinstance(value, str):
        payload = value
    elif isinstance(value, dict):
        payload = json.dumps(value, sort_keys=True)
    elif callable(value):
        payload = f"{value.__module__}.{value.__qualname__}"
    else:
        payload = repr(value)
    return hashlib.md5(payload.encode()).hexdigest()
```

这种模式很快会碎片化。字典行、toolkit 定义与 callable capsule 各自需要不同编码逻辑，可选的命名空间 salt 又会变成另一种临时拼接规则。

HeavenBase 用共享编码器与可选 `salt` 包装标准摘要——MD5、SHA-256 与 CRC32。编码器在哈希前将常见 Python 值（含结构化对象与 callable）规范为确定性字符串；当多个逻辑部分应一起哈希时，`hash_id(...)` 是带命名空间的前门：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from heavenbase.utils import crc32hash, hash_id, hash_int, md5hash

# Same API for scalars, collections, and structured objects
row_id = md5hash({"source": "docs", "name": "Ada"})
entity_id = hash_id("document", "Ada")

# Callables hash through the same encoder path
tool_id = md5hash(my_callable)

# Salt namespaces a digest without changing the value encoding
cache_key = md5hash(large_payload, salt="llm-cache-v2")
gram_weight = crc32hash("redis query", salt="heavenbase.gram.v1")
sample_weight = hash_int("row-17", method="crc32")
```

一条 import 路径即可覆盖 HeavenBase 在 JSON、数据库、catalog、toolkit 与 capsule 中流转的各类标识符、取模分桶、缓存键与指纹。输入形态变化时，你不必每次另选哈希策略。

<Warning>
  统一哈希会在摘要前先序列化输入。对标量与小字典成本很低，但对大量大型深层嵌套对象——或触发完整源码序列化的 callable——进行海量哈希可能带来明显开销。对每秒哈希数百万重量级载荷的热路径应做性能剖析。
</Warning>

<Info>
  这些 helper 是确定性 utility 哈希，不是认证或密码存储原语。
</Info>

<br />

## 2. 核心思想

HeavenBase 常需要行为像字符串的标识符，因为它们会流经 JSON、数据库行、object ID 与文件名。有时也受益于可解释为整数的值，用于排序、分桶或索引友好存储。

`md5hash(...)` 与 `crc32hash(...)` 返回补零十进制字符串。这意味着它们可作为普通字符串 ID 使用，且等长值还可按整数表示排序。`crc32hash(...)` 默认长度为 `10`；`md5hash(...)` 默认长度为 `42`。

<Info>
  这尚未定为通用设计。可转为整数的字符串哈希是当前预发布阶段的实用兼容方案，并非声称每个外部 API 都应依赖这一精确表示。我们仍在探索兼顾稳定性与通用可用性的最佳方案。
</Info>

<br />

## 3. 创建稳定 ID

`md5hash(...)` 以稳定 JSON 顺序序列化常见 Python 值，并返回补零十进制字符串。默认长度为 `42`，与 HeavenBase 标识符友好哈希宽度一致。

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from heavenbase.utils import md5hash

row_id = md5hash({"source": "docs", "name": "Ada"})
same_id = md5hash({"name": "Ada", "source": "docs"})

assert row_id == same_id
```

当 ID 应携带逻辑命名空间时使用 `hash_id(...)`：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from heavenbase.utils import hash_id

prompt_id = hash_id("prompt", "demo.greet", "1")
```

<br />

## 4. 分桶或排序值

当取模运算、确定性采样、稀疏权重或排序需要数值时，使用整数摘要。当方法属于运行时策略而非固定 ID 契约时，使用 `hash_int(...)` 或 `resolve_hash_int(...)`。

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from heavenbase.utils import crc32int, hash_int, md5int, resolve_hash_int, sha256int

bucket = md5int("workspace-alpha") % 16
gram_bucket = crc32int("redis query", salt="heavenbase.gram.v1") % 1024
wide_bucket = sha256int({"workspace": "alpha", "entity": "person"}) % 1024
policy_bucket = hash_int("candidate-row", method="crc32") % 1024
same_policy = resolve_hash_int("crc32")("candidate-row") % 1024
```

`resolve_hash_int(...)` 接受 `md5`、`sha256`、`crc32`、安装 `xxhash` 包后可用的可选 `xxhash64` / `xxhash128`，以及签名为 `fn(obj, salt=None, sep="||") -> int` 的 dotted callable。

`crc32int(...)` 是最便宜的标准库确定性选项，Sparse GRAM runtime 使用它生成 SQL 托管 `SparseGramIndex` 与显式兼容 `gram` backend 的 trigram 权重和 sparse-span 哈希。CRC32 碰撞只会扩大候选集，精确关键词验证会保护查询正确性。`md5int(...)` 仍适合本地 utility ID；当更宽摘要能更清楚表达意图时，使用 `sha256int(...)`。

持久化 identity 与 integrity 表面应固定使用显式 helper：现有 object ID 使用 `hash_id(...)` / `md5hash(...)`，指纹与缓存正确性边界使用 `sha256hash(...)`。CRC32 是候选生成与确定性采样的默认策略，因为这些路径会精确验证或可接受样本选择变化。

<br />

## 5. 为较大载荷生成指纹

在 manifest、配置快照与完整性检查中使用 `sha256hash(...)` 生成 hex 指纹。

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from heavenbase.utils import fmt_short_hash, sha256hash

fingerprint = sha256hash({"model": "ds-flash", "temperature": 0})
display = fmt_short_hash(fingerprint, length=10)
```

<Info>
  这些 helper 是确定性 utility 哈希，不是认证或密码存储原语。
</Info>

<br />

## 进一步探索

<Tip>
  **相关资源：**

  * [随机](/zh/features/utilities/random) - 确定性 seed 演进与基于哈希的采样。
  * [文件系统](/zh/features/utilities/file-system) - 哈希结构化数据前使用的序列化 helper。
  * [目录](/zh/features/catalog) - object ID 与可发现命名。
</Tip>

<br />
