Metadata-Version: 2.5
Name: zleap-sag2
Version: 0.4.0
Summary: SAG2 passage retrieval with portable relational storage
Project-URL: Homepage, https://github.com/Zleap-AI/zleap
Project-URL: Repository, https://github.com/Zleap-AI/zleap
Project-URL: Documentation, https://github.com/Zleap-AI/zleap/tree/main/packages/sag2#readme
Project-URL: Issues, https://github.com/Zleap-AI/zleap/issues
License-Expression: MIT
License-File: LICENSE
License-File: NOTICE
Requires-Python: >=3.11
Requires-Dist: aiohttp>=3.14.3
Requires-Dist: aiosqlite>=0.19
Requires-Dist: jieba==0.42.1
Requires-Dist: pydantic-settings>=2.6
Requires-Dist: pydantic>=2.5
Requires-Dist: pyuca==1.2
Requires-Dist: regex>=2026.9.29
Requires-Dist: sqlalchemy[asyncio]>=2.0
Requires-Dist: tiktoken>=0.14
Requires-Dist: tokenizers>=0.22
Requires-Dist: tzdata
Provides-Extra: all
Requires-Dist: aiomysql>=0.2; extra == 'all'
Requires-Dist: asyncpg>=0.29; extra == 'all'
Requires-Dist: cryptography>=50; extra == 'all'
Requires-Dist: lancedb<0.38,>=0.37.1; extra == 'all'
Requires-Dist: markitdown[xlsx]<0.2,>=0.1.5; extra == 'all'
Requires-Dist: openpyxl<4,>=3.1.5; extra == 'all'
Requires-Dist: pandas<3,>=2.2; extra == 'all'
Requires-Dist: xlrd<3,>=2; extra == 'all'
Provides-Extra: dev
Requires-Dist: build>=1; extra == 'dev'
Requires-Dist: hatchling>=1.27; extra == 'dev'
Requires-Dist: httpx>=0.28; extra == 'dev'
Requires-Dist: packaging>=24; extra == 'dev'
Requires-Dist: pytest-asyncio>=1; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff==0.16.4; extra == 'dev'
Requires-Dist: twine>=6; extra == 'dev'
Provides-Extra: lance
Requires-Dist: lancedb<0.38,>=0.37.1; extra == 'lance'
Provides-Extra: mysql
Requires-Dist: aiomysql>=0.2; extra == 'mysql'
Requires-Dist: cryptography>=50; extra == 'mysql'
Provides-Extra: postgres
Requires-Dist: asyncpg>=0.29; extra == 'postgres'
Provides-Extra: tables
Requires-Dist: markitdown[xlsx]<0.2,>=0.1.5; extra == 'tables'
Requires-Dist: openpyxl<4,>=3.1.5; extra == 'tables'
Requires-Dist: pandas<3,>=2.2; extra == 'tables'
Requires-Dist: xlrd<3,>=2; extra == 'tables'
Description-Content-Type: text/markdown

# zleap-sag2

[中文](#中文) | [English](#english)

## 中文

SAG2 原文检索引擎：统一词法召回、多轮 JEV 证据评分和本地多样性排序。
支持 SQLite、MySQL、PostgreSQL 和 OceanBase，并提供独立的 LanceDB 索引接口。
连接已有 SAG1 库时，自动从 `source_chunk` 读取现有段落；空库使用 SAG2 自有存储。

### 0.4.0：无损分页快照与滚动升级兼容

- 新增可选的引用快照，避免长文档全文在分页结果中重复保存而超过 16 MiB；
  续页时从已发布索引恢复原文，并校验来源标识和内容摘要。
- 默认保持 `SAG2_SEARCH_SNAPSHOT_FORMAT=inline`。所有共享库实例升级后可开启
  `references`；升级后的 reader 始终支持两种格式。回滚旧版本前，先将所有实例
  切回 `inline`、排空引用写入，再从最后一次引用写入提交起等待至少 3600 秒。
  详见[升级与回滚说明](docs/api-compatibility.md)。

### 0.3.0：持久化倒排索引

- SQLite、MySQL、PostgreSQL、OceanBase 持久化保存词项、词频和词位置；LanceDB
  使用持久化倒排表与 BTree 索引。分词、BM25、短语匹配、扩展、JEV 和 DPP 沿用包内规则。
- 打开库和搜索不再重建全量 Python 倒排索引；按查询词分批读取命中记录，并用有界
  Top-K 堆保留候选。LanceDB 建库统计使用磁盘临时库。
- 关系型写入在检查点事务内更新倒排；不可变版本与可续期租约保护并发搜索。
- 新增独立的 `SQLiteIndex`、`LanceIndex` 和 `LancePassage` 公共接口，详见
  [持久化索引接口](#持久化索引接口)。
- 直接创建新库，不提供旧 schema 或实验索引的自动迁移。MySQL 需要 8.0 或更高版本。

### 0.2.0：减少 JEV 输入 token

JEV 默认使用 `stateful` 请求格式，在同一批请求内共享候选上下文，减少重复输入。
MuSiQue、HotpotQA、2WikiMultihopQA 各前 1,000 题的在线对照中，服务端返回的
JEV 输入 token 分别减少 **19.14%、18.65%、18.32%**，合计减少 **18.70%**。
实验使用 302ai 的 `typesafe/jev-1.13`，收益取决于模型、服务商和候选内容；
本次未观察到稳定提速，检索召回率有小幅波动。

兼容或排障时仍可设置 `DECISION_PAYLOAD_STYLE=inline`。完整口径和结果见
[实验说明](https://github.com/Zleap-AI/zleap/blob/main/packages/sag2/docs/benchmarks/jev-payload-2026-10-27.md)，
版本变更见 [CHANGELOG](https://github.com/Zleap-AI/zleap/blob/main/packages/sag2/CHANGELOG.md)。

### 安装

可按包名从 PyPI 安装：

```sh
pip install zleap-sag2
# MySQL / OceanBase
pip install 'zleap-sag2[mysql]'
# PostgreSQL
pip install 'zleap-sag2[postgres]'
# LanceDB
pip install 'zleap-sag2[lance]'
# 电子表格转换
pip install 'zleap-sag2[tables]'
```

从源码安装时，先进入包含本文件和 `pyproject.toml` 的包目录，再执行
`pip install .`；可选依赖使用 `pip install '.[tables]'` 等形式。
也可通过 `pip install` 指定已下载 wheel 文件的实际路径。

### 独立开发

可以直接在 IDE 或 Codex 中打开包目录：仓库中的 `packages/sag2`，或解压后的
源码包根目录。以下命令均在该目录执行。源码、测试、脚本、文档和环境变量模板
均在本目录内；使用仓库检出时，Git 提交仍属于 `zleap` 根仓库。

```sh
make install                    # 本目录 .venv，只安装 SAG2 和开发/表格依赖
make verify                     # lint、离线测试、构建、产物元数据检查
cp .env.example .env             # 需要连接模型服务时再填写
```

也可在根目录运行 `make -C packages/sag2 verify`。根目录的 `make verify` 仍检查 SAG。
本包独立版本为 `src/zleap/sag2/__about__.py`，发布 tag 为 `zleap-sag2/vX.Y.Z`；
发布配置见仓库的 [RELEASING.md](https://github.com/Zleap-AI/zleap/blob/main/RELEASING.md)。`zleap` 元包暂不依赖 SAG2，
使用者需单独安装 `zleap-sag2`。

```python
import asyncio
from zleap.sag2 import DataEngine, EngineConfig
from zleap.sag2 import TextSource, SourceDescriptor, SearchScope, SearchRequest


async def main():
    config = EngineConfig.from_env(".env")
    async with DataEngine(config, data_source_id="demo") as engine:
        await engine.ingest(
            TextSource(
                text="# 示例\nAlice 出生在北京。",
                descriptor=SourceDescriptor(
                    data_source_id="demo",
                    source_id="alice",
                    source_type="text",
                ),
            )
        )
        result = await engine.search(
            SearchRequest(query="Alice 出生在哪里？", scope=SearchScope(data_source_ids=("demo",)))
        )
        for hit in result.chunks:
            print(hit.score, hit.content)


asyncio.run(main())
```

`parse` 和 `chunk` 可在启动数据库前使用。`index(ChunkSet)` 直接保存已有分块。

### 配置

关系库环境变量与 SAG1 一致，使用 `EngineConfig.from_env(".env")` 显式读取文件；
`EngineConfig.from_env()` 只读取进程环境，不自动寻找 `.env`。最小配置：

```dotenv
SAG_RELATIONAL_PROVIDER=sqlite
SAG_DATA_DIR=./.zleap
DECISION_ENDPOINT=https://api.typesafe.ai/v1/systemone
DECISION_MODEL=jev-latest
DECISION_API_KEY=your-key
```

推荐使用 [JEV（TypeSafe）](https://typesafe.ai/) 或
[D1-ultra（Liquid AI）](https://www.liquid.ai/blog/d1-ultra) 作为决策模型。
使用 D1-ultra 时，将接口改为 `https://api.liquid.ai/decisions/v1/systemone`、
模型改为 `d1-ultra`，并填写 Liquid AI 的 API Key。使用其他服务商时，
模型 ID 与接口地址以该服务商为准，三项配置需对应同一服务。

决策请求的 token 预算使用随包提供的 `o200k_base` 编码资源；首次启动无需下载
tokenizer 或预置缓存。实际用量仍取决策服务返回的 `usage`。

SQLite 使用 `<SAG_DATA_DIR>/sag.db`，默认 `.zleap/sag.db`。服务库使用
`SAG_RELATIONAL_HOST` / `PORT` / `USER` / `PASSWORD` / `DATABASE`，连接池、超时及
PostgreSQL TLS 参数同样沿用 `SAG_RELATIONAL_*`。默认端口为 MySQL 3306、
PostgreSQL 5432、OceanBase 2881。

`RELATIONAL_PROVIDER`、`DATA_DIR`、`DB_HOST` / `DB_PORT` / `DB_USER` /
`DB_PASSWORD` / `DB_NAME`、`DB_POOL_*` / `DB_MAX_OVERFLOW` / `DB_CONNECT_TIMEOUT` /
`DB_COMMAND_TIMEOUT`、`DB_TLS_*` 也与 SAG1 一致。同名进程变量覆盖文件值；
同时设置等价名称时，`SAG_*` 优先，空值视为未设置。

SAG1 的配置文件可以直接复用，SAG2 不使用其中的 LLM、Embedding、向量库和
事件配置；搜索需补充 `DECISION_*`。未配置任何决策模型参数时仍可解析、切块、读取与续页，
部分配置决策模型参数会在加载时明确报错。也可以直接构造 `EngineConfig` 和
`RelationalConfig`，显式配置不读取环境变量。

### 直接搜索 SAG1 已有数据

用 `EngineConfig.from_env(".env")` 读取 SAG1 的连接配置，补充决策模型配置后直接调用
`search()` 或 `search_page()`，无需先调用 `index()`。
引擎启动时识别 `source_chunk`，沿用原段落 ID，读取 `article` / `chat_conversation`
补充来源信息，并遵守活动 generation、来源删除和数据源停用状态。normal / lite
的文本关系表均可读取，不需要安装 `zleap-sag` 或访问原向量库、事件表。

此模式支持搜索、分页、`read_chunk()`、`read_outline()` 和 `source_state()`。
原 SAG1 业务表保持只读，写入、删除和持久处理任务继续由 SAG1 管理；这些调用
在 SAG2 中会明确报 `sag.read_only_storage`，`capabilities()` 返回实际可用能力。
启动补建 `sag2_state`、`sag2_search_sessions` 和 `sag2_lex_*` 持久化倒排辅助表，需要相应建表权限；
翻页仍会写会话状态，SAG1/SAG2 的分页结果不会混用。

SAG1 的后续写入会使缓存刷新、旧游标过期，包括没有更新 manifest 的普通
`index()` 写入。为此，当前每次读取与游标校验都会扫描请求数据源的段落并计算
可见文本指纹，成本随范围内数据量增长。不提供旧 SAG2 数据向 SAG1 的迁移。

会话和录音转写支持按完整单元重叠切块。对 `parse()` 返回的会话或录音结果使用：

```python
from zleap.sag2 import ChunkOptions

chunk_set = await engine.chunk(
    parsed,
    ChunkOptions(strategy="overlap", max_tokens=800, overlap_tokens=100),
)
```

下一块会尽可能携带上一块末尾连续的完整消息或转写单元。重叠部分的 token 数
不超过 `overlap_tokens`，同时为新单元预留 `max_tokens` 内的空间；计算包含说话人
标签和换行。单元放不下时减少或取消重叠，不截断消息。单条超长单元仍完整保留，
因此可能单独超过 `max_tokens`。重叠单元保留原始文本、引用及时间范围。
`overlap_tokens` 默认是 0，表示不重叠；会话默认的时间窗口和录音默认的 token
窗口不受影响。

`SearchOptions` 配置 SAG2 候选数、扩展词数、追加轮数和输出数量；默认 100/20/2/10。
搜索失败会抛出异常，JEV 可重试错误最多尝试四次。

分页搜索沿用 `zleap-sag` 的调用方式：

```python
from zleap.sag2 import SearchPageRequest

# request 是包含 query、scope、options 的 SearchRequest。
page = await engine.search_page(SearchPageRequest(request=request, page_size=20))
for hit in page.result.chunks:
    print(hit.score, hit.content)
if page.next_cursor is not None:
    page = await engine.search_page(
        SearchPageRequest(cursor=page.next_cursor, cursor_request=request)
    )
```

首次执行 SAG2 并持久化结果，后续翻页不再调用 JEV，可跨进程与重启使用。
总数受搜索的 `top_k` 限制；默认每页 50 项、有效期 300 秒。
问题或范围不匹配、游标篡改会报 `CursorInvalidError`；到期或相关数据源变更会报
`CursorExpiredError`，调用方应重新搜索。过期会话通过 `maintain()` 有界清理。

长文分页可在所有共享库实例升级后启用
`EngineConfig(search_snapshot_format="references")`；使用 `from_env()` 时设置
`SAG2_SEARCH_SNAPSHOT_FORMAT=references`。默认 `inline` 保持旧版本可读的写入格式，
两种模式均读取旧快照与新引用。回滚旧版本前先关闭全部引用写入，排空在途请求，
再等待最后一次引用写入后的最大 TTL（3600 秒）；详见接口兼容说明中的升级与回滚步骤。

指定数据库时，向 `EngineConfig(relational=RelationalConfig(...))` 传入提供方与
对应的异步连接地址。`sqlite` 使用 `sqlite+aiosqlite:///...`，`mysql` 与
`oceanbase` 使用 `mysql+aiomysql://...`，`postgres` 使用
`postgresql+asyncpg://...`；凭据由应用配置提供。

详细说明见仓库中的[架构文档](https://github.com/Zleap-AI/zleap/blob/main/packages/sag2/docs/architecture.md)、
[开发与验证](https://github.com/Zleap-AI/zleap/blob/main/packages/sag2/docs/reproduction.md)和
[接口兼容说明](https://github.com/Zleap-AI/zleap/blob/main/packages/sag2/docs/api-compatibility.md)。
这些文档也包含在源码包的 `docs/` 目录中。

JEV 默认使用 `stateful` 请求格式共享批内候选上下文。兼容或排障时可设置
`DECISION_PAYLOAD_STYLE=inline`，或显式传入 `JevConfig(payload_style="inline", ...)`。

### 持久化索引接口

SQLite、MySQL、PostgreSQL、OceanBase 原生存储共用持久化位置倒排实现：
`sag2_lex_postings` 以 `(term_key, chunk_id)` 为主键，保存三字段词位、加权词频和
正文词频。词典标识使用 SHA-256，避免数据库大小写或重音排序规则改变精确匹配。
SQL 查询需要 CTE 和窗口函数，MySQL 需要 8.0 或更高版本。
包内统一计算 BM25、短语匹配、扩展与 DPP，不使用各数据库原生 FTS 的分词或评分。

关系型后端在写入检查点事务内维护倒排；发布切换活动版本，删除立即退出检索，
`maintain()` 回收退役版本。搜索租用不可变版本，JEV 等待期间不占用数据库连接或
全局写锁。租约有效期 5 分钟，每分钟续期；租约过期时查询报错并要求重试。
正常结束、失败、取消和关闭均释放租约，崩溃遗留的过期租约由 `maintain()` 回收。

打开库和搜索不重建全量 Python 索引。客户端工作集取决于查询词数、256 条倒排分页、
候选数和返回的原始文档；单个原始文档仍需容纳其文本。常见词仍可能命中很长的倒排表，
数据库也需执行范围过滤、统计与排序，目前没有百万级延迟或 SLA 结论。
扩展词和 DPP 的词频统计采用批量查询，扩展候选共享评分扫描。
`LexicalSnapshot` 仅保留为小规模回归参考，正式存储后端不构造它。

连接已有 SAG1 库时，业务表保持只读，辅助倒排按原始文档持久化。旧写入接口未必
递增可靠版本号，搜索与分页校验因此仍会分页扫描可见记录以检测变更，排序临时文件
放在磁盘；仅变化文档重新建立倒排。此兼容读取路径与旧 SAG2 schema 迁移不同，
`0.3.0` 不提供旧 schema 或实验索引的自动迁移。

`SQLiteIndex`、`LanceIndex` 是独立、不可变的 passage 索引接口，与关系型
`DataEngine` 的命令和生命周期接口分别提供。每个 passage 是一个评分文档，来源引用
可放入 `metadata`。创建需要新的文件或目录；语料变更需要创建新的索引，未提供增量修改。
两个接口均使用 `LancePassage` 输入；SQLite 不需要安装 LanceDB。
下面的 `scorer` 是已配置的 `JevClient` 或实现异步 `score()` 的评分器。

#### SQLite 示例

```python
from pathlib import Path
from zleap.sag2 import SQLiteIndex, LancePassage


async def search_sqlite(scorer):
    passages = [
        LancePassage(
            title="Conversation",
            content="Alice adopted cats from Cedar Shelter.",
            source_id="session-1",
            metadata={"message_ids": ["m1"]},
        ),
    ]
    with SQLiteIndex.create(Path("example.sqlite"), passages, corpus_digest="revision-1") as index:
        assert index.check_integrity()
    with SQLiteIndex.open(Path("example.sqlite"), corpus_digest="revision-1") as index:
        return await index.search("Where did Alice adopt the cats?", scorer=scorer)
```

#### LanceDB 示例

安装 `pip install 'zleap-sag2[lance]'`；从源码安装时使用 `pip install '.[lance]'`。

```python
from pathlib import Path
from zleap.sag2 import LanceIndex, LancePassage


async def search_lance(scorer):
    passages = [
        LancePassage(
            title="Conversation",
            content="Alice adopted cats from Cedar Shelter.",
            source_id="session-1",
            metadata={"message_ids": ["m1"]},
        ),
    ]
    with LanceIndex.create(
        Path("example-lance-index"), passages, corpus_digest="revision-1"
    ) as index:
        original = index.get_passages([1])[1]
    with LanceIndex.open(Path("example-lance-index"), corpus_digest="revision-1") as index:
        return await index.search("Where did Alice adopt the cats?", scorer=scorer)
```

LanceDB 表保存倒排、长度、语料词频与来源元数据，并为词项、统计项和片段 ID 建立
BTree 索引。打开索引只读取 schema 和计数；查询使用独立缓存，分批读取倒排与最终
选中的正文。构建统计落在磁盘临时库，常见词排序仅保留有界 Top-K 堆。
标题短语、重音人名修复和正文规范化沿用包内规则；`metadata` 保留原始正文与来源引用。

## English

SAG2 is a passage retrieval engine that combines lexical retrieval, multiple rounds
of JEV evidence scoring, and local diversity ranking. It supports SQLite, MySQL,
PostgreSQL, and OceanBase, with a standalone index API for LanceDB. When connected
to an existing SAG1 database, it reads passages from `source_chunk`; empty databases
use SAG2's own storage.

### 0.4.0: lossless pagination snapshots and rolling upgrades

- Add opt-in reference snapshots so duplicated full text from long documents does
  not exceed the 16 MiB snapshot limit. Pagination restores original text from the
  published index and verifies source identities and content checksums.
- Keep `SAG2_SEARCH_SNAPSHOT_FORMAT=inline` by default. Enable `references` after
  upgrading all instances that share the database; upgraded readers always support
  both formats. Before reverting to older code, switch all instances to `inline`,
  drain reference writes, and wait at least 3600 seconds after the last reference
  write commits. See the [upgrade and rollback guide](docs/api-compatibility.md).

### 0.3.0: persistent inverted indexes

- SQLite, MySQL, PostgreSQL, and OceanBase persist terms, frequencies, and token
  positions. LanceDB uses persistent posting tables and BTree indexes. Tokenization,
  BM25, phrase matching, expansion, JEV, and DPP retain the package's existing rules.
- Opening and searching an index no longer reconstructs corpus-wide Python
  postings. Searches read matching postings in batches and retain candidates in
  bounded top-k heaps. LanceDB construction statistics use a temporary disk database.
- Relational ingestion updates postings in checkpoint transactions. Immutable
  versions and renewable leases protect concurrent searches.
- Added the public `SQLiteIndex`, `LanceIndex`, and `LancePassage` interfaces; see
  [Persistent index APIs](#persistent-index-apis).
- Create fresh databases directly; automatic migration of old schemas or
  experimental indexes is not provided. MySQL requires version 8.0 or later.

### 0.2.0: reduced JEV input tokens

JEV uses the `stateful` payload format by default, sharing candidate context within
each request batch to reduce repeated input. Online comparisons on the first
1,000 questions from each of MuSiQue, HotpotQA, and 2WikiMultihopQA reduced
server-reported JEV input tokens by **19.14%, 18.65%, and 18.32%**, respectively,
or **18.70% combined**. The experiment used `typesafe/jev-1.13` via 302ai.
Savings depend on the model, provider, and candidate content. The experiment did
not demonstrate a consistent speedup, and retrieval recall varied slightly.

Set `DECISION_PAYLOAD_STYLE=inline` for compatibility or troubleshooting. See the
[experiment report](https://github.com/Zleap-AI/zleap/blob/main/packages/sag2/docs/benchmarks/jev-payload-2026-10-27.md)
for the methodology and results, and the
[CHANGELOG](https://github.com/Zleap-AI/zleap/blob/main/packages/sag2/CHANGELOG.md)
for release notes.

### Installation

Install the package from PyPI:

```sh
pip install zleap-sag2
# MySQL / OceanBase
pip install 'zleap-sag2[mysql]'
# PostgreSQL
pip install 'zleap-sag2[postgres]'
# LanceDB
pip install 'zleap-sag2[lance]'
# Spreadsheet conversion
pip install 'zleap-sag2[tables]'
```

To install from source, enter the package directory containing this file and
`pyproject.toml`, then run `pip install .`. Use `pip install '.[tables]'` to include
optional dependencies. You can also pass a downloaded wheel's path to `pip install`.

### Independent development

Open `packages/sag2` in the repository, or the root of an extracted source
distribution, directly in your IDE or Codex. Run the following commands in that
directory. Source code, tests, scripts, documentation, and the environment template
are all contained there. In a repository checkout, commits belong to the root
`zleap` repository.

```sh
make install                    # Local .venv with SAG2, development and table dependencies
make verify                     # Lint, offline tests, build and artifact metadata checks
cp .env.example .env             # Fill in credentials when connecting to a model service
```

You can also run `make -C packages/sag2 verify` from the repository root. The root
`make verify` checks SAG. SAG2 maintains its own version in
`src/zleap/sag2/__about__.py` and uses release tags named `zleap-sag2/vX.Y.Z`.
See [RELEASING.md](https://github.com/Zleap-AI/zleap/blob/main/RELEASING.md) for the
release configuration. The `zleap` umbrella package does not currently depend on
SAG2; install `zleap-sag2` separately.

```python
import asyncio
from zleap.sag2 import DataEngine, EngineConfig
from zleap.sag2 import TextSource, SourceDescriptor, SearchScope, SearchRequest


async def main():
    config = EngineConfig.from_env(".env")
    async with DataEngine(config, data_source_id="demo") as engine:
        await engine.ingest(
            TextSource(
                text="# Example\nAlice was born in Beijing.",
                descriptor=SourceDescriptor(
                    data_source_id="demo",
                    source_id="alice",
                    source_type="text",
                ),
            )
        )
        result = await engine.search(
            SearchRequest(
                query="Where was Alice born?", scope=SearchScope(data_source_ids=("demo",))
            )
        )
        for hit in result.chunks:
            print(hit.score, hit.content)


asyncio.run(main())
```

`parse` and `chunk` can be used before starting the database. Use `index(ChunkSet)`
to store chunks that have already been prepared.

### Configuration

Relational database environment variables are compatible with SAG1. Use
`EngineConfig.from_env(".env")` to explicitly load a file; `EngineConfig.from_env()`
reads only the process environment and does not search for `.env`. Minimal settings:

```dotenv
SAG_RELATIONAL_PROVIDER=sqlite
SAG_DATA_DIR=./.zleap
DECISION_ENDPOINT=https://api.typesafe.ai/v1/systemone
DECISION_MODEL=jev-latest
DECISION_API_KEY=your-key
```

[JEV (TypeSafe)](https://typesafe.ai/) and
[D1-ultra (Liquid AI)](https://www.liquid.ai/blog/d1-ultra) are recommended decision
models. For D1-ultra, set the endpoint to `https://api.liquid.ai/decisions/v1/systemone`,
the model to `d1-ultra`, and use your Liquid AI API key. For other providers, use
their documented model ID and endpoint. The endpoint, model, and key must all
refer to the same service.

Decision request token budgets use the bundled `o200k_base` encoding resource.
The first startup does not require a tokenizer download or a prepopulated cache.
Actual usage comes from the decision service's returned `usage`.

SQLite uses `<SAG_DATA_DIR>/sag.db`, defaulting to `.zleap/sag.db`. Server databases
use `SAG_RELATIONAL_HOST`, `PORT`, `USER`, `PASSWORD`, and `DATABASE`.
Connection pool, timeout, and PostgreSQL TLS settings also use `SAG_RELATIONAL_*`.
Default ports are 3306 for MySQL, 5432 for PostgreSQL, and 2881 for OceanBase.

The aliases `RELATIONAL_PROVIDER`, `DATA_DIR`, `DB_HOST`, `DB_PORT`, `DB_USER`,
`DB_PASSWORD`, `DB_NAME`, `DB_POOL_*`, `DB_MAX_OVERFLOW`, `DB_CONNECT_TIMEOUT`,
`DB_COMMAND_TIMEOUT`, and `DB_TLS_*` are compatible with SAG1 as well. A process
variable overrides the same name in the file. When equivalent names are both set,
`SAG_*` takes precedence; empty values are treated as unset.

You can reuse a SAG1 configuration file. SAG2 does not use its LLM, embedding,
vector database, or event settings; add `DECISION_*` settings for search. Without
any decision model configuration, parsing, chunking, reading, and pagination remain
available. Partial decision model configuration raises an explicit error during
configuration loading. You can also construct `EngineConfig` and
`RelationalConfig` directly; explicit configuration does not read environment variables.

### Searching existing SAG1 data

Load SAG1 connection settings with `EngineConfig.from_env(".env")`, add decision
model settings, and call `search()` or `search_page()` directly without first
calling `index()`. On startup, the engine detects `source_chunk`, preserves the
existing passage IDs, and reads `article` and `chat_conversation` for source
metadata. It respects active generations, deleted sources, and disabled data
sources. Both normal and lite relational text tables are supported, without
installing `zleap-sag` or accessing the original vector database or event tables.

This mode supports search, pagination, `read_chunk()`, `read_outline()`, and
`source_state()`. Existing SAG1 business tables are read-only. SAG1 continues to
manage writes, deletion, and durable processing tasks; these operations raise
`sag.read_only_storage` in SAG2, and `capabilities()` reports the available
operations. Startup creates auxiliary `sag2_state`, `sag2_search_sessions`, and `sag2_lex_*`
persistent positional-index tables, requiring the corresponding table-creation
permissions. Pagination writes session state; SAG1 and SAG2 pagination results
are not interchangeable.

Subsequent SAG1 writes refresh caches and expire old cursors, including ordinary
`index()` writes that do not update a manifest. To support this, every read and
cursor validation currently scans passages within the requested data sources and
computes a fingerprint of the visible text. This cost grows with the data in
scope. Migration from old SAG2 data to SAG1 is not provided.

Conversations and recording transcripts support chunk overlap using complete
units. For conversation or transcript output returned by `parse()`, use:

```python
from zleap.sag2 import ChunkOptions

chunk_set = await engine.chunk(
    parsed,
    ChunkOptions(strategy="overlap", max_tokens=800, overlap_tokens=100),
)
```

Each new chunk carries as many consecutive, complete trailing messages or
transcript units from the previous chunk as fit. Overlap does not exceed
`overlap_tokens` and leaves room for a new unit within `max_tokens`; counting
includes speaker labels and newlines. If a unit does not fit, overlap is reduced
or omitted rather than truncating the message. A single oversized unit remains
intact and may exceed `max_tokens`. Overlapping units preserve the original text,
references, and time ranges. `overlap_tokens` defaults to 0, meaning no overlap.
The default conversation time window and recording token window are unaffected.

`SearchOptions` controls candidate count, expansion terms, additional rounds, and
output count, with defaults of 100/20/2/10. Search failures raise exceptions;
retryable JEV errors allow at most four attempts.

Paginated search follows the `zleap-sag` calling pattern:

```python
from zleap.sag2 import SearchPageRequest

# request is a SearchRequest containing query, scope, and options.
page = await engine.search_page(SearchPageRequest(request=request, page_size=20))
for hit in page.result.chunks:
    print(hit.score, hit.content)
if page.next_cursor is not None:
    page = await engine.search_page(
        SearchPageRequest(cursor=page.next_cursor, cursor_request=request)
    )
```

The first call runs SAG2 and persists the results. Later pages do not call JEV
again and work across processes and restarts. The total result count is limited
by search `top_k`; the default page size is 50 and sessions expire after 300
seconds. A mismatched question or scope, or a tampered cursor, raises
`CursorInvalidError`. Expiration or changes to the relevant data sources raise
`CursorExpiredError`, requiring a new search. `maintain()` cleans up expired
sessions in bounded batches.

For long-document pagination, enable `EngineConfig(search_snapshot_format="references")`
only after upgrading every instance sharing the database. With `from_env()`, set
`SAG2_SEARCH_SNAPSHOT_FORMAT=references`. The default `inline` keeps writes readable by
older versions; both modes read inline and reference snapshots. Before reverting to old
readers, disable all reference writers, drain in-flight requests, and wait the maximum
TTL (3600 seconds) after the last reference write commits. See the upgrade and rollback
procedure in the API compatibility guide.

To specify a database explicitly, pass its provider and asynchronous connection
URL to `EngineConfig(relational=RelationalConfig(...))`. SQLite uses
`sqlite+aiosqlite:///...`; MySQL and OceanBase use `mysql+aiomysql://...`;
PostgreSQL uses `postgresql+asyncpg://...`. Supply credentials through your
application configuration.

Further details are available in the repository's
[architecture](https://github.com/Zleap-AI/zleap/blob/main/packages/sag2/docs/architecture.md),
[development and validation](https://github.com/Zleap-AI/zleap/blob/main/packages/sag2/docs/reproduction.md),
and [API compatibility](https://github.com/Zleap-AI/zleap/blob/main/packages/sag2/docs/api-compatibility.md)
documents. These are also included in the source distribution's `docs/` directory.

JEV defaults to the `stateful` payload format to share candidate context within
each batch. For compatibility or troubleshooting, set
`DECISION_PAYLOAD_STYLE=inline` or pass `JevConfig(payload_style="inline", ...)`.

### Persistent index APIs

The native SQLite, MySQL, PostgreSQL, and OceanBase stores share a persistent
positional inverted index. `sag2_lex_postings` uses `(term_key, chunk_id)` as its
primary key and stores positions for three fields, weighted term frequencies,
and body frequencies. SHA-256 term identifiers prevent database case or accent
collations from changing exact matching. SQL queries require CTEs and window
functions; MySQL requires version 8.0 or later. BM25, phrase matching, expansion,
and DPP use the package's shared rules, without native database FTS tokenization
or scoring.

Relational ingestion maintains postings in checkpoint transactions. Publication
switches the active version; deleted data leaves search immediately, and
`maintain()` reclaims retired versions. Searches lease immutable versions without
holding a database connection or global write lock while waiting for JEV. Leases
expire after five minutes and renew every minute. An expired lease fails the
query and requires a retry. Completion, failure, cancellation, and close release
leases; `maintain()` reclaims expired leases left by crashed processes.

Opening and searching an index does not reconstruct corpus-wide Python postings.
Client working memory depends on query terms, 256-row posting batches, candidate
counts, and returned original documents. A single original document still needs
memory for its text. Common terms can match long posting lists, and the database
still performs scope filtering, statistics, and sorting. No million-document
latency or SLA claim has been established. Expansion and DPP frequency statistics
use batched queries; expansion candidates share scoring scans. `LexicalSnapshot`
remains only as a small regression oracle and is not constructed by production
storage backends.

When reading an existing SAG1 database, business tables remain read-only and
auxiliary postings are persisted per original document. Legacy writes may not
update reliable revision counters, so search and cursor validation still scan
visible records in pages to detect changes, with sorting spilled to disk. Only
changed documents are reindexed. This compatibility read path is separate from
old SAG2 schema migration. Version `0.3.0` does not automatically migrate old
schemas or experimental indexes.

`SQLiteIndex` and `LanceIndex` are standalone, immutable passage-index APIs,
provided separately from the relational `DataEngine` command/lifecycle API. Each
passage is one scoring document, and `metadata` can carry source references.
Creation requires a new file or directory. Corpus changes require a fresh index;
incremental mutation is not provided. Both APIs accept `LancePassage`; SQLite does
not require LanceDB. In the examples, `scorer` is a configured `JevClient` or an
object implementing asynchronous `score()`.

#### SQLite example

```python
from pathlib import Path
from zleap.sag2 import SQLiteIndex, LancePassage


async def search_sqlite(scorer):
    passages = [
        LancePassage(
            title="Conversation",
            content="Alice adopted cats from Cedar Shelter.",
            source_id="session-1",
            metadata={"message_ids": ["m1"]},
        ),
    ]
    with SQLiteIndex.create(Path("example.sqlite"), passages, corpus_digest="revision-1") as index:
        assert index.check_integrity()
    with SQLiteIndex.open(Path("example.sqlite"), corpus_digest="revision-1") as index:
        return await index.search("Where did Alice adopt the cats?", scorer=scorer)
```

#### LanceDB example

Install `pip install 'zleap-sag2[lance]'`, or use `pip install '.[lance]'` from source.

```python
from pathlib import Path
from zleap.sag2 import LanceIndex, LancePassage


async def search_lance(scorer):
    passages = [
        LancePassage(
            title="Conversation",
            content="Alice adopted cats from Cedar Shelter.",
            source_id="session-1",
            metadata={"message_ids": ["m1"]},
        ),
    ]
    with LanceIndex.create(
        Path("example-lance-index"), passages, corpus_digest="revision-1"
    ) as index:
        original = index.get_passages([1])[1]
    with LanceIndex.open(Path("example-lance-index"), corpus_digest="revision-1") as index:
        return await index.search("Where did Alice adopt the cats?", scorer=scorer)
```

LanceDB tables persist postings, lengths, corpus frequencies, and source metadata.
BTree indexes select terms, statistics, and chunk IDs. Opening reads schemas and
counts only; searches use isolated caches and fetch postings in batches and only
the final selected passages. Construction statistics spill to a temporary disk
database, and common-term ranking retains bounded top-k heaps. Title phrases,
accent-name repair, and passage normalization follow the package's existing
rules. `metadata` preserves raw passage text and source references.
