Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: several adjustments
jinzhenje26aea2f263f
diff --git a/docs/next/architecture.md b/docs/next/architecture.mdindex 5199131b..5dee290c 100644--- a/docs/next/architecture.md+++ b/docs/next/architecture.md@@ -31,7 +31,7 @@ Tier 的产品语义以 [解析 Tier](tiers.md) 为准;本文只描述它们| 边界 | 选择 | 目的 ||------|------|------|-| CLI/MCP/桌面端 -> doclib | HTTP + JSON over Unix Domain Socket | 本地安全、低延迟、避免端口冲突 |+| CLI/MCP/桌面端 -> doclib | HTTP + JSON over UDS or TCP loopback | UDS 优先;Windows Python 无 UDS 时自动 fallback 到 TCP || doclib -> local parse-server | HTTP + JSON over TCP loopback | 进程隔离,允许 GPU 模型崩溃不拖垮 doclib || doclib 存储 | SQLite WAL + FTS5 | 零运维、单文件、支持全文检索 || 任务队列 | DB rows + timestamp lock | 无外部依赖,崩溃后可恢复 |@@ -41,7 +41,9 @@ Tier 的产品语义以 [解析 Tier](tiers.md) 为准;本文只描述它们| 通道 | 地址 | 用途 ||------|------|------|-| UDS | `$MINERU_HOME/doclib.sock` | CLI、MCP、桌面端访问 doclib |+| UDS | `$MINERU_HOME/doclib.sock` | CLI、MCP、桌面端访问 doclib,UDS 可用时默认启用 |+| TCP | `127.0.0.1:15980` | UDS 不可用时访问 doclib 的本地 fallback |+| endpoint discovery | `$MINERU_HOME/doclib.endpoint.json` | CLI / SDK 发现 doclib 实际可用 transport || TCP | `127.0.0.1:15981` | doclib 调用 local parse-server || TCP 随机端口 | `127.0.0.1:<random>` | P1 Web UI |@@ -291,6 +293,7 @@ ParseWorker 按 `tier`、`privacy` 和 parse-server 健康状态路由:```text~/.mineru/config.yaml+ doclib.endpoint.jsondoclib.sockdoclib.dbdoclib.logdiff --git a/docs/next/cli/mineru-e2e-test-cases.md b/docs/next/cli/mineru-e2e-test-cases.mdindex 46cd4e6d..6ae2fd62 100644--- a/docs/next/cli/mineru-e2e-test-cases.md+++ b/docs/next/cli/mineru-e2e-test-cases.md@@ -61,7 +61,7 @@~/mineru-e2e-test```-进入测试目录后,只需设置 `MINERU_HOME`,即可让默认配置文件(`$MINERU_HOME/config.yaml`)、DB、日志、UDS socket 和数据目录都落在测试目录中:+进入测试目录后,只需设置 `MINERU_HOME`,即可让默认配置文件(`$MINERU_HOME/config.yaml`)、DB、日志、endpoint discovery 文件、UDS socket(启用 UDS 时)和数据目录都落在测试目录中:```bashcd ~/mineru-e2e-test@@ -100,6 +100,7 @@ mineru --help- exit code = 0- 输出包含 `parse`、`read`、`scan`、`watch`、`search`、`find`、`list`、`show`、`server`、`config`、`invalidate`、`forget`、`cleanup`+- 输出包含 `telemetry`- 输出不包含 `mineru-kit`### CLI-002 子命令 help@@ -115,6 +116,7 @@ mineru search --helpmineru find --helpmineru list --helpmineru show --help+mineru telemetry --helpmineru server --helpmineru config --helpmineru invalidate --help@@ -199,7 +201,7 @@ mineru server start- exit code = 0- 如果已运行,输出包含 `already running`-- 如果未运行,输出包含 `started` 或 `Socket`+- 如果未运行,输出包含 `started`### SERVER-003 查询运行状态@@ -227,7 +229,8 @@ mineru server status --json- server 运行时 exit code = 0- 输出为 JSON 或等价结构化 server 状态-- 至少包含 running、socket、data_dir、队列或文档库统计中的若干字段+- 至少包含 `running`、`socket_path`、`tcp`、`data_dir`、队列或文档库统计中的若干字段+- `tcp` 字段至少包含 `enabled`、`host`、`port`### SERVER-005 重复启动 server@@ -258,10 +261,10 @@ mineru server status --json预期:- 两条 exit code = 0-- restart 输出包含 stopped/started、started、Socket 或等价生命周期信息+- restart 输出包含 stopped/started、started 或等价生命周期信息- status 输出为 JSON- JSON 表示 server 正在运行-- UDS/socket 路径仍落在测试 HOME 配置下+- `socket_path`、`data_dir`、`sqlite_path`、`log_path` 仍落在测试 HOME 配置下### SERVER-007 stop 后依赖 server 的命令报错可读@@ -294,9 +297,322 @@ mineru server status --json- exit code = 0- 输出为 JSON- `data_dir` 默认位于 `$MINERU_HOME/data`;若显式覆盖 `doclib.data_dir`,则返回该覆盖值-- socket/UDS 字段等价于 `MINERU_DOCLIB_UDS_PATH`,如果字段名为 `socket_path` 则不得为空+- `socket_path` 字段等价于 `MINERU_DOCLIB_UDS_PATH`,不得为空;即使当前 transport 是 TCP-only,也可以表示配置路径+- TCP 相关字段应位于 `tcp.enabled`、`tcp.host`、`tcp.port`- 日志相关字段或启动失败日志路径应落在 `MINERU_DOCLIB_LOG_PATH`+### SERVER-013 endpoint discovery 文件写入++前置: server 已启动。++命令:++```bash+cat "$MINERU_HOME/doclib.endpoint.json"+mineru server status --json+```++预期:++- endpoint 文件存在,且 stdout 可解析为 JSON+- endpoint JSON 至少包含 `version`、`pid`、`transports`+- `transports` 非空,每个 transport 均包含 `type`+- 默认 UDS 可用环境下,`transports` 至少包含 `{"type": "uds", "path": ...}`,且 path 位于测试 HOME+- 如果当前环境使用 TCP transport,则对应项包含 `{"type": "tcp", "base_url": "http://127.0.0.1:<port>"}`+- `mineru server status --json` 能通过 discovery 正常连接 server++### SERVER-014 TCP-only fallback++前置:++- 使用一个新的独立 `MINERU_HOME`,避免与主测试 server 冲突。+- 执行前保存主测试 HOME,例如 `MAIN_MINERU_HOME="$MINERU_HOME"`;执行结束后恢复 `MINERU_HOME="$MAIN_MINERU_HOME"`。+- 设置:++```bash+MAIN_MINERU_HOME="$MINERU_HOME"+export MINERU_HOME="$HOME/mineru-e2e-test-tcp"+export MINERU_DOCLIB_UDS_ENABLED=false+export MINERU_DOCLIB_TCP_ENABLED=true+export MINERU_DOCLIB_TCP_PORT=0+```++命令:++```bash+mineru server start+mineru server status --json+cat "$MINERU_HOME/doclib.endpoint.json"+mineru server stop+export MINERU_HOME="$MAIN_MINERU_HOME"+unset MINERU_DOCLIB_UDS_ENABLED MINERU_DOCLIB_TCP_ENABLED MINERU_DOCLIB_TCP_PORT+```++预期:++- start exit code = 0+- status JSON 中 `running=true`+- status JSON 中 `tcp.enabled=true`+- status JSON 中 `tcp.host=127.0.0.1`+- status JSON 中 `tcp.port` 是大于 0 的实际端口,不应为 0+- endpoint JSON 的 `transports` 只需包含 TCP transport,`base_url` 端口必须等于 status JSON 的 `tcp.port`+- stop exit code = 0+- stop 后 `$MINERU_HOME/doclib.endpoint.json` 被清理,或后续 `mineru server status --json` 返回 `running=false`++### SERVER-015 endpoint stale 清理++前置:++- 使用独立 `MINERU_HOME`。+- 执行前保存主测试 HOME,例如 `MAIN_MINERU_HOME="$MINERU_HOME"`;执行结束后恢复 `MINERU_HOME="$MAIN_MINERU_HOME"`。+- 手工写入一个 stale `$MINERU_HOME/doclib.endpoint.json`,内容指向不存在的本地 TCP 端口。++命令:++```bash+MAIN_MINERU_HOME="$MINERU_HOME"+export MINERU_HOME="$HOME/mineru-e2e-test-stale-endpoint"+mkdir -p "$MINERU_HOME"+cat > "$MINERU_HOME/doclib.endpoint.json" <<'JSON'+{"version":1,"pid":999999,"transports":[{"type":"tcp","base_url":"http://127.0.0.1:9"}]}+JSON+mineru server status --json+mineru server stop+export MINERU_HOME="$MAIN_MINERU_HOME"+```++预期:++- status exit code = 0+- status JSON 返回 `running=false`,不因 stale endpoint 输出 Python traceback+- stop exit code = 0+- stop 输出 `Server is not running` 或等价信息+- stop 后 stale endpoint 文件被 best-effort 清理++## 4A. Telemetry 命令++### TELEMETRY-001 telemetry help++命令:++```bash+mineru telemetry --help+mineru telemetry status --help+mineru telemetry enable --help+mineru telemetry disable --help+mineru telemetry preview --help+mineru telemetry flush --help+```++预期:++- 每条 exit code = 0+- 输出包含 usage 或 options 类帮助信息+- `mineru telemetry --help` 输出包含 `status`、`enable`、`disable`、`preview`、`flush`+- 不触发 telemetry 首次选择 prompt+- 不包含 Python traceback++### TELEMETRY-002 status JSON 结构++前置: server 正在运行。++命令:++```bash+mineru telemetry status --json+```++预期:++- exit code = 0+- stdout 为可直接解析的 JSON+- JSON 包含 `state`、`installation_id`、`pending_periods`、`pending_metrics`+- `state` 取值为 `unset`、`enabled` 或 `disabled`+- `installation_id` 为非空字符串+- `pending_periods` 和 `pending_metrics` 为非负整数+- telemetry status 命令自身不触发首次选择 prompt+- 不包含 Python traceback++### TELEMETRY-003 preview JSON 结构++前置: server 正在运行。++命令:++```bash+mineru telemetry preview+```++预期:++- exit code = 0+- stdout 为可直接解析的 JSON+- JSON 为下一次外部 telemetry HTTP 请求 body 的预览,不额外包 CLI metadata+- JSON 包含 `api_version`、`schema_version`、`batch_id`、`installation_id`、`period_start`、`period_end`、`context`、`metrics`+- `installation_id` 与 TELEMETRY-002 的 `installation_id` 一致+- `metrics` 为数组;没有待上报数据时允许为空数组+- preview 不触发 flush,不要求外网可用+- 不包含 Python traceback++### TELEMETRY-004 enable / disable 与 installation_id 稳定性++前置: server 正在运行。++命令:++```bash+mineru telemetry status --json+mineru telemetry enable --json+mineru telemetry status --json+mineru telemetry disable --json+mineru telemetry status --json+```++预期:++- 每条 exit code = 0+- 每条 stdout 为可直接解析的 JSON+- enable 返回后,后续 status 的 `state` 为 `enabled`+- disable 返回后,后续 status 的 `state` 为 `disabled`+- 全流程中 `installation_id` 保持不变+- enable/disable 命令自身不触发首次选择 prompt+- 不包含 Python traceback++### TELEMETRY-005 disabled 时不新增聚合++前置: server 正在运行。++命令:++```bash+mineru telemetry disable --json+mineru search "mineru-e2e-query-that-should-not-exist" --limit 1 --json+mineru telemetry preview+```++预期:++- 三条 exit code = 0+- search stdout 为可直接解析的 JSON,允许结果为空+- preview stdout 为可直接解析的 JSON+- preview JSON 中 `metrics` 为空数组,或至少不包含本次 search 产生的 `search.request.count`、`search.finished.count`、`search.duration_bucket.count`、`search.results_bucket.count`+- 不包含 Python traceback++### TELEMETRY-006 unset 或 disabled 时 flush 不外发++前置: server 正在运行;如果当前状态不是 `disabled`,先执行 `mineru telemetry disable --json`。++命令:++```bash+mineru telemetry flush --json+```++预期:++- exit code = 0+- stdout 为可直接解析的 JSON+- JSON 中 `action` = `flush`+- JSON 中 `executed` = `false`+- JSON 中 `reason` = `telemetry_not_enabled`+- 不要求外网可用+- 不包含 Python traceback++### TELEMETRY-007 enabled 时 preview 可观察业务聚合++前置: server 正在运行。++命令:++```bash+mineru telemetry enable --json+mineru search "mineru-e2e-query-that-should-not-exist" --limit 1 --json+mineru telemetry preview+```++预期:++- 三条 exit code = 0+- search stdout 为可直接解析的 JSON,允许结果为空+- preview stdout 为可直接解析的 JSON+- preview JSON 中 `metrics` 包含 `search.request.count`+- preview JSON 中应包含 `search.finished.count` 和 `search.duration_bucket.count`+- 如果 search 正常返回,`search.finished.count` 的 status 维度为 `succeeded`+- `metrics` 中不得包含 query 原文 `mineru-e2e-query-that-should-not-exist`+- 不包含 Python traceback++### TELEMETRY-008 enabled flush 行为++前置: 已执行 TELEMETRY-007,且 preview 中有待上报 metrics。++命令:++```bash+mineru telemetry flush --json+mineru telemetry preview+```++预期分支:++- 如果外部 telemetry endpoint 可访问且接收成功:+ - flush exit code = 0+ - flush JSON 中 `action` = `flush`+ - flush JSON 中 `flush_result.status` 为 `success` 或 `partial_success`+ - 后续 preview 中已成功发送 period 的 metrics 被清除或减少+- 如果外部 telemetry endpoint 不可访问、超时或返回 5xx:+ - flush exit code = 0+ - flush JSON 中 `flush_result.status` 为 `failed`、`partial_success` 或等价重试状态+ - 后续 preview 可保留待上报 metrics+- 两个分支都不应输出外部 endpoint response body+- 两个分支都不应包含 Python traceback++### TELEMETRY-009 首次交互式 prompt++前置:++- 使用全新的 `MINERU_HOME`,server 已启动,且 `mineru telemetry status --json` 返回 `state=unset`。+- 本用例必须在真实交互式终端执行;如果执行 Agent 只能非交互执行命令,可标记 BLOCKED。++命令:++```bash+mineru search "mineru-e2e-query-that-should-not-exist" --limit 1+```++操作与预期:++- 命令进入业务执行前提示是否开启匿名聚合 telemetry+- prompt 文案不得包含文件路径、query、文档内容或其它业务输入+- 输入 Enter、`y` 或 `yes` 后,命令继续执行,后续 `mineru telemetry status --json` 返回 `state=enabled`+- 在另一轮全新 `MINERU_HOME` 中输入 `n` 或 `no` 后,命令继续执行,后续 `mineru telemetry status --json` 返回 `state=disabled`+- `mineru telemetry ...`、`mineru server ...`、`mineru config ...` 命令自身不触发 prompt+- 不包含 Python traceback++### TELEMETRY-010 preview 隐私边界++前置: server 正在运行,telemetry 已启用。++命令:++```bash+mineru telemetry enable --json+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --wait 60 --json+mineru search "mineru-e2e-query-that-should-not-exist" --limit 1 --json+mineru telemetry preview+```++预期:++- 前三条业务命令 exit code = 0;如果 parse 因环境缺少 flash 能力失败,可记录失败分支,但仍继续检查 preview 隐私边界+- preview exit code = 0,stdout 为可直接解析的 JSON+- preview JSON 不包含:+ - `$MINERU_E2E_FIXTURE_DIR`+ - `sample.pdf`+ - `mineru-e2e-query-that-should-not-exist`+ - Markdown 正文、snippet、页面文本、traceback+ - API key、secret、配置对象原文+- preview JSON 中允许出现 metric name、低基数字段、bucket、status、tier、source、caller、installation_id 和粗粒度环境 context+## 5. Config 命令### CONFIG-001 查看配置@@ -2705,7 +3021,9 @@ mineru server status执行方式:-- 人工制造一个不会成功建立 UDS 的 server 启动环境,例如把 `MINERU_DOCLIB_UDS_PATH` 指向一个父目录不存在且不可创建的位置。+- 人工制造一个不会成功建立任何 local transport 的 server 启动环境。可选方式:+ - 设置 `MINERU_DOCLIB_UDS_ENABLED=false` 且 `MINERU_DOCLIB_TCP_ENABLED=false`。+ - 或显式设置 `MINERU_DOCLIB_UDS_ENABLED=true`,并把 `MINERU_DOCLIB_UDS_PATH` 指向一个父目录不存在且不可创建的位置。- 只允许通过环境变量制造失败,不直接修改数据库或内部状态。命令:@@ -2749,13 +3067,16 @@ mineru server start- SERVER-006 restart server- SERVER-007 stop 后依赖 server 的命令报错可读- SERVER-009 环境变量路径生效+- SERVER-013 endpoint discovery 文件写入+- SERVER-014 TCP-only fallback+- SERVER-015 endpoint stale 清理- SERVER-012 error summary 与 recent logs- SERVER-010 停止 server执行要求:- SERVER-011 必须仍作为整套测试最后一个 case 执行,不放入本批次中间。-- stop/restart 后必须恢复 server,避免影响后续批次。+- stop/restart 或独立 `MINERU_HOME` transport 测试后必须恢复主测试 server,避免影响后续批次。### COVERAGE-003 config 普通文本与错误分支补充@@ -2973,6 +3294,30 @@ mineru server start- server restart 后配置仍可读取- rule hit_count 或等价统计在 scan 后体现规则被使用+### COVERAGE-014 telemetry 补充++必跑 case:++- TELEMETRY-001 telemetry help+- TELEMETRY-002 status JSON 结构+- TELEMETRY-003 preview JSON 结构+- TELEMETRY-004 enable / disable 与 installation_id 稳定性+- TELEMETRY-005 disabled 时不新增聚合+- TELEMETRY-006 unset 或 disabled 时 flush 不外发+- TELEMETRY-007 enabled 时 preview 可观察业务聚合+- TELEMETRY-008 enabled flush 行为+- TELEMETRY-010 preview 隐私边界++条件必跑 case:++- TELEMETRY-009 首次交互式 prompt:仅在执行 Agent 能使用真实交互式终端时必跑;否则标记 BLOCKED,并说明执行环境不支持交互输入。++执行要求:++- telemetry E2E 只能通过 `mineru telemetry ...` 和其它 `mineru` 业务命令观察结果,不得直接读取 SQLite 或调用内部 API。+- 外部 telemetry endpoint 不可用时,flush 用例按失败/保留待上报数据分支判定,不应因此整体失败。+- 所有 preview 隐私边界检查必须确认不包含路径、文件名、query、snippet、正文、traceback 或 API key。+## 19. 最终报告格式执行 Agent 最终必须按以下格式汇总:diff --git a/docs/next/cli/mineru-server.md b/docs/next/cli/mineru-server.mdindex bc1a8de8..1e8211cb 100644--- a/docs/next/cli/mineru-server.md+++ b/docs/next/cli/mineru-server.md@@ -31,16 +31,18 @@4. 创建 services。5. managed 模式下拉起 local parse-server。6. 启动 watch、ingest、parse、health check、device monitor 和 compaction。-7. 通过 UDS 提供本地 HTTP + JSON 协议。+7. 通过 UDS 或 TCP loopback 提供本地 HTTP + JSON 协议。-默认情况下,UDS socket 位于 `$MINERU_HOME/doclib.sock`。如需覆盖,可设置 `doclib.uds.path` 或环境变量 `MINERU_DOCLIB_UDS_PATH`。+默认情况下,UDS 可用时使用 `$MINERU_HOME/doclib.sock`;UDS 不可用时自动启用 TCP loopback fallback。server 启动成功后会写入 `$MINERU_HOME/doclib.endpoint.json`,供 CLI / SDK 发现实际 endpoint。++如需覆盖,可设置 `doclib.uds.*` / `doclib.tcp.*` 或对应环境变量,例如 `MINERU_DOCLIB_UDS_PATH`、`MINERU_DOCLIB_TCP_PORT`。关闭时:1. 停止后台任务。2. managed 模式下停止 local parse-server。3. 关闭数据库资源。-4. 删除 socket 文件。+4. 删除 socket 文件和 endpoint discovery 文件。## 4. 状态输出@@ -58,9 +60,9 @@- `log_path`- `version`- `python_version`-- `http.enabled`-- `http.host`-- `http.port`+- `tcp.enabled`+- `tcp.host`+- `tcp.port`- `files_total`- `docs_total`- `parse_queue_length`@@ -115,7 +117,7 @@人类可读输出应至少展示:- Server 进程与 uptime-- `MINERU_HOME`、UDS、HTTP、SQLite、log、data 路径+- `MINERU_HOME`、UDS、TCP、SQLite、log、data 路径- 文件、文档、队列、watch、scan 摘要- SQLite 基础信息- worker 运行状态与 worker 数量diff --git a/docs/next/cli/mineru.md b/docs/next/cli/mineru.mdindex 3b9b29ed..4de9b663 100644--- a/docs/next/cli/mineru.md+++ b/docs/next/cli/mineru.md@@ -36,6 +36,7 @@```text~/.mineru/config.yaml+ doclib.endpoint.jsondoclib.sockdoclib.dbdoclib.log@@ -44,6 +45,8 @@temp/```+`doclib.endpoint.json` 记录当前本地 doclib server 实际可用的 transport。UDS 可用时通常会有 `doclib.sock`;在 Windows Python runtime 不支持 UDS 时,doclib 可以只通过 TCP loopback 工作,此时不要求存在可用 socket 文件。+`doclib.db` 记录文件路径、文档 SHA256、解析任务、缓存状态、FTS 索引、watch 目录和配置。详细数据模型见 [系统架构](../architecture.md)。## 4. 处理模型diff --git a/docs/next/config.md b/docs/next/config.mdindex bede6de2..f93a4eb6 100644--- a/docs/next/config.md+++ b/docs/next/config.md@@ -37,16 +37,18 @@ MinerU 有两类配置:| 分组 | 字段 | 默认值 | 说明 ||------|------|--------|------|+| UDS | `doclib.uds.enabled` | `auto` | `auto` / `true` / `false`;`auto` 时当前 Python runtime 支持 UDS 则启用,否则关闭 || UDS | `doclib.uds.path` | `~/.mineru/doclib.sock` | CLI / doclib 通信 socket,默认取 `$MINERU_HOME/doclib.sock` || UDS | `doclib.uds.permission` | `0o600` | socket 权限 |-| HTTP | `doclib.http.enabled` | `False` | 是否启用 TCP HTTP |-| HTTP | `doclib.http.host` | `127.0.0.1` | TCP 监听地址 |-| HTTP | `doclib.http.port` | `15980` | TCP 监听端口 |-| HTTP | `doclib.http.strict_port` | `False` | 端口占用时是否报错 |-| HTTP | `doclib.http.backlog` | `128` | socket backlog |-| HTTP | `doclib.http.timeout` | `600` | keep-alive timeout |+| TCP | `doclib.tcp.enabled` | `auto` | `auto` / `true` / `false`;`auto` 时 UDS 不可用则启用,作为 Windows fallback |+| TCP | `doclib.tcp.host` | `127.0.0.1` | TCP 监听地址 |+| TCP | `doclib.tcp.port` | `15980` | TCP 监听端口 |+| TCP | `doclib.tcp.strict_port` | `False` | 端口占用时是否报错 |+| TCP | `doclib.tcp.backlog` | `128` | socket backlog |+| TCP | `doclib.tcp.timeout` | `600` | keep-alive timeout || log | `doclib.log.path` | `~/.mineru/doclib.log` | 日志路径 || log | `doclib.log.level` | `info` | 日志级别 |+| doclib | `doclib.endpoint_path` | `~/.mineru/doclib.endpoint.json` | 当前 server 实际可用 endpoint discovery 文件 || doclib | `doclib.data_dir` | `~/.mineru/data` | 数据目录,默认取 `$MINERU_HOME/data`,但仍可通过配置文件或环境变量覆盖 || doclib | `doclib.ingest_workers` | `2` | ingest worker 数 || doclib | `doclib.parse_workers` | `2` | parse worker 数 |@@ -68,6 +70,8 @@ MinerU 有两类配置:| sqlite | `doclib.sqlite.temp_store` | `memory` | temp store || sqlite | `doclib.sqlite.synchronous` | `NORMAL` | synchronous pragma |+`doclib.uds.enabled` 和 `doclib.tcp.enabled` 是 `auto | true | false` 配置项。默认值为 `auto`。当前第一版只在启动前解析 `auto`: UDS 可用则启用 UDS、关闭 TCP;UDS 不可用则关闭 UDS、启用 TCP loopback。用户显式配置 `true` / `false` 时,server 尊重该配置。+这些配置影响 doclib 如何启动,因此不能依赖 `mineru config` 读取。### 2.2 运行时配置@@ -99,7 +103,7 @@ SDK client 显式参数属于当前调用方传入的请求上下文;当它最如果一个配置会改变隐私边界,例如启用远端上传,必须要求当前请求或规则显式允许,不能只因为全局配置存在 remote URL 或 API Key 就上传文档。-启动前配置只用于必须在 doclib 初始化前确定的字段,比如 UDS 路径、DB 路径、SQLite pragma。它不与 SQLite 配置定义同一 key,也不在 doclib 启动后被 SQLite 覆盖。`MINERU_HOME` 属于 bootstrap 层,负责默认 home 与默认配置文件位置;`doclib.data_dir` 是独立配置项,默认取 `$MINERU_HOME/data`。+启动前配置只用于必须在 doclib 初始化前确定的字段,比如 UDS/TCP transport、endpoint discovery 路径、DB 路径、SQLite pragma。它不与 SQLite 配置定义同一 key,也不在 doclib 启动后被 SQLite 覆盖。`MINERU_HOME` 属于 bootstrap 层,负责默认 home 与默认配置文件位置;`doclib.data_dir` 是独立配置项,默认取 `$MINERU_HOME/data`。## 4. 运行时 KV 配置diff --git a/docs/next/decisions/0020-doclib-schema-stability-boundary.md b/docs/next/decisions/0020-doclib-schema-stability-boundary.mdindex 24b78259..7e21226a 100644--- a/docs/next/decisions/0020-doclib-schema-stability-boundary.md+++ b/docs/next/decisions/0020-doclib-schema-stability-boundary.md@@ -60,7 +60,7 @@ v1 稳定 schema 绑定的是 **doclib public models 的字段**,而不是 SQL- `WatchStats`- `ErrorBucket`- `ErrorSummary`-- `HTTPServerStatus`+- `TCPServerStatus`- `WorkerStatus`- `LocalParseServerStatus`- `RemoteParseServerStatus`diff --git a/docs/next/decisions/0021-doclib-local-transport-discovery.md b/docs/next/decisions/0021-doclib-local-transport-discovery.mdnew file mode 100644index 00000000..12c76bff--- /dev/null+++ b/docs/next/decisions/0021-doclib-local-transport-discovery.md@@ -0,0 +1,283 @@+# ADR-0021: Doclib 本地 Transport 与 Endpoint Discovery++状态: Accepted+日期: 2026-06-22+相关文档: ../architecture.md, ../config.md, ../cli/mineru-server.md, ../sdk/doclib-client.md++## 背景++doclib server 是本地常驻进程,服务 CLI、SDK、MCP、桌面端和未来 Web UI。当前实现默认通过 Unix domain socket 连接 doclib,同时可以额外启用 TCP listener。++这个模型在 macOS 和 Linux 上工作良好,但面向 Windows 用户时存在风险:++- Windows 版本本身可能支持 Unix domain socket,但用户安装的 Python distribution build 未必启用 `socket.AF_UNIX`。+- 当前配置在 import 阶段就会计算默认 UDS path,如果 UDS 不可用可能导致 CLI / SDK 在启动前失败。+- 当前 server 启动时无条件 bind UDS,不能只使用 TCP。+- 当前 client 默认只使用 UDS,无法自动切换到 TCP。+- TCP 端口可能因为占用而 fallback 到随机端口,client 需要一种稳定方式发现实际 endpoint。++为了面向 Windows 用户大规模推广,doclib 不能要求用户电脑上的 Python 一定支持 UDS。需要将 UDS 从“必需 transport”调整为“优先 transport”,并提供跨平台 fallback。++## 决策++doclib 本地连接采用 “UDS 优先,TCP loopback 自动兜底” 的策略。++### 配置命名++将启动前配置中的 `doclib.http` 改名为 `doclib.tcp`。不兼容旧配置项,因为当前仍处于第一版实现阶段。++原因:++- UDS 和 TCP 上运行的都是 HTTP + JSON 协议。+- `http.enabled` 容易被误解为是否启用 HTTP API。+- 该配置实际控制的是 TCP listener,命名为 `tcp` 与 `uds` 对称。++配置结构:++```yaml+doclib:+ uds:+ enabled: true+ path: ~/.mineru/doclib.sock+ permission: 0o600+ tcp:+ enabled: false+ host: 127.0.0.1+ port: 15980+ strict_port: false+ backlog: 128+ timeout: 600+```++### 默认启用规则++`enabled` 字段继续使用 `bool`,不引入字符串三态,也不使用 `None` 表示 auto。++`doclib.uds.enabled` 和 `doclib.tcp.enabled` 的配置类型为 `auto | true | false`,默认值均为 `auto`。当前第一版只在启动前解析 `auto`,不在 UDS bind 失败后继续 fallback:++- 如果当前 Python runtime 支持 UDS:+ - `doclib.uds.enabled=auto` 解析为 `true`+ - `doclib.tcp.enabled=auto` 解析为 `false`+- 如果当前 Python runtime 不支持 UDS:+ - `doclib.uds.enabled=auto` 解析为 `false`+ - `doclib.tcp.enabled=auto` 解析为 `true`++用户显式配置 `true` / `false` 时,server 尊重用户配置。++如果用户显式或默认结果导致 UDS 和 TCP 都关闭,server 启动失败,并提示至少需要启用一个 local transport。++如果用户显式启用 UDS,但当前 Python runtime 不支持 UDS,server 启动失败,并提示可以关闭 UDS 或启用 TCP。++### UDS path 不再承担能力检测++默认 UDS path 始终可以计算:++```text+$MINERU_HOME/doclib.sock+```++`_default_uds_path()` 不再因为 UDS 不可用而抛错。UDS 能力检测只影响 `uds.enabled=auto` 和 `tcp.enabled=auto` 的启动前解析结果,以及 server 启动时的 bind 逻辑。++### TCP listener++TCP 第一版只作为本地 loopback transport:++- 默认 host 为 `127.0.0.1`。+- 默认 port 为 `15980`。+- `strict_port=false` 时,如果默认端口被占用,server 可以绑定随机可用端口。+- 实际端口通过 endpoint discovery 文件暴露给 client。++如果用户显式配置非 loopback host,第一版允许,但视为高级配置。第一版不额外实现 token 或远程访问防护。++### Endpoint discovery 文件++server 启动成功后写入:++```text+$MINERU_HOME/doclib.endpoint.json+```++该文件描述当前 server 实例可用的本地连接方式。++示例:++```json+{+ "version": 1,+ "pid": 12345,+ "transports": [+ {+ "type": "uds",+ "path": "/Users/me/.mineru/doclib.sock"+ },+ {+ "type": "tcp",+ "base_url": "http://127.0.0.1:15980"+ }+ ]+}+```++规则:++- 只写入实际成功绑定的 transports。+- TCP 使用随机端口时,`base_url` 必须写入真实端口。+- 文件写入应使用 atomic write: 先写临时文件,再 `replace`。+- server shutdown / stop 时 best-effort 删除该文件。+- stale endpoint 文件不能被视为 server 一定运行;client 连接失败后仍应报 `ServerNotRunningError`。++### Client 连接策略++`DoclibClient()` 默认走 endpoint resolver,而不是固定使用 UDS。++公开构造参数调整为:++```python+class DoclibClient:+ def __init__(+ self,+ *,+ endpoint_path: str | Path | None = None,+ socket_path: str | Path | None = None,+ base_url: str | None = None,+ timeout: int = 60,+ api_prefix: str = "/api/v1",+ ) -> None: ...+```++参数语义:++- `endpoint_path`: endpoint discovery 文件路径。默认 `None` 表示 `$MINERU_HOME/doclib.endpoint.json`。+- `socket_path`: 显式指定 UDS path。传入后不读取 endpoint discovery。+- `base_url`: 只表示 TCP 模式下的真实 base URL,例如 `http://127.0.0.1:15980`。不再承担 UDS dummy URL 的公开语义。+- `timeout`: HTTP client timeout。+- `api_prefix`: doclib API path prefix。++`socket_path` 和 `base_url` 都是显式 endpoint override,不能同时传入;如果同时传入,client 应抛出 `ValueError`。++UDS 模式下 httpx 仍然需要一个 base URL。这个 dummy URL 使用内部常量,例如:++```python+DOCLIB_UDS_BASE_URL = "http://mineru"+```++普通用户不需要关心该常量。++默认连接顺序:++1. 如果调用方显式传入 `socket_path`,使用该 UDS path。+2. 如果调用方显式传入 `base_url`,使用该 TCP endpoint。+3. 否则读取 `$MINERU_HOME/doclib.endpoint.json`。+4. endpoint 中同时存在 UDS 和 TCP 时,优先尝试 UDS。+5. UDS 不存在、不可用或连接失败时,尝试 TCP。+6. endpoint 不存在时,可以根据当前 config 推导默认 UDS / TCP endpoint 作为 fallback。+7. 所有候选 endpoint 都失败时,抛 `ServerNotRunningError`。++CLI 的 `server status`、`server stop` 和业务命令都应使用同一套 resolver,不再依赖 socket 文件是否存在判断 server 是否运行。++### Server status++状态模型中的 `http` 字段改为 `tcp`,CLI human-readable 输出也显示 `TCP`。++`server status --json` 应继续返回:++- `socket_path`: UDS path,可能为空或仅表示配置 path。+- `tcp.enabled`+- `tcp.host`+- `tcp.port`++其中 `tcp.port` 表示实际绑定端口;如果 TCP 未启用则为 `null`。++### 本地 TCP 不实现 token++第一版本地 TCP 不实现 token,不写入 token,不要求 client 携带 token header。++安全边界由以下约束提供:++- 默认只监听 `127.0.0.1`。+- 本地 doclib 主要面向同一用户会话内的 CLI / SDK / Agent。+- 非 loopback host 需要用户显式配置,属于高级使用场景。++后续如果要支持更开放的本地服务场景,可以在新 ADR 中讨论 token、mTLS、系统凭据或 named pipe。++## 替代方案++### 方案 A: 继续要求 UDS++拒绝。Windows 用户的 Python distribution build 不一定启用 `AF_UNIX`,要求 UDS 会让 CLI / SDK 在部分 Windows 环境下不可用。++### 方案 B: 将 `enabled` 改为字符串三态++示例:++```python+Literal["auto", "enabled", "disabled"]+```++拒绝。它能明确表达 auto,但会改变现有配置字段类型,用户配置也更啰嗦。第一版只需要“未配置时自动选择,显式配置时尊重用户”,用 bool + default factory 足够。++### 方案 C: 使用 `bool | None` 表示 auto++示例:++```python+enabled: bool | None = None+```++拒绝。它保留字段名,但 `None` 的业务语义不够自解释,后续实现容易在多个调用点散落 `is None` 判断。第一版选择把 auto 收敛到默认值生成逻辑中。++### 方案 D: Windows 使用 Named Pipe++暂不采用。Named Pipe 的安全属性更接近 UDS,但当前 doclib 基于 uvicorn / httpx 的 HTTP transport 实现,Named Pipe 会引入较多平台特化代码。TCP loopback fallback 成本更低,覆盖面更好。++### 方案 E: 本地 TCP 强制 token++暂不采用。token 可以降低本机低成本误连或误发风险,但也会增加 endpoint 文件、client header、调试和文档复杂度。第一版先限制默认 host 为 `127.0.0.1`,不实现 token。++## 影响++配置影响:++- `doclib.http.*` 改为 `doclib.tcp.*`。+- 环境变量从 `MINERU_DOCLIB_HTTP_*` 改为 `MINERU_DOCLIB_TCP_*`。+- 不兼容旧配置项。++Server 影响:++- server 启动时按 `uds.enabled` 和 `tcp.enabled` 分别创建 socket。+- server 允许只启 TCP。+- server 写入并清理 `doclib.endpoint.json`。+- UDS 不可用不再导致 config import 失败。++Client / CLI 影响:++- `DoclibClient()` 默认使用 endpoint resolver。+- CLI 不再用 socket 文件存在性判断 server 运行状态。+- `server status`、`server stop`、业务命令使用同一套连接发现逻辑。++文档影响:++- 更新 architecture / config / server CLI / SDK 文档中的 UDS-only 描述。+- 明确 UDS 与 TCP 都承载 HTTP + JSON 协议。+- 明确 Windows fallback 行为。++测试影响:++- 增加 UDS 可用时默认只启 UDS 的配置测试。+- 增加 UDS 不可用时默认启 TCP 的配置测试。+- 增加 server 只启 TCP 的启动测试。+- 增加 endpoint 文件写入、随机端口写入、shutdown 清理测试。+- 增加 client resolver 优先 UDS、fallback TCP、stale endpoint 失败测试。+- 更新 `MINERU_DOCLIB_HTTP_*` 相关测试为 `MINERU_DOCLIB_TCP_*`。++## 后续动作++1. 修改配置模型: `HTTPConfig` 改为 `TCPConfig`,`DoclibConfig.http` 改为 `DoclibConfig.tcp`。+2. 为 `UDSConfig` 和 `TCPConfig` 使用 `auto | true | false` 类型,默认值为 `auto`,并在启动时解析为布尔值。+3. 移除 `_default_uds_path()` 中的 UDS 能力检测和异常。+4. 修改 server bind 逻辑,允许 UDS / TCP 独立启用。+5. 实现 `$MINERU_HOME/doclib.endpoint.json` 的 atomic write 和 cleanup。+6. 实现 `DoclibClient` endpoint resolver。+7. 修改 CLI server lifecycle 使用 resolver。+8. 修改 status schema 和 CLI 输出: `http` -> `tcp`。+9. 更新文档和 E2E 测试用例。diff --git a/docs/next/decisions/README.md b/docs/next/decisions/README.mdindex d315fb8c..c82478a7 100644--- a/docs/next/decisions/README.md+++ b/docs/next/decisions/README.md@@ -48,6 +48,7 @@| [ADR-0018](0018-mineru-kit-vlm-server-command.md) | Accepted | MinerU Kit VLM Server Command || [ADR-0019](0019-mineru-kit-models-command.md) | Accepted | MinerU Kit Models Command || [ADR-0020](0020-doclib-schema-stability-boundary.md) | Accepted | Doclib Schema Stability Boundary |+| [ADR-0021](0021-doclib-local-transport-discovery.md) | Accepted | Doclib 本地 Transport 与 Endpoint Discovery |## 模板diff --git a/docs/next/open-questions.md b/docs/next/open-questions.mdindex 04bc07f2..8ef7df2f 100644--- a/docs/next/open-questions.md+++ b/docs/next/open-questions.md@@ -63,7 +63,7 @@| Tool SDK `server_url` | Tool SDK 的 PDF VLM / hybrid parser 可以保留 `server_url` 作为 parser-layer 高级 backend 参数;API-backed parser 使用 `api_url`。 || `MinerUApiParser` 位置 | API-backed parser 保持现状,公开入口继续使用 `from mineru.parser import MinerUApiParser`;不重命名,不移动到 `mineru.parser.remote`。 || `ParseResult` backend 字段 | `ParseResult` 不再持有 `_backend` / `_version_name`;backend 仅允许作为 page / middle-json 内部来源信息存在。 |-| 其他语言 SDK | 其他语言 SDK 暂无开发计划;如果未来开发,只覆盖 v1 Unified API,不覆盖本地 doclib UDS 能力。 |+| 其他语言 SDK | 其他语言 SDK 暂无开发计划;如果未来开发,只覆盖 v1 Unified API,不覆盖本地 doclib transport discovery 能力。 || `mineru server status` | `mineru server status` 使用 doclib `ServerStatusResponse`,不与 parse-server `/v1/health` 强行对齐;后续只需决定该 JSON schema 的稳定发布边界。 || doclib schema 稳定边界 | 稳定的是 doclib public models,不是 SQLite 表结构;稳定性分为 `core stable`、`operational stable` 和 `diagnostic / internal`,详见 [ADR-0020](decisions/0020-doclib-schema-stability-boundary.md)。 || `mineru-kit` 对外暴露 | `mineru-kit` 保留为专家工具入口;Agent 默认入口是 `mineru`,skill 不主动暴露 `mineru-kit`。 |diff --git a/docs/next/sdk.md b/docs/next/sdk.mdindex 47e953e8..f56d9895 100644--- a/docs/next/sdk.md+++ b/docs/next/sdk.md@@ -41,4 +41,4 @@ SDK 文档定义代码集成入口。它既要让普通开发者知道如何解- SDK 默认遵守隐私优先,不隐式上传本地文件到远端。- Tool SDK 不依赖 doclib;doclib 可以依赖 Tool SDK。- 对外 API 层应避免 import 时加载重依赖。-- 其他语言 SDK 暂无开发计划;如果未来开发,只覆盖 v1 Unified API,不覆盖本地 doclib UDS 能力。+- 其他语言 SDK 暂无开发计划;如果未来开发,只覆盖 v1 Unified API,不覆盖本地 doclib transport discovery 能力。diff --git a/docs/next/sdk/README.md b/docs/next/sdk/README.mdindex 8fd1a474..2bb018d1 100644--- a/docs/next/sdk/README.md+++ b/docs/next/sdk/README.md@@ -21,9 +21,9 @@- API-backed Parser 是无状态 API client。- Doclib SDK 是有状态本地文档库 client。-Doclib SDK 与 doclib HTTP/UDS API 使用同一套方法和协议语义。项目内部除 `mineru.doclib.client` 外,不应直接通过 HTTP 调用 doclib API;外部客户端未来可以直接依赖 doclib HTTP API。+Doclib SDK 与 doclib 本地 HTTP + JSON API 使用同一套方法和协议语义。doclib 本地 API 可以运行在 UDS 或 TCP loopback transport 上,Python client 默认通过 `$MINERU_HOME/doclib.endpoint.json` 发现实际 endpoint。项目内部除 `mineru.doclib.client` 外,不应直接通过 HTTP 调用 doclib API;外部客户端未来可以直接依赖 doclib HTTP API。-其他语言 SDK 暂无开发计划。如果未来开发,只覆盖 v1 Unified API,不覆盖本地 doclib UDS 能力;本地 doclib UDS 能力由 Python Doclib SDK 和 MinerU 自身入口承载。+其他语言 SDK 暂无开发计划。如果未来开发,只覆盖 v1 Unified API,不覆盖本地 doclib transport discovery 能力;本地 doclib 能力由 Python Doclib SDK 和 MinerU 自身入口承载。## 依赖方向@@ -39,7 +39,7 @@ mineru-kit api-servermineru doclib-> mineru.doclib.client- -> doclib server over UDS+ -> doclib server over UDS or TCP loopback-> doclib services-> mineru.parser-> MinerUApiParser -> local parse-server or mineru.net@@ -71,7 +71,7 @@ mineru doclib- **API-backed parser**: `MinerUApiParser`。- **Doclib SDK**: `MineruClient`。- **parse-server**: 实现 v1 Unified API 的无状态解析服务。-- **doclib server**: 本地文档库服务,通过 UDS 暴露本地产品能力。+- **doclib server**: 本地文档库服务,通过 UDS 或 TCP loopback 暴露本地产品能力。## 未决问题diff --git a/docs/next/sdk/doclib-client.md b/docs/next/sdk/doclib-client.mdindex 9602b537..3dbb0b50 100644--- a/docs/next/sdk/doclib-client.md+++ b/docs/next/sdk/doclib-client.md@@ -25,20 +25,28 @@ Doclib SDK 是 doclib 本地 API 的推荐承载方式。MinerU 项目内部除目标公开签名:```python+from pathlib import Path+from mineru.doclib.client import MineruClientclass MineruClient:def __init__(self,+ endpoint_path: str | Path | None = None,socket_path: str | None = None,+ base_url: str | None = None,timeout: int = 60,+ api_prefix: str = "/api/v1",) -> None: ...```约束:- 构造 client 不应启动 doclib server。-- 无法连接 UDS 时,方法调用抛出 `ServerNotRunningError`。+- 默认通过 `$MINERU_HOME/doclib.endpoint.json` 发现 doclib endpoint。+- `socket_path` 表示显式 UDS endpoint;`base_url` 只表示显式 TCP endpoint,例如 `http://127.0.0.1:15980`。+- `socket_path` 和 `base_url` 不能同时传入。+- 无法连接任何候选 endpoint 时,方法调用抛出 `ServerNotRunningError`。- client 应支持 `close()`,并最终支持 context manager。示例:diff --git a/docs/next/telemetry-implementation-plan.md b/docs/next/telemetry-implementation-plan.mdnew file mode 100644index 00000000..1fb159d9--- /dev/null+++ b/docs/next/telemetry-implementation-plan.md@@ -0,0 +1,362 @@+# Telemetry Implementation Plan++状态: Draft+日期: 2026-06-22+依据: `docs/next/telemetry-minimum.md`++本文档记录 doclib 第一版 telemetry 的实现计划。指标定义、隐私边界和协议语义以 `telemetry-minimum.md` 为准;本文只描述开发顺序、代码挂点和实现约束。++## 1. 已确认实现口径++第一版只实现 doclib telemetry:++- doclib server 负责本地记录、聚合和 flush。+- CLI / `DoclibClient` 只传递 context 或 observation,不直接外发 telemetry。+- parser SDK、`mineru-kit parse`、`mineru-kit api-server` 不纳入第一版。+- `parse.wait.*` 不带 `error_code`。+- `error_code` 只出现在失败类结果 count metric:+ - `parse.finished.count`+ - `parse_task.finished.count`+ - `parse_task.execute.count`+ - `parse_task.write.count`+- duration bucket 不带 `error_code`。+- 成功状态不带 `error_code`,不上传 `none`。++第一版外部 metrics API 先按 `aaa.py` 中 staging 接口实现:++```text+POST https://staging.mineru.org.cn/metrics/v2/metrics+```++请求规则:++- body 使用 compact JSON raw bytes,不能使用 HTTP client 的 `json=...` 自动序列化。+- body 包含 `api_version="v2"`。+- `schema_version` 使用字符串 `"1"`。+- header 包含 `Content-Type: application/json`、`X-Track-App-Key`、`X-Track-Ts`、`X-Track-Sign`。+- `X-Track-Sign = hmac_sha256(APP_SECRET, APP_KEY + ts + raw_body)`。+- `APP_KEY` / `APP_SECRET` 第一版内置在代码常量中,值从 `aaa.py` 同步。+- `preview` 只返回 request body,不返回签名 header。+- flush 不解析 response body,只看 HTTP status。++flush response 处理:++- `2xx`: batch accepted,删除对应 aggregate rows。+- `4xx`: 删除对应 batch rows,不更新 `last_flush_at`,返回 `invalid_payload_discarded`,记录 warning。+- `5xx`: 保留 rows,返回 `server_error`。+- network / timeout: 保留 rows,返回 `network_error`。+- 同一次 flush 中既有 2xx,又有失败 batch,返回 `partial_success`。+- response body 不写 DB、不进入 preview、不进入 CLI 输出、不进入日志。++official remote 判定:++- host 等于或后缀匹配 `mineru.net`、`mineru.org.cn` 时为 official。+- 不使用裸 substring 匹配,避免误判。++CLI unset prompt 覆盖:++- 触发: `parse`、`read`、`scan`、`watch`、`search`、`find`、`list`、`show`、`invalidate`、`forget`、`cleanup`。+- 不触发: `server`、`config`、`telemetry`。+- `--json`、CI、agent caller、非 TTY、server 不可访问时不提示。++## 2. 开发阶段++### Phase 1: Core 模块与 DB++新增模块:++```text+mineru/doclib/telemetry/+ __init__.py+ constants.py+ buckets.py+ context.py+ caller.py+ store.py+ payload.py+ observation.py+ service.py+```++实现内容:++- `constants.py`: metric name、dimension whitelist、`METRIC_SPECS`、consent state、endpoint、API version、schema version、staging app key/secret。+- `buckets.py`: duration、pages、file size、results bucket。+- `context.py`: `contextvars`、HTTP header parse、request context set/reset。+- `caller.py`: parent process tree inference,最大深度 12,只读进程名。+- `store.py`: `telemetry_state` 和 `telemetry_aggregates` 读写。+- `payload.py`: preview / flush payload 组装,metrics 稳定排序。+- `service.py`: `record_*`、`status`、`preview`、`enable`、`disable`、`flush`。++DB 改动:++- 修改 `mineru/doclib/migrations/001_init.sql`,增加 `telemetry_state`、`telemetry_aggregates`。+- 修改 `mineru/doclib/app.py` 的 `REQUIRED_SCHEMA_TABLES`。+- 不做单独 migration,现阶段直接改 `001_init.sql`。++测试重点:++- bucket 边界。+- dimension normalize / whitelist / hash。+- state 初始化: `installation_id`、`consent_state=unset`、`last_flush_at=0`、`flush_locked_at=0`。+- disabled 后 record no-op,disable 清空 aggregates 但保留 `installation_id`。+- preview payload 不包含 forbidden fields。++### Phase 2: Context 传递与管理 API++接口模型:++- 在 `mineru/doclib/types.py` 增加 telemetry response / request models。+- 在 `mineru/doclib/base.py` 和 `AsyncDoclibInterface` 增加抽象方法。+- 在 `mineru/doclib/client.py` 增加 sync client 方法。+- 在 `mineru/doclib/server.py` 增加 route 实现。++新增 API:++```text+GET /telemetry/status+GET /telemetry/preview+POST /telemetry/actions/{action}+POST /observations+```++context 传递:++- `DoclibClient._request_model` 读取 contextvars,并发送:+ - `X-MinerU-Source`+ - `X-MinerU-Caller`+- server middleware 解析 header,缺失时默认 `source=http_api`、`caller=http_client`。+- request 结束后 reset context token。++测试重点:++- missing / invalid header 降级。+- SDK 默认 `source=sdk`,caller best-effort 推断。+- telemetry status / preview / enable / disable / flush 行为。+- `/observations` schema 校验和 disabled/unset 行为。++### Phase 3: Flush Worker++新增:++```text+mineru/doclib/background/telemetry_flush.py+```++`AppState` 增加:++```text+state.telemetry_store+state.telemetry_svc+state.telemetry_flush_worker+```++startup 顺序:++```text+DatabaseManager.initialize()+ -> TelemetryStore(db)+ -> TelemetryService(store, context collector)+ -> business services with telemetry_svc+ -> background workers+ -> TelemetryFlushWorker+```++flush 行为:++- 启动后先尝试一次 flush。+- 每 2 小时尝试一次 flush。+- 只有 `consent_state=enabled` 才外发。+- 一次 flush 最多 10 个 period。+- 每个 HTTP request 只发送一个 period。+- period 按 `period_start ASC, period_end ASC`。+- lock TTL 1800 秒。+- 发送使用 `httpx.AsyncClient`,timeout 10 秒。+- 使用 compact JSON raw bytes + HMAC header。++测试重点:++- unset / disabled 不外发。+- no pending metrics 不外发。+- 2xx 删除 rows。+- 4xx 删除 rows,不更新 `last_flush_at`。+- 5xx/network 保留 rows。+- partial success。+- lock 存在时跳过。+- 一次最多 10 个 period。++### Phase 4: Route-level Metrics++先接入口体验层,不碰后台 worker 内部步骤。++parse route:++- `parse.request.count`+- `parse.finished.count`+- `parse.duration_bucket.count`+- `parse.files.count`+- `parse.pages.count`+- `parse.file_size_bucket.count`+- `parse.pages_bucket.count`+- `parse.invalidate.count`++search / find / content:++- `search.request.count`+- `search.finished.count`+- `search.duration_bucket.count`+- `search.results_bucket.count`+- `find.request.count`+- `find.finished.count`+- `find.duration_bucket.count`+- `find.results_bucket.count`+- `content.request.count`+- `content.finished.count`+- `content.duration_bucket.count`++scan / watch route:++- `scan.request.count` route 部分。+- `watch.add.count`+- `watch.add.finished.count`+- `watch.remove.count`+- `watch.remove.finished.count`++实现约束:++- route-level request metric 在进入业务 handler 后立即记录。+- FastAPI / Pydantic 进入 handler 前拒绝的请求不计。+- 失败路径可以计算 telemetry status / error_code,但必须 re-raise 原异常。+- telemetry 写入失败不能影响业务返回。++### Phase 5: Service / Worker Metrics++`ParseService`:++- 构造函数显式接收 `telemetry_svc`。+- 接 `parse_task.created.count`、`parse_task.started.count`。+- 在 `process_doc` 周围接:+ - `parse_task.finished.count`+ - `parse_task.duration_bucket.count`+ - `parse_task.files.count`+ - `parse_task.pages.count`+- 在 `_parse_via_local` / `_parse_via_api` 周围接:+ - `parse_task.execute.count`+ - `parse_task.execute_duration_bucket.count`+- JSON 写入、FTS 更新、docs metadata 更新作为 write 步骤:+ - `parse_task.write.count`+ - `parse_task.write_duration_bucket.count`++`ParseWorkerPool`:++- fallback exception 路径也必须记录 `parse_task.finished.count {status=failed}`。++`ScanService`:++- 构造函数显式接收 `telemetry_svc`。+- 接:+ - `scan.reuse.count`+ - `scan.finished.count`+ - `scan.duration_bucket.count`+ - `scan.files.count`+- internal watch-triggered scan 创建时记录 `scan.request.count {source=watch, caller=system}`。++Ingest:++- `refresh_file` / `ensure_ingested` / `ingest_file` 增加 keyword-only `trigger`,默认 `unknown`。+- 触发来源: `parse | scan | watch | show | background | unknown`。+- 记录:+ - `ingest.finished.count`+ - `ingest.duration_bucket.count`++测试重点:++- parse task created / started / finished。+- execute succeeded / failed。+- write succeeded / failed。+- write failed 同时导致 task finished failed。+- scan counters 映射到 `scan.files.count`。+- ingest trigger 和 skipped 规则。++### Phase 6: Observations 与 CLI Wait++`POST /observations`:++- 第一版只支持 `type=parse_wait`。+- 根据 `parse_ids` 查询 task,补齐 `tier` 和 `pages_bucket`。+- 不补齐、不上报 `error_code`。+- 记录:+ - `parse.wait.count`+ - `parse.wait_duration_bucket.count`++`DoclibClient`:++- 增加 `submit_observation()`。++CLI parse wait:++- wait 前记录 `wait_start = time.monotonic()`。+- done -> `status=succeeded`。+- failed -> `status=failed`。+- timeout -> `status=timeout`。+- Ctrl-C / cancel -> 尽量 `status=canceled`。+- observation 失败静默忽略。++### Phase 7: CLI Telemetry 命令与 Unset Prompt++新增:++```text+mineru/cli/commands/telemetry.py+mineru/cli/telemetry.py+```++`mineru` 顶层命令:++```text+mineru telemetry status+mineru telemetry enable+mineru telemetry disable+mineru telemetry preview+mineru telemetry flush+```++`TOP_LEVEL_COMMAND_ORDER`:++```text+server+config+telemetry+```++prompt helper:++- `is_interactive_cli()`+- `is_ci_environment()`+- `maybe_prompt_telemetry_consent(client, *, json_mode, command_name)`++触发范围:++- 触发: `parse`、`read`、`scan`、`watch`、`search`、`find`、`list`、`show`、`invalidate`、`forget`、`cleanup`。+- 不触发: `server`、`config`、`telemetry`。+- `--json`、CI、agent caller、非 TTY、server 不可访问时不提示。++## 3. 建议提交边界++建议拆成 5 个开发包:++1. `telemetry core`: DB、store、service、payload、buckets、context。+2. `telemetry api`: management API、observations API、client/base/types。+3. `telemetry flush`: worker、flush lock、staging metrics API。+4. `telemetry metrics`: parse/search/content/scan/watch/ingest/parse_task 打点。+5. `telemetry cli`: commands、prompt、parse wait observation。++## 4. 高风险点++- `DoclibClient` 是 sync client,server 侧 telemetry service 是 async,不要混用。+- route decorator 要求 `base.py`、`client.py`、`server.py` 接口保持一致。+- `DatabaseManager` 当前每次操作新建连接,aggregate upsert 和 flush lock 要依赖 SQL 原子性。+- `error_code` 只在四个失败 count metric 上出现,不得加到 duration bucket。+- telemetry record 失败必须吞掉,业务异常必须原样返回。+- HMAC 签名必须使用发送出去的 exact raw body。+- preview 只展示 body,不展示 app key、secret、签名或 response。diff --git a/docs/next/telemetry-minimum.md b/docs/next/telemetry-minimum.mdnew file mode 100644index 00000000..338e2060--- /dev/null+++ b/docs/next/telemetry-minimum.md@@ -0,0 +1,1535 @@+# Telemetry Minimum Design++状态: Draft+日期: 2026-06-18+范围: doclib 第一版 telemetry 最小设计和指标集+非目标: CLI 早失败漏斗、rules / cleanup / compaction、完整 watch event 统计、详细硬件画像、blocking wait API++本文档是第一版 telemetry 实现的准确定义。`telemetry.md` 作为背景和候选设计参考;当两者不一致时,以本文档为准。++## 1. 第一版目标++第一版 telemetry 只回答两个问题:++1. 用户和 Agent 在以什么方式、什么频率使用 MinerU。+2. 从结果、速度、等待时间和出错情况评估用户满意度。++第一版只统计进入 doclib 后的业务行为。暂不统计 `mineru` CLI 在进入 doclib 之前的失败,例如参数错误、文件不存在、server 未启动。这类入口漏斗后续可用 `cli.request.count` 单独补充。++## 2. 采集边界++只有 doclib server 记录、聚合和上报 telemetry。++`mineru` CLI 和 `DoclibClient` 可以向 doclib server 传递调用上下文或 observation,但不直接向外部 telemetry endpoint 上报。++以下纯工具不具备 telemetry 能力:++- parser SDK,包括 `mineru.parser.parse()` 和 `parse_async()`。+- `mineru-kit parse`。+- `mineru-kit api-server`。+- 其他不依赖 doclib server 的专家工具。++这个边界避免 parser/tool 层在作为库或底层工具使用时包含 telemetry 配置、存储或网络行为。++### 实现模块边界++第一版 telemetry 作为 doclib 内部独立模块实现:++```text+mineru/doclib/telemetry/+ __init__.py+ constants.py+ context.py+ caller.py+ buckets.py+ store.py+ payload.py+ observation.py+ service.py+```++职责:++- `constants.py`: metric name、dimension key/value 白名单、metric allowed dimensions 内存表、consent 枚举和 telemetry endpoint 常量。+- `context.py`: `contextvars` 上下文、HTTP header 解析、request context 设置。+- `caller.py`: 当前进程 caller 推断,只输出 `agent | user | unknown`。+- `buckets.py`: duration、pages、file size、results 分桶。+- `store.py`: telemetry state 和 aggregate 的 DB 读写。+- `payload.py`: preview 和 flush payload 组装。+- `observation.py`: `/observations` request 校验和转换。+- `service.py`: telemetry 对外主入口,提供 record、preview、flush、enable、disable 能力。++`AppState` 持有:++```text+state.telemetry_store+state.telemetry_svc+state.telemetry_flush_worker+```++startup 初始化顺序:++```text+DatabaseManager.initialize()+ -> TelemetryStore(db)+ -> TelemetryService(store, context collector)+ -> ParseService(..., telemetry_svc=state.telemetry_svc)+ -> ScanService(..., telemetry_svc=state.telemetry_svc)+ -> SearchService(..., telemetry_svc=state.telemetry_svc)+ -> background workers+ -> TelemetryFlushWorker(...)+```++传递规则:++- `ParseService`、`ScanService`、`SearchService` 构造函数显式接收 `telemetry_svc`。+- `DoclibServer` route 通过 `self.state.telemetry_svc` 记录 route-level metric。+- background worker 不创建 telemetry service,只使用已注入到 service 的 telemetry。+- telemetry service 所有 record 方法内部吞掉异常,最多记录 debug / warning log,不影响主流程。+- 不使用全局单例或动态从模块级变量读取 telemetry service。++`TelemetryFlushWorker` 放在 doclib background 模块:++```text+mineru/doclib/background/telemetry_flush.py+```++形态:++```python+class TelemetryFlushWorker:+ def __init__(+ self,+ telemetry_svc: TelemetryService,+ *,+ interval_sec: int = 7200,+ ) -> None: ...++ async def run(self) -> None: ...+ async def stop(self) -> None: ...+```++worker 规则:++- 启动后先尝试一次 flush,但只有 `consent_state=enabled` 才真正外发。+- 之后每 2 小时尝试一次 flush。+- shutdown 时调用 `stop()`。+- 手动 flush 和后台 flush 复用同一个 `TelemetryService.flush()`。+- 一个 HTTP 请求只发送一个 period。+- 一次 flush 最多发送 10 个 period,即最多 10 个 HTTP 请求。+- `preview` 只展示最早一个将发送的 period batch。++## 3. 用户选择与开关++首次启动 doclib server 时,如果用户尚未选择,允许先进入 `unset` 状态。++状态:++```text+consent_state = unset | enabled | disabled+```++语义:++- `unset`: 用户尚未完成首次选择。doclib server 可以本地记录 telemetry 聚合数据,但不得 flush 到外部 endpoint。+- `enabled`: 用户允许记录并上报 telemetry。+- `disabled`: 用户明确关闭 telemetry。++默认策略:++- 首次选择界面默认勾选开启 telemetry。+- 用户可以关闭。+- 用户选择结果记录为 `consent_state`。+- `consent_state=unset` 时,可以写入本地 telemetry 聚合数据,但不能上报。+- 如果用户后续选择 `enabled`,此前 `unset` 状态下记录的本地聚合数据可以随之后数据一起 flush。+- `consent_state=disabled` 时,不写入新的 telemetry 聚合数据,也不上报。+- 用户选择或切换到 `disabled` 时,DB 中未上报 telemetry 数据应删除,避免后续误发。++CLI 被调用时,应 best-effort 判断是否处于交互式环境。可以使用 stdin / stdout 是否为 TTY 作为基础判断,并避免在 CI、Agent 或明确非交互环境中提示。若处于交互式普通用户环境且 `consent_state=unset`,第一版 CLI 应提示用户完成选择。若开始使用后一直是非交互或 Agent 场景,则默认维持 `unset`,直到有机会让用户选择。++CLI `unset` prompt 规则:++- prompt 只在 CLI 层实现,不放入 `DoclibClient`,避免 SDK 用户被提示。+- `mineru telemetry status|enable|disable|preview|flush` 命令自身不触发 prompt。+- `mineru server start` 第一版暂不触发 prompt;后续业务命令会提示。+- prompt 触发条件必须同时满足:+ - `consent_state == "unset"`+ - stdin 和 stdout 都是 TTY+ - 当前不是 `--json` 输出模式+ - 不在 CI 环境+ - caller 推断不是 `agent`+ - doclib server 已可访问+- 不满足条件时不提示,保持 `unset`。+- 用户输入 Enter / `y` / `yes` 时,调用 `POST /telemetry/actions/enable`。+- 用户输入 `n` / `no` 时,调用 `POST /telemetry/actions/disable`。+- EOF 或其它非法输入保持 `unset`,并继续原命令。非法输入第一版不循环追问。+- Ctrl-C 保持 `unset`,并按 CLI 原取消逻辑退出。+- 只要用户选择过,server 里的 `consent_state` 变成 `enabled` 或 `disabled`,后续不再提示。++推荐提示文案:++```text+MinerU can send anonymous, aggregated telemetry to help improve doclib.+No document content, filenames, paths, queries, IDs, or error messages are sent.++Enable telemetry? [Y/n]:+```++用户必须可以通过命令查看和修改状态:++```bash+mineru telemetry status+mineru telemetry enable+mineru telemetry disable+mineru telemetry preview+mineru telemetry flush+```++`preview` 展示本地待 flush 的 telemetry request body。它等价于一次外部 telemetry HTTP 请求的 body 预览,但不触发 flush。+`installation_id` 不是敏感隐私字段,`preview` 可以展示完整 `installation_id`。++doclib server 提供最小 telemetry 管理 API:++```text+GET /telemetry/status+GET /telemetry/preview+POST /telemetry/actions/{action}+```++`action` 取值:++```text+enable | disable | flush+```++`enable` 将 `consent_state` 置为 `enabled`。`disable` 将 `consent_state` 置为 `disabled`,并清除本地未上报聚合数据。`flush` 触发一次手动 flush;如果当前不是 `enabled`,应返回 accepted 但不执行外部上报。++管理 API response:++```python+TelemetryConsentState = Literal["unset", "enabled", "disabled"]+TelemetryAction = Literal["enable", "disable", "flush"]++class TelemetryStatusResponse(DoclibModel):+ consent_state: TelemetryConsentState+ installation_id: str+ pending_aggregate_count: int+ pending_period_count: int+ last_flush_at: int | None = None+ flush_locked_at: int | None = None+++class TelemetryFlushResult(DoclibModel):+ accepted: bool+ executed: bool+ reason: str | None = None+ sent_batch_count: int = 0+ sent_metric_count: int = 0+++class TelemetryActionResponse(DoclibModel):+ action: TelemetryAction+ accepted: bool+ executed: bool+ consent_state: TelemetryConsentState+ reason: str | None = None+ flush_result: TelemetryFlushResult | None = None+```++API 语义:++- `GET /telemetry/status` 返回 `TelemetryStatusResponse`。+- `pending_aggregate_count` 表示当前 `telemetry_aggregates` 中待上报 aggregate row 的数量,不是 `metric_value` 总和。+- `pending_period_count` 表示当前待上报的 distinct period 数量,即 distinct `(period_start, period_end)` 数量。+- `last_flush_at` 表示最近一次至少有一个 batch 被 telemetry endpoint 2xx 确认接收的完成时间;此前从未成功 flush 时返回 `null`。+- `flush_locked_at` 表示当前 live flush lock 的获取时间;没有 live lock 时返回 `null`。+- `GET /telemetry/preview` 直接返回外部 telemetry request body,不额外包 metadata。+- `preview` 不触发 flush,不修改 `last_flush_at`,可以展示完整 `installation_id`。+- 如果本地没有待上报 metrics,`preview` 返回合法空 batch,`metrics=[]`。这只表示当前没有待上传 metrics,`flush` 不会上传空 batch。+- 空 preview payload 只用于 CLI 展示,不是 external endpoint 会收到的 payload。+- 如果本地有多个 period,第一版 `preview` 只返回一次实际 flush 会发送的最早一个 period 的 batch。+- `preview` 的 `batch_id` 固定为 `tb_preview`,不写入 DB。+- 空 batch preview 的 `period_start` / `period_end` 使用当前 UTC 小时 period。+- `POST /telemetry/actions/enable` 设置 `consent_state=enabled`,返回 `accepted=true`、`executed=true`。+- `POST /telemetry/actions/disable` 设置 `consent_state=disabled`,删除本地未上报聚合数据,返回 `accepted=true`、`executed=true`。+- `POST /telemetry/actions/flush` 在 `enabled` 时同步触发一次 flush,并返回 `TelemetryActionResponse`,其中 `flush_result` 填充 `TelemetryFlushResult`。+- `flush` 在 `unset` 或 `disabled` 时返回 HTTP 200,`accepted=true`、`executed=false`、`reason="telemetry_not_enabled"`。+- 未知 action 返回 HTTP 4xx。+- `TelemetryActionResponse.executed` 表示 action 已被执行,不表示 flush 成功上传;flush 结果以 `flush_result.reason` 为准。++`TelemetryService.flush()` 返回 `TelemetryFlushResult`。语义:++- `unset` / `disabled`: `accepted=true`、`executed=false`、`reason="telemetry_not_enabled"`。+- 没有 pending aggregate: `accepted=true`、`executed=false`、`reason="no_pending_metrics"`。+- flush lock 未过期: `accepted=true`、`executed=false`、`reason="flush_locked"`。+- 网络失败: 保留 rows,`executed=false`、`reason="network_error"`。+- telemetry endpoint 5xx: 保留 rows,`executed=false`、`reason="server_error"`。+- telemetry endpoint 4xx: 删除对应 batch rows,不更新 `last_flush_at`,记录 warning log,`executed=true`、`reason="invalid_payload_discarded"`。+- 如果同一次 flush 中同时出现至少一个 2xx 成功 batch,且也出现至少一个 network / 5xx / 4xx discard batch,则返回 `accepted=true`、`executed=true`、`reason="partial_success"`。+- 至少一个 batch 被 telemetry endpoint 2xx 确认接收时,删除已确认 rows,更新 `last_flush_at`。+- 全部 batch 都失败时,不更新 `last_flush_at`。+- 4xx discard 不算成功,不触发 `last_flush_at` 更新。+- `sent_batch_count` 表示被 telemetry endpoint 2xx 确认接收的 batch 数。+- `sent_metric_count` 表示被 telemetry endpoint 2xx 确认接收的 aggregate row 数总和,不是尝试发送的 row 数,也不是 `metric_value` 总和。++## 4. 隐私边界++Telemetry 禁止采集:++- 文档内容+- 文件名+- 文件路径+- 原始 URL+- search query+- prompt+- sha256+- parse_id / scan_id / job_id+- traceback+- exception message+- hostname+- 用户名+- 邮箱+- 账号 ID+- CPU/GPU 具体型号+- GPU 显存、驱动版本、CUDA 版本++允许采集的数据必须来自白名单字段。不得把请求体、异常对象、配置对象、`kwargs` 或任意 dict 直接透传到 telemetry。++`/observations` 可以接收 `parse_ids` 作为本地查询引用,但这些 ID 只允许用于 doclib server 本地补齐低基数字段,不得写入 telemetry 聚合或外部上报 payload。++## 5. 本地聚合与上报++第一版使用匿名 `installation_id` 作为安装实例口径。++- `installation_id` 在 doclib server 第一次启动时自动生成。+- `installation_id` 存储在 doclib DB 的 telemetry 内部状态中。+- `installation_id` 不是敏感隐私字段。+- 不依赖账号体系。+- 即使用户尚未选择 telemetry,或当前没有上报需求,也可以生成 `installation_id`。+- 用户选择或切换到 `disabled` 时,不删除 `installation_id`,避免后续重新启用后安装实例 ID 改变。+- 用户删除配置或重装后,会被视为新的安装实例。+- 第一版 `installation_id` 格式定义为 `inst_<32 lowercase hex>`,例如 `inst_7f6e0c6a0d174dc6a3f1b6f6a36d7f73`。++第一版采用本地聚合 metrics 上报,不采用每个事件即时上报。++运行时行为:++```text+doclib server runtime+ -> record metric delta+ -> update telemetry aggregate in doclib DB+ -> periodic flush+ -> POST telemetry endpoint+ -> delete flushed rows from doclib DB after success+```++聚合和 flush 策略:++- 本地 telemetry 配置和 telemetry 聚合数据都存储在 doclib DB 中。+- 本地按 1 小时 period 聚合,period 边界使用 UTC 整点。+- period 采用左闭右开区间,即 `[period_start, period_end)`。+- 一次 flush 可以处理多个未 flush 的小时级 period,但每个 period 独立生成一个 HTTP request。+- flush 发送顺序按 `period_start ASC, period_end ASC`。+- `consent_state=enabled` 时,启动后尝试 flush 一次。+- `consent_state=enabled` 时,运行中每 2 小时尝试 flush 一次。+- `consent_state=unset` 或 `disabled` 时,不进行外部 flush。+- 网络失败或服务端 5xx 时保留本地聚合结果,后续重试。+- 服务端 4xx 表示 payload 不合法,对应 batch rows 应删除,不更新 `last_flush_at`,记录 warning log,不应无限重试。+- flush 成功后,已被服务端确认接收的 telemetry 聚合数据应从 doclib DB 中删除。+- 同一个 period 内 context 变化可以接受;flush 时使用当前 context 上报该 period 的聚合 metrics。+- 一个 HTTP 请求只发送一个 period。+- 一次 flush 最多发送 10 个 period。++主流程不得等待 telemetry 上报。telemetry 失败不得影响 parse、watch、search 或 doclib API。++Telemetry endpoint 使用代码内置值,用户不可配置:++```http+POST https://telemetry.mineru.net/v1/metrics+Content-Type: application/json+```++开发和测试环境如需覆盖 endpoint,应使用测试构建或专门的开发开关,不进入用户配置体系。++flush 使用 `httpx.AsyncClient`,请求 timeout 固定为 10 秒。测试环境可以通过内部测试 hook 或构造参数替换 endpoint;该能力不进入用户配置。++现阶段不用考虑 migration,可以直接修改 `mineru/doclib/migrations/001_init.sql`。新增表应使用 `CREATE TABLE IF NOT EXISTS`,使已有 DB 在启动时也能补建 telemetry 表。++Telemetry state 不使用现有 `config` 表。`config` 表语义是用户可配 runtime config override;`installation_id`、`last_flush_at`、`flush_locked_at` 不是用户配置。++本地状态使用独立 KV 表表达:++```sql+CREATE TABLE IF NOT EXISTS telemetry_state (+ key TEXT PRIMARY KEY,+ value TEXT NOT NULL,+ updated_at INTEGER NOT NULL+);+```++`telemetry_state` keys:++| key | value |+|-----|-------|+| `consent_state` | `unset | enabled | disabled` |+| `installation_id` | `inst_...` |+| `last_flush_at` | epoch ms timestamp |+| `flush_locked_at` | epoch ms timestamp |++初始化规则:++- server startup 时,如果没有 `installation_id`,生成并写入。+- server startup 时,如果没有 `consent_state`,写入 `unset`。+- server startup 时,如果没有 `last_flush_at` 或 `flush_locked_at`,写入字符串 `"0"`,表示当前为空值。+- server startup 时固定初始化所有 telemetry state keys,包括 `installation_id`、`consent_state`、`last_flush_at`、`flush_locked_at`,避免后续 flush lock 或 status 查询处理 key 缺失。+- 即使用户选择或切换到 `disabled`,也不删除 `installation_id`。+- 用户选择或切换到 `disabled` 时,删除 `telemetry_aggregates` 中全部未上报聚合数据。++Telemetry 聚合数据使用独立表保存:++```sql+CREATE TABLE IF NOT EXISTS telemetry_aggregates (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ period_start INTEGER NOT NULL,+ period_end INTEGER NOT NULL,+ metric_name TEXT NOT NULL,+ metric_value INTEGER NOT NULL DEFAULT 0,+ dimensions TEXT NOT NULL,+ dimensions_hash TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ UNIQUE(period_start, period_end, metric_name, dimensions_hash)+);++CREATE INDEX IF NOT EXISTS idx_telemetry_aggregates_period+ON telemetry_aggregates(period_start, period_end);+```++字段说明:++| 字段 | 说明 |+|------|------|+| `id` | 本地聚合记录 ID |+| `period_start` | 聚合窗口开始时间 |+| `period_end` | 聚合窗口结束时间 |+| `metric_name` | metric 名称 |+| `metric_value` | 非负数值 |+| `dimensions` | metric-level dimensions JSON |+| `dimensions_hash` | dimensions JSON 的稳定 hash,用于聚合 upsert |+| `created_at` | 创建时间 |+| `updated_at` | 最近更新时间 |++`metric_value` 使用 `INTEGER`。第一版所有 metric 都是 count、bucket count、files/pages 总数或其它非负整数值。以后如果需要 ratio / float metric,再单独扩展存储模型。++时间格式:++- DB 中时间使用 epoch ms。+- 外部 payload 中的 `period_start` / `period_end` 使用 UTC ISO 8601,例如 `2026-06-22T10:00:00Z`。+- preview payload 也使用同样的 UTC ISO 8601 时间格式。++聚合唯一键:++```text+period_start + period_end + metric_name + dimensions_hash+```++同一唯一键重复写入时,累加 `metric_value`。聚合 key 不包含 context;flush 时读取当前 context 并组装 telemetry batch。++`dimensions_hash` 生成规则:++1. 对 dimensions 先做 normalize 和 whitelist 过滤。+2. 使用 `json.dumps(dimensions, sort_keys=True, separators=(",", ":"))` 生成稳定 JSON 字符串。+3. 对该字符串计算 SHA-256 hex。++Flush 并发与幂等采用第一版简单方案:++1. doclib 同一时间只允许一个 flush 任务执行。+2. flush 开始时获取本地 flush lock;已有 lock 且未过期时,本次 flush 直接跳过。+3. flush 从 DB 读取最多 10 个未上报 period,每个 period 生成一个 `batch_id` 并 POST 一次 telemetry endpoint。+4. 服务端确认成功接收后,本地删除这些聚合记录。+5. 如果 POST 成功但本地删除前 doclib 崩溃,后续可能重复上报同一批 metrics。+6. 第一版接受少量重复。服务端应基于 `batch_id` 在短窗口内做幂等去重;超过窗口的重复数据由 cleaned metrics 层处理。++flush lock TTL:++```text+flush_lock_ttl_sec = 1800+```++即 30 分钟。超过该时间的 lock 视为过期。++lock 存储规则:++- 获取 flush lock 时,把 `flush_locked_at` 写为当前 epoch ms。+- flush 结束时,无论成功、失败还是提前跳过,只要当前调用持有 lock,就把 `flush_locked_at` 重置为 `"0"`。+- `TelemetryStatusResponse.flush_locked_at` 中,`"0"` 映射为 `null`。++## 6. Payload 与 Context++一次上报包含一个 batch。环境信息放在 batch-level `context` 中,不重复放入每个 metric。++```json+{+ "batch_id": "tb_01HX...",+ "schema_version": 1,+ "installation_id": "inst_01HX...",+ "period_start": "2026-06-10T14:00:00Z",+ "period_end": "2026-06-10T15:00:00Z",+ "context": {+ "app": "mineru",+ "app_version": "3.0.0",+ "os": "macos",+ "arch": "arm64",+ "python_version": "3.11",+ "install_channel": "pip",+ "cpu_count_bucket": "9_16",+ "gpu_vendor": "apple"+ },+ "metrics": [+ {+ "name": "parse.finished.count",+ "value": 12,+ "dimensions": {+ "source": "cli",+ "caller": "agent",+ "tier": "standard(default)",+ "status": "queued"+ }+ }+ ]+}+```++规则:++- `batch_id` 由本地 flush 任务生成,用于服务端短窗口幂等。第一版格式定义为 `tb_<32 lowercase hex>`。+- `schema_version` 使用整数,第一版固定为 `1`。+- `value` 必须是非负数。+- 字符串数据只能出现在 `context` 或 `dimensions`。+- `context` 描述安装实例、运行环境和版本。+- `metrics[].dimensions` 描述当前 metric 的业务分类。+- `metrics[].dimensions` 必须来自白名单,不能包含任意字符串。+- `context` 表示 flush 时 doclib server 的当前运行环境。同一 period 内 context 变化可以接受,不要求拆分 batch。+- `metrics` 列表按稳定顺序输出,第一版使用 `name ASC`,再按 normalize 后的 `dimensions` JSON 字符串升序。++第一版 context 字段:++| 字段 | 类型 | 枚举 / 格式 | 说明 |+|------|------|-------------|------|+| `app` | string | `mineru` | 固定应用名 |+| `app_version` | string | semver 或发布版本 | MinerU 版本 |+| `os` | string | `macos` / `windows` / `linux` / `other` / `unknown` | 操作系统 |+| `arch` | string | `x86_64` / `arm64` / `other` / `unknown` | CPU 架构 |+| `python_version` | string | `3.10` / `3.11` / `3.12` / `3.13` / `other` / `unknown` | Python 主次版本 |+| `install_channel` | string | `pip` / `uv` / `docker` / `source` / `unknown` | 安装来源 |+| `cpu_count_bucket` | string | `1_4` / `5_8` / `9_16` / `gt_16` / `unknown` | CPU 核心数分桶 |+| `gpu_vendor` | string | `nvidia` / `apple` / `amd` / `none` / `unknown` | GPU 或常见加速器厂商 |++`gpu_vendor` 规则:++- `nvidia`: 识别到 NVIDIA GPU。+- `apple`: 识别到 Apple GPU。+- `amd`: 识别到 AMD GPU。+- `none`: 明确没有发现 GPU。+- `unknown`: 无法检测、检测失败,或发现了第一版未分类的其他加速器。++context 采集规则:++- `os`: 使用 `platform.system()` 归一化为 `macos | windows | linux | other | unknown`。+- `arch`: 使用 `platform.machine()` 归一化为 `x86_64 | arm64 | other | unknown`;`amd64` 归一化为 `x86_64`,`aarch64` 归一化为 `arm64`。+- `python_version`: 使用 `sys.version_info.major.minor`;不在白名单时记为 `other`。+- `cpu_count_bucket`: 使用 `os.cpu_count()`;`None` 或小于等于 0 时记为 `unknown`,否则按 `1_4 | 5_8 | 9_16 | gt_16` 分桶。+- `install_channel` 使用以下优先级:+ 1. 若检测到当前运行在 Docker / 容器环境中,记为 `docker`。+ 2. 否则若 `importlib.metadata.distribution("mineru")` 的 `direct_url.json` 表示本地目录安装,或 `dir_info.editable=true`,记为 `source`。+ 3. 否则若当前 `mineru` 模块文件路径不在 `site-packages` / `dist-packages` 下,且向上能找到项目级 `pyproject.toml`,记为 `source`。+ 4. 否则尝试读取 `importlib.metadata.distribution("mineru")` 的 `INSTALLER` 元数据;值为 `uv` 时记为 `uv`,值为 `pip` 时记为 `pip`。+ 5. 其它情况记为 `unknown`。+- Docker / 容器检测为 best-effort,第一版允许使用 `/.dockerenv`、`/proc/1/cgroup`、`/proc/self/cgroup` 等本地信号;判断失败时降级,不向业务层抛错。+- `gpu_vendor` 使用保守检测:+ 1. `platform.system()=="Darwin"` 且 `arch=="arm64"` 时记为 `apple`。+ 2. Linux 上若 DRM / sysfs vendor 可明确识别为 `0x10de`,或存在 `nvidia-smi` / `/dev/nvidiactl`,记为 `nvidia`。+ 3. Linux 上若 DRM / sysfs vendor 可明确识别为 `0x1002`,记为 `amd`。+ 4. Linux 上若未发现任何 GPU / render device 信号,记为 `none`。+ 5. Windows 上使用 `winreg` best-effort 读取 display adapter 信息;能明确识别 `NVIDIA` / `VEN_10DE` 时记为 `nvidia`,能明确识别 `AMD` / `Radeon` / `VEN_1002` 时记为 `amd`,其它情况记为 `unknown`。第一版不在 Windows 上上报 `none`。+ 6. 其它无法可靠判断的情况记为 `unknown`。+- 第一版不为了 telemetry 主动 import `torch`、`paddle`、`transformers` 等重依赖做硬件探测。++第一版不采集 CPU/GPU family、具体型号、显存、驱动和 CUDA 版本。++外部 telemetry endpoint 必须实现 schema version 校验、metric name 白名单、context key/value 白名单、dimension key/value 白名单、`value` 非负数校验、batch 大小限制、period 时间范围限制,以及安装实例和 IP 级限流。++## 7. 命名原则++流程结构写入 metric name,分类结果写入 dimensions。++示例:++```text+parse.request.count+parse.finished.count+parse.wait_duration_bucket.count+parse_task.execute.count+```++不用 `phase` 或 `stage` 维度区分入口和步骤。入口请求使用 `parse.*`,后台异步任务使用 `parse_task.*`。++Metric value 口径:++- `*.request.count`、`*.finished.count`、`*.started.count`、`*.created.count` 等事件型 metric 的 `value` 表示发生次数。+- `*.duration_bucket.count`、`*.file_size_bucket.count`、`*.pages_bucket.count`、`*.results_bucket.count` 的 `value` 表示落入该 bucket 的样本数。+- `*.files.count` 的 `value` 表示文件数量总和,不表示请求或任务次数。+- `*.pages.count` 的 `value` 表示页数总和,不表示请求或任务次数。+- `scan.files.count` 的 `value` 表示对应 `result` 下的文件数量总和。++Duration bucket 口径:++- 所有 `*.duration_bucket.count` 应尽量携带与对应结果 metric 相同的 `status`。+- `parse.duration_bucket.count` 使用同一次 `parse.finished.count` 的 `status`,即 `cached | direct | reused | queued | failed`。+- `parse.wait_duration_bucket.count` 使用同一次 `parse.wait.count` 的 `status`,即 `succeeded | failed | timeout | canceled`。+- `parse_task.duration_bucket.count` 使用同一次 `parse_task.finished.count` 的 `status`。+- `parse_task.execute_duration_bucket.count` 使用同一次 `parse_task.execute.count` 的 `status`。+- `parse_task.write_duration_bucket.count` 使用同一次 `parse_task.write.count` 的 `status`。+- `ingest.duration_bucket.count`、`search.duration_bucket.count`、`find.duration_bucket.count`、`content.duration_bucket.count`、`scan.duration_bucket.count` 使用对应 `*.finished.count` 的 `status`。++## 8. Context 传递++`source` 和 `caller` 不写入每个业务 request model。++CLI 到 `DoclibClient` 是同进程调用,使用 `contextvars` 传递进程内 telemetry context,不使用环境变量。++```text+source=cli+caller=agent | user | unknown+```++进程内 context API:++```python+@dataclass(frozen=True)+class TelemetryContext:+ source: TelemetrySource+ caller: TelemetryCaller++def set_telemetry_context(source: TelemetrySource, caller: TelemetryCaller) -> Token: ...+def reset_telemetry_context(token: Token) -> None: ...+def get_telemetry_context() -> TelemetryContext | None: ...+def infer_default_client_context() -> TelemetryContext: ...+```++CLI 规则:++- CLI 入口设置 telemetry context。+- `DoclibClient` 在发请求前读取 context。+- `caller` 由 helper best-effort 检测当前进程父进程树。+- 已知 Agent 进程记为 `agent`,普通 shell / terminal 记为 `user`,无法可靠判断时记为 `unknown`。+- helper 只输出枚举值,不记录进程名原文、命令行、路径或 prompt。++`DoclibClient` 发送 header 规则:++- 如果 `contextvars` 中已有 context,使用该 context。+- 如果没有 context,默认 `source=sdk`。+- 如果没有 context,`caller` 仍由当前进程调用树 best-effort 推断。+- caller 推断失败时,`caller=unknown`。++`DoclibClient` 到 doclib server 使用 HTTP header 传递:++```text+X-MinerU-Source: cli | sdk | http_api | watch | background | unknown+X-MinerU-Caller: agent | user | sdk | http_client | system | unknown+```++server middleware 解析 header,写入 request context。route、service 和 telemetry emitter 从 request context 读取。request 结束时必须 reset contextvars token,避免上下文泄漏到后续请求。++默认规则:++- CLI 设置进程内 context 后,`DoclibClient` 发送 `source=cli`。+- SDK 直接创建 `DoclibClient` 时,默认 `source=sdk`,`caller` 仍由进程上下文 best-effort 推断。+- 外部 HTTP 请求缺少 header 时,server 默认 `source=http_api`、`caller=http_client`。+- HTTP header 值不在白名单时降级: invalid source -> `unknown`,invalid caller -> `unknown`。+- watch / background 等 server 内部任务不走 header,直接使用内部固定来源,例如 `source=watch`、`caller=system`。++caller 推断规则:++- 遍历父进程树,只读取进程名,不读取完整命令行、路径、参数或环境变量。+- 进程名统一取 basename 后转小写,再与白名单比较。+- 遍历最大深度固定为 12;遇到 `pid <= 1`、父 pid 重复、读取失败或达到最大深度时停止。+- 命中白名单时按优先级返回: `agent` 高于 `user`。即只要 12 层内出现已知 Agent 进程名,就返回 `agent`;否则若出现 shell / terminal 进程名,则返回 `user`;否则返回 `unknown`。+- 命中常见 Agent 进程名时返回 `agent`,例如 `codex`、`claude`、`cursor`、`windsurf`、`aider`、`gemini`、`qwen`、`cline`。+- 命中常见 shell / terminal 进程名时返回 `user`,例如 `bash`、`zsh`、`fish`、`Terminal`、`iTerm2`、`WindowsTerminal`。+- 权限不足、平台不支持、进程树读取失败或无法判断时返回 `unknown`。+- 进程名只用于本地枚举判断,不写入 telemetry 聚合或外部 payload。++第一版不做后台 task 的 `source/caller` 归因。`parse_task.*`、`scan.finished.count`、`scan.files.count`、`ingest.*` 等后台执行指标不要求带 `source` / `caller`。用户或 Agent 来源通过入口请求指标和 `/observations` 观察。++## 9. 公共 Dimensions++所有用户行为类 metric 应尽量带:++```text+source+caller+status+```++取值:++```text+source = cli | sdk | http_api | watch | background | unknown+caller = agent | user | sdk | http_client | system | unknown+status = <metric-specific low-cardinality status>+```++按需补充:++```text+tier = default | flash | standard | pro | standard(default) | pro(default) | unknown+server = local(flash) | local(managed) | local(self-hosted) | remote(official) | remote(custom) | none | unknown+error_code = <telemetry_error_code>+bucket = <metric bucket value>+result = <metric-specific low-cardinality result>+content_mode = read | parse_output | export | unknown+output_format = markdown | image | other+trigger = parse | scan | watch | show | background | unknown+```++不得把路径、文件名、sha256、query、异常消息、traceback、URL、API Key、prompt 或文档内容放入 dimensions。++`status` 表示当前 metric 的业务状态。不同 metric 可以有不同枚举,但必须在 metric 定义中写清楚,且保持低基数。++`source` / `caller` 适用范围:++- 入口请求和调用方观察类指标应带 `source` / `caller`,例如 `parse.request.count`、`parse.finished.count`、`search.*`、`find.*`、`content.*`、`scan.request.count`、`watch.add.count`、`watch.remove.count`、`parse.wait.*`。+- 后台执行类指标不要求带 `source` / `caller`,例如 `parse_task.*`、`scan.finished.count`、`scan.duration_bucket.count`、`scan.files.count`、`ingest.*`。++`error_code` 规则:++- 第一版 `error_code` 只用于失败类结果 count metric,不用于 request metric、value metric、bucket metric,也不用于任何 duration bucket。+- 第一版会带 `error_code` 的 metric 只有:+ - `parse.finished.count`+ - `parse_task.finished.count`+ - `parse_task.execute.count`+ - `parse_task.write.count`+- 成功状态不带 `error_code`,不上传 `none`。+- metric 中的 `error_code` 必须来自第一版 whitelist:++```text+internal_error++invalid_request+file_not_found+file_permission_denied+not_cached+no_accessible_file++quality_tier_unavailable+no_engine+engine_unavailable+parse_server_unavailable+tier_mismatch+parse_failed+parse_timeout++metadata_failed+parse_json_write_failed+ingest_failed+scan_failed+```++- 不在 whitelist 的稳定错误码,第一版统一降级为 `internal_error`。++`tier` 归一化规则:++- `flash` / `standard` / `pro` 表示用户显式指定,或后台任务的实体 tier。+- `standard(default)` / `pro(default)` 只用于入口请求层指标,表示请求未显式指定 tier,但默认选择策略最终解析到了 `standard` 或 `pro`。+- `default` 只用于入口请求在默认 tier 解析完成前就失败,且调用方未显式指定 tier 的场景。+- `unknown` 表示无法安全判断。++`server` 归一化规则:++- `none`: 当前步骤不涉及 parse-server,例如 `flash` 本地解析。+- `local(managed)`: 命中 doclib 自己拉起并管理的 local parse-server,即 `parse_server.local.mode=managed`。+- `local(self-hosted)`: 命中用户自管的 local parse-server,即 `parse_server.local.mode=self_hosted`。+- `remote(official)`: 目标 URL 命中官方托管的 remote parse-server,包括 production 和 staging 等官方环境。+- `remote(custom)`: 使用 remote parse-server,但目标 URL 不属于官方托管环境。+- `local(flash)` 作为保留枚举,第一版如果 `parse_task.execute.*` 不经过 parse-server,可统一使用 `server=none`。+- 无法安全判断时记为 `unknown`。++### CLI / Client 改动++新增 CLI 文件:++```text+mineru/cli/commands/telemetry.py+```++更新:++```text+mineru/cli/commands/__init__.py+mineru/cli/main.py+```++`mineru` 顶层命令新增:++```bash+mineru telemetry status+mineru telemetry enable+mineru telemetry disable+mineru telemetry preview+mineru telemetry flush+```++`TOP_LEVEL_COMMAND_ORDER` 中放在 `config` 后:++```text+server+config+telemetry+```++输出规则:++- `status`: human 输出 consent、installation_id、pending aggregates、last_flush_at;支持 `--json`。+- `preview`: 默认 pretty JSON 输出 telemetry request body。+- `enable` / `disable` / `flush`: 输出 action result;支持 `--json`。+- server 未启动时沿用现有 CLI error 风格。++`DoclibClient` 新增方法:++```python+def get_telemetry_status(self) -> TelemetryStatusResponse: ...+def get_telemetry_preview(self) -> dict[str, Any]: ...+def telemetry_action(self, action: TelemetryAction) -> TelemetryActionResponse: ...+def submit_observation(self, request: ObservationRequest) -> ObservationResponse: ...+```++对应 route:++```text+GET /telemetry/status+GET /telemetry/preview+POST /telemetry/actions/{action}+POST /observations+```++`DoclibInterface` 和 `AsyncDoclibInterface` 也需要补对应抽象方法,保持当前接口模式。++CLI context:++- `mineru/cli/main.py` 增加 root callback。+- callback 设置 `source=cli`,`caller=infer_caller_from_process_tree()`。+- 不使用环境变量。+- 第一版实现 CLI 交互式且 `consent_state=unset` 时提示用户选择。+- CLI prompt 只在 stdin / stdout 是 TTY,且不在 CI 或明确非交互环境中触发。+- 非交互或 Agent 场景下不提示,维持 `consent_state=unset`。+- 用户也可以随时通过显式 `mineru telemetry ...` 命令查看和修改状态。++CLI prompt helper:++```python+def maybe_prompt_telemetry_consent(+ client: DoclibClient,+ *,+ json_mode: bool,+ command_name: str,+) -> None: ...+```++实现位置:++```text+mineru/cli/telemetry.py+```++职责:++- `is_interactive_cli()` 判断 stdin / stdout 是否为 TTY。+- `is_ci_environment()` 判断常见 CI 环境变量,例如 `CI`、`GITHUB_ACTIONS`、`GITLAB_CI`、`BUILDKITE`、`JENKINS_URL`。+- `maybe_prompt_telemetry_consent()` 查询 telemetry status,按规则提示用户,并调用 telemetry action。++调用时机:++- 各业务 CLI 命令创建 `DoclibClient` 后、发业务请求前调用。+- `mineru telemetry ...` 命令自身不调用。+- prompt 失败、status 查询失败或 action 调用失败时,不影响原业务命令继续执行。++`parse --wait` observation:++- `parse_cmd` 开始等待前记录 `wait_start = time.monotonic()`。+- 等到 done: 上报 `parse_wait {status=succeeded, duration_ms, parse_ids}`。+- 等到 failed: 先上报 `status=failed`,再按原逻辑报错。+- 超时: 上报 `status=timeout`。+- 用户取消,例如 Ctrl-C: 尽量上报 `status=canceled`,然后按原 CLI 取消逻辑退出。+- 上报失败静默忽略,不影响 CLI 输出。++### TelemetryService 采集 API++第一版使用少量通用 record API,不为每个 metric 单独定义专用方法:++```python+class TelemetryService:+ async def record_count(+ self,+ name: str,+ *,+ dimensions: Mapping[str, str] | None = None,+ value: int = 1,+ ) -> None: ...++ async def record_value(+ self,+ name: str,+ value: int,+ *,+ dimensions: Mapping[str, str] | None = None,+ ) -> None: ...++ async def record_duration(+ self,+ name: str,+ duration_ms: int,+ *,+ dimensions: Mapping[str, str] | None = None,+ ) -> None: ...++ async def record_bucket(+ self,+ name: str,+ bucket: str,+ *,+ dimensions: Mapping[str, str] | None = None,+ value: int = 1,+ ) -> None: ...+```++语义:++- `record_count`: 事件发生次数,例如 `parse.request.count`。+- `record_value`: 数值总和,例如 `parse.pages.count`、`scan.files.count`。+- `record_duration`: 根据 `duration_ms` 自动写入 duration bucket,调用方不传 bucket。+- `record_bucket`: 非 duration bucket,例如 pages、file size、results bucket。+- 第一版所有 `value` 必须是非负整数。+- `dimensions` 在 telemetry 层统一 normalize 和 whitelist 校验。+- unknown / invalid dimension value 降级为 `unknown` 或 `none`,不让任意字符串进入聚合。+- `consent_state=disabled` 时,所有 record 方法直接 no-op。+- `consent_state=unset` 或 `enabled` 时,record 方法写本地 aggregate。+- 本地 aggregate 写入可以 `await`,第一版不引入内存 queue。+- 本地 aggregate 写失败不重试,不影响主流程。++Metric allowed dimensions 映射:++- metric -> allowed dimensions 映射是 telemetry schema 的一部分,使用代码内存表,不放入数据库。+- `METRIC_SPECS` 放在 `mineru/doclib/telemetry/constants.py`。+- DB 只存 normalize 后的 `dimensions` JSON 和 `dimensions_hash`。+- 本地 telemetry 和外部 telemetry endpoint 都应按 `schema_version` 维护各自白名单。++示例:++```python+@dataclass(frozen=True)+class MetricSpec:+ allowed_dimensions: frozenset[str]+ required_dimensions: frozenset[str] = frozenset()+++METRIC_SPECS: dict[str, MetricSpec] = {+ "parse.request.count": MetricSpec(+ allowed_dimensions=frozenset({"source", "caller"}),+ ),+ "parse.finished.count": MetricSpec(+ allowed_dimensions=frozenset({"source", "caller", "status", "tier", "error_code"}),+ ),+ "parse.duration_bucket.count": MetricSpec(+ allowed_dimensions=frozenset({"source", "caller", "status", "tier", "bucket"}),+ ),+}+```++`required_dimensions` 第一版可用于测试和开发期校验;运行时缺失时按失败兜底规则降级或跳过,不向业务层抛错。++### 失败兜底规则++- telemetry 永远不能改变业务返回、异常类型或状态码。+- 所有 `record_*` 内部 catch `Exception`,不向外抛。+- 打点代码不得读取或传递 exception message、traceback、path、filename、query、sha256、parse_id。+- `error_code` 只允许使用稳定业务错误码,例如 `MineruError.code` 或 parse / scan row 的 `error_code`。不在 telemetry whitelist 内时统一降级为 `internal_error`。+- route 层失败时,可以用 `try/except Exception as exc` 计算 telemetry status / error_code,但必须重新 `raise` 原异常。+- duration 使用 `time.monotonic()`;DB timestamp 仍使用 ms epoch。+- 如果无法补齐必需维度,使用安全枚举值,例如 `status=failed` 或 `unknown`。+- 如果无法补齐非必需规模信息,例如 pages、file size,不记录对应规模 metric,不使用 `unknown` bucket。+- route-level request metric 在进入业务 handler 后立即记录;如果后续业务失败,request 仍保留,finished 记录 failed。+- FastAPI / Pydantic 在进入业务 handler 前拒绝的请求第一版不计。+- background task 的 source / caller 不做归因,不为此修改 `parses` 或 `scans` 表存来源快照。++## 10. Observations++有些体验信息只存在于 client / CLI / SDK 侧,server 自己无法观察,例如调用方等待了多久、是否超时、是否被取消。++第一版增加一个通用 observations 接口:++```text+POST /observations+```++request 必须使用白名单 type,不允许透传任意 dict。第一版支持:++```text+type = parse_wait+```++`parse_wait` 只记录低敏字段:++```json+{+ "type": "parse_wait",+ "duration_ms": 43120,+ "status": "succeeded",+ "refs": {+ "parse_ids": [123, 124]+ }+}+```++请求约束:++| 字段 | 类型 | 约束 |+|------|------|------|+| `type` | string | 第一版只允许 `parse_wait` |+| `duration_ms` | integer | `0 <= duration_ms <= 86400000` |+| `status` | string | `succeeded` / `failed` / `timeout` / `canceled` |+| `refs.parse_ids` | integer array | 非空,最多 200 个,元素必须为正整数 |++响应:++```json+{+ "accepted": true,+ "recorded": true,+ "reason": null+}+```++响应语义:++- `accepted=true`: server 接受了 observation 请求格式。+- `recorded=true`: observation 已写入 telemetry 聚合。+- `recorded=false`: 请求格式有效,但没有写入聚合,例如 telemetry disabled、`parse_ids` 全部查不到,或无法补齐必要低基数字段。+- `reason` 只在 `recorded=false` 时使用,第一版取值为 `telemetry_disabled | parse_refs_not_found | missing_dimensions`。+- schema 不合法时返回 HTTP 4xx,例如未知 `type`、字段类型错误、`duration_ms` 超限、`refs.parse_ids` 为空或过长。++server 收到 observation 后,根据 `parse_ids` 查询本地 DB 补齐 tier、页数、错误码等低基数字段,再写入 telemetry 聚合。++observation 写入失败不能影响主流程。`consent_state=disabled` 时,该接口应返回 `accepted=true, recorded=false, reason=telemetry_disabled`。`consent_state=unset` 时,可以写入本地聚合,但不会触发外部 flush。++第一版保持简单,不做 observation 幂等去重。client 上报失败可以丢失,重试导致的重复 observation 也可以接受。++第一版不增加 blocking wait API。`POST /parses` 继续保持非阻塞,CLI / client 通过轮询显示进度,并在等待结束后上报 `parse_wait` observation。++采集点位:++- `POST /observations` 只支持 `parse_wait`。+- schema 合法后,根据 `parse_ids` 查询 task,补齐 `tier` 和 `pages_bucket`。+- 记录 `parse.wait.count {source, caller, status, tier, pages_bucket}`。+- 记录 `parse.wait_duration_bucket.count {source, caller, status, tier, pages_bucket}`。+- `consent_state=disabled` 时返回 `accepted=true, recorded=false, reason=telemetry_disabled`。+- `parse_ids` 全部查不到时返回 `accepted=true, recorded=false, reason=parse_refs_not_found`。+- 无法补齐必要低基数字段时返回 `accepted=true, recorded=false, reason=missing_dimensions`。++## 11. 使用方式与频率++这些 metric 回答“谁在用、从哪里用、用什么能力、频率如何”。++```text+parse.request.count+scan.request.count+watch.add.count+watch.remove.count+search.request.count+find.request.count+content.request.count+```++口径:++- `parse.request.count`: doclib 收到一次 parse 业务请求。+- `scan.request.count`: doclib 收到一次 scan 请求,包括手动 scan、watch rescan、watch initial scan。+- `watch.add.count`: doclib 收到一次 watch add 配置请求。+- `watch.remove.count`: doclib 收到一次 watch remove 配置请求。+- `search.request.count`: doclib 收到一次全文搜索请求,不记录 query。+- `find.request.count`: doclib 收到一次文件名搜索请求,不记录 query。+- `content.request.count`: doclib 收到一次读取或导出内容请求,不记录内容。++除 `scan.request.count` 外,`*.request.count` 的计数边界是进入对应 doclib 业务 handler 之后。FastAPI / Pydantic 在进入业务 handler 前拒绝的 schema 错误、路由不存在、认证或连接层错误,第一版不计入 request metric。进入业务 handler 后发生的业务失败仍计入 request metric,并通过对应 `*.finished.count {status=failed}` 表达结果。`scan.request.count` 额外覆盖 internal watch-triggered scan 创建。++这些 metric 不带 `command` 维度。能力类型已经由 metric name 表达。++采集点位总则:++- request metric 默认由 `DoclibServer` route 层记录,不在 service 层重复记录;`scan.request.count` 是唯一例外,internal watch-triggered scan 也记。+- route 进入业务 handler 后立即记录对应 `*.request.count`。+- route 层负责入口体验指标,例如 finished、duration、results bucket、content mode。+- service / worker 层负责后台执行指标,例如 `parse_task.*`、`scan.finished.count`、`scan.files.count`、`ingest.*`。++## 12. 用户满意度: Parse 请求层++`parse.*` 表示调用方感知到的 parse 请求体验。一次请求可能 cache hit、复用已有任务、创建新任务、等待任务完成,或直接返回 queued。++```text+parse.finished.count+parse.duration_bucket.count++parse.wait.count+parse.wait_duration_bucket.count++parse.files.count+parse.pages.count+parse.file_size_bucket.count+parse.pages_bucket.count++parse.invalidate.count+```++口径:++- `parse.finished.count`: `POST /parses` 请求返回给调用方的状态。+- `parse.duration_bucket.count`: 从进入 doclib parse 请求到 `POST /parses` 返回的耗时分布。+- `parse.wait.count`: 调用方等待后台 parse task 的结果,由 `parse_wait` observation 采集。+- `parse.wait_duration_bucket.count`: 调用方等待后台 task 的真实耗时分布,由 `parse_wait` observation 采集。+- `parse.files.count`: 请求涉及的文件数。第一版通常为 1。+- `parse.pages.count`: 请求涉及的页数,只记录数量,不记录页码列表。+- `parse.file_size_bucket.count`: 请求文件大小分布。+- `parse.pages_bucket.count`: 请求页数分布。+- `parse.invalidate.count`: 用户主动让已完成 parse 结果失效。++推荐状态:++```text+parse.finished.count:+ status = cached | direct | reused | queued | failed++parse.wait.count:+ status = succeeded | failed | timeout | canceled++parse.invalidate.count:+ status = succeeded | failed | skipped+```++说明:++- `cached` 表示请求所需内容已在本地 cache 中,`POST /parses` 立即返回可读取结果。+- `direct` 表示请求无需创建后台 parse task,doclib 直接完成,例如 plain text 文件不需要异步解析。+- `reused` 表示请求复用了已有 pending / parsing task,没有创建新的 parse task。+- `queued` 表示请求创建了新的后台 parse task。+- 当前代码映射规则: `cache_hit=True` -> `cached`;plain text response -> `direct`;`reused_parse_ids` 非空且 `created_parse_ids` 为空 -> `reused`;`created_parse_ids` 非空 -> `queued`;`ParseResponse.status=failed` 或 route 抛出异常 -> `failed`。+- `parse.finished.count {status=queued}` 已表示本次请求需要后台 task,因此不再用 `parse.wait.count` 记录 `required` / `not_required`。+- `parse.wait.count {status=succeeded|failed|timeout|canceled}` 和 `parse.wait_duration_bucket.count` 只由 `parse_wait` observation 记录。+- `parse.wait.*` 只覆盖使用 CLI / `DoclibClient` wait helper 的调用方。直接 HTTP 调用方如果只调用 `POST /parses` 而不上报 observation,不会产生 wait 指标。+- `parse.wait.*` 不是所有 `parse.finished.count {status=queued}` 的完整子集统计,只表示客户端明确上报过 observation 的等待行为。+- 第一版 `parse.wait.*` 不带 `error_code`。+- `parse.wait_duration_bucket.count` 应带 `tier`、`pages_bucket`。这两个维度从 `parse_ids` 对应的 task 中读取。+- 同一次 wait observation 包含多个 `parse_ids` 时,`pages_bucket` 使用这些 task 页数之和;通常这些 task 属于同一 tier。如果发现多个 tier,`tier=unknown`。+- `cached`、`direct`、`reused` 通常不会产生新的 `parse_task.created.count`。+- `force=True` 会跳过 cache lookup,通常表现为 `queued` 或 `reused`。+- `parse.files.count`、`parse.pages.count`、`parse.file_size_bucket.count`、`parse.pages_bucket.count` 只在对应信息可获得时记录。如果请求在 ingest 或 metadata 可用前失败,缺失的规模指标不记录,不使用 `unknown` bucket。+- `parse.finished.count {status=failed}` 的 `tier` 规则:+ - 调用方显式指定 tier 且请求失败时,使用该显式 tier。+ - 调用方未显式指定 tier,且在默认 tier 解析完成前就失败时,使用 `default`。+ - 调用方未显式指定 tier,但默认选择策略已明确解析到了实体 tier 后才失败时,使用 `standard(default)` 或 `pro(default)`。++采集点位:++- `DoclibServer.ensure_parse` 进入 handler 后记录 `parse.request.count {source, caller}`。+- `DoclibServer.ensure_parse` 正常返回后记录 `parse.finished.count {source, caller, status, tier}`。+- `DoclibServer.ensure_parse` 正常返回或抛出异常时记录 `parse.duration_bucket.count {source, caller, status, tier}`。+- `DoclibServer.ensure_parse` 抛出异常时,`parse.finished.count` 的 `status=failed`,`error_code` 使用稳定业务错误码;没有则使用 `internal_error`。+- `DoclibServer.ensure_parse` 能拿到文件 metadata 时记录 `parse.files.count`、`parse.pages.count`、`parse.file_size_bucket.count`、`parse.pages_bucket.count`。+- `DoclibServer.invalidate` 成功且 `invalidated_count > 0` 时记录 `parse.invalidate.count {status=succeeded}`。+- `DoclibServer.invalidate` 成功但 `invalidated_count = 0` 时记录 `parse.invalidate.count {status=skipped}`。+- `DoclibServer.invalidate` 抛出异常时记录 `parse.invalidate.count {status=failed}`,然后重新抛出原异常。++## 13. 用户满意度: Parse 后台任务层++`parse_task.*` 表示 doclib worker 实际执行的异步 parse 任务。它对应 `parses` 表中的任务实体,不等同于入口请求。++```text+parse_task.created.count+parse_task.started.count+parse_task.finished.count+parse_task.duration_bucket.count++parse_task.execute.count+parse_task.execute_duration_bucket.count+parse_task.write.count+parse_task.write_duration_bucket.count++parse_task.files.count+parse_task.pages.count+```++口径:++- `parse_task.created.count`: doclib 创建新的后台 parse task。+- `parse_task.started.count`: worker 获取 task 并开始执行。+- `parse_task.finished.count`: 后台 task 完成,按成功或失败区分。+- `parse_task.duration_bucket.count`: 从 worker 开始执行到 task 完成的耗时分布。+- `parse_task.execute.count`: 实际解析执行步骤结果。+- `parse_task.execute_duration_bucket.count`: 实际解析执行步骤耗时分布。+- `parse_task.write.count`: 写 Middle JSON、更新 FTS、更新 doc metadata 的步骤结果。+- `parse_task.write_duration_bucket.count`: write 步骤耗时分布。+- `parse_task.files.count`: 后台 task 实际处理文件数。第一版通常为 1。+- `parse_task.pages.count`: 后台 task 实际处理页数。++推荐状态:++```text+parse_task.finished.count:+ status = succeeded | failed++parse_task.execute.count:+ status = succeeded | failed++parse_task.write.count:+ status = succeeded | failed+```++采集要求:++- `parse_task.created.count` 必须在所有 `parses` row 创建点记录,包括显式 `POST /parses` 和 ingest 自动创建的初始 parse task。+- `parse_task.started.count` 应在 worker acquire task 成功后记录。+- `parse_task.finished.count` 应覆盖 service 内失败和 worker fallback 异常处理。+- 第一版 `parse_task.*` 不带 `source` / `caller`。不需要为后台 task 增加来源快照存储。+- `parse_task.execute.*` 覆盖 `_parse_via_local` / `_parse_via_api` 的实际解析执行。+- `parse_task.write.*` 覆盖解析后所有后续操作,包括 Middle JSON 写入、FTS 更新和 docs metadata 更新。+- 如果 FTS 更新或 docs metadata 更新失败,应同时记录 `parse_task.write.count {status=failed}` 和 `parse_task.finished.count {status=failed}`。+- step metric 只在 step 已开始后记录。execute 失败时不记录 write;write 未开始时不记录 `parse_task.write.*`。++`parse_task.execute.*` 应带 `server` 维度:++```text+server = local(flash) | local(managed) | local(self-hosted) | remote(official) | remote(custom) | unknown+```++因此第一版不再单独使用 `parse_server.*` metric。parse-server 使用情况通过:++```text+parse_task.execute.count {server=local(managed)}+parse_task.execute.count {server=remote(official)}+parse_task.execute_duration_bucket.count {server=local(self-hosted)}+```++表达。++采集点位:++- `ParseService.request_parse` 新建 `parses` row 后记录 `parse_task.created.count {tier}`。+- `ParseService.ingest_file` 自动创建初始 parse row 后记录 `parse_task.created.count {tier}`。+- `ParseService.acquire_task` 成功返回 task 后记录 `parse_task.started.count {tier}`。+- `ParseService.process_doc` 从开始执行到 task 成功或失败,记录 `parse_task.finished.count {status, tier, error_code}`。+- `parse_task.finished.count {status=failed}` 的 `error_code` 来源优先级:+ 1. 如果 execute 步骤失败,使用 execute 步骤的失败码。+ 2. 否则如果 write 步骤失败,使用 write 步骤的失败码。+ 3. 否则如果 worker fallback 或其它未归类异常导致 task failed,使用 `parse_failed`;若没有稳定失败码可用,再降级为 `internal_error`。+- `ParseService.process_doc` 从开始执行到 task 成功或失败,记录 `parse_task.duration_bucket.count {status, tier}`。+- `ParseService.process_doc` 能拿到 task 页数时记录 `parse_task.files.count` 和 `parse_task.pages.count`。+- `_parse_via_local` / `_parse_via_api` 周围记录 `parse_task.execute.count {status, tier, server, error_code}`。+- `_parse_via_local` / `_parse_via_api` 周围记录 `parse_task.execute_duration_bucket.count {status, tier, server}`。+- JSON 写入、FTS 更新、docs metadata 更新作为一个 write 步骤,记录 `parse_task.write.count {status, tier, error_code}`。+- write 步骤记录 `parse_task.write_duration_bucket.count {status, tier}`。+- execute 失败时不记录 write。+- write 未开始时不记录 `parse_task.write.*`。+- FTS 更新或 docs metadata 更新失败时,同时记录 `parse_task.write.count {status=failed}` 和 `parse_task.finished.count {status=failed}`。+- `ParseWorkerPool` fallback exception 路径也必须记录 `parse_task.finished.count {status=failed}`,避免 service 外异常漏记。++## 14. Ingest++`ingest.*` 表示 doclib 发现文件后读取文件状态、计算 sha256、提取 metadata、创建 doc/file 记录和默认 parse task 的过程。++```text+ingest.finished.count+ingest.duration_bucket.count+```++口径:++- `ingest.finished.count`: ingest 完成结果。+- `ingest.duration_bucket.count`: ingest 耗时分布。++推荐状态:++```text+status = succeeded | failed | skipped+```++说明:++- ingest 可由 parse、scan、watch、show file 等路径触发。+- ingest 失败会影响用户是否能 parse / search / read,因此进入第一版。+- `ingest.*` 应带 `trigger` 维度,表示触发来源: `parse | scan | watch | show | background | unknown`。+- `trigger=parse`: `POST /parses` 路径触发同步 ingest。+- `trigger=scan`: scan service 刷新文件时触发 ingest。+- `trigger=watch`: watch filesystem event 直接刷新文件时触发 ingest。+- `trigger=show`: `show file`、`get_file_by_path` 或 `get_doc_by_path` 这类状态查询触发 ingest。+- `trigger=background`: ingest worker 处理 backlog 文件。+- 不记录路径、文件名或具体 metadata 内容。++采集点位:++- `ParseService.refresh_file`、`ensure_ingested`、`ingest_file` 增加 keyword-only `trigger` 参数,默认 `unknown`。+- `POST /parses` 路径调用 ingest 时传 `trigger=parse`。+- scan service 刷新文件时传 `trigger=scan`。+- `get_doc_by_path`、`get_file_by_path` 等状态查询触发 ingest 时传 `trigger=show`。+- watch filesystem event 直接 refresh 文件时传 `trigger=watch`。+- ingest worker 处理 backlog 文件时传 `trigger=background`。+- `ingest_file` 完成后记录 `ingest.finished.count {trigger, status}`。+- `ingest_file` 完成后记录 `ingest.duration_bucket.count {trigger, status}`。+- 第一版只在进入 ingest path 后记录 `ingest.*`。+- 不支持、无需 ingest 或已有 sha256 且未变化时,如果已经进入 ingest path,可以记为 `status=skipped`。+- 普通 `refresh_file` 判断为 known 且未调用 `ingest_file` 时,不强制记录 `ingest.finished.count {status=skipped}`,避免 scan 噪音。+- ingest 抛出异常时记录 `status=failed`,然后重新抛出原异常。++## 15. Search / Find / Content 体验++这些 metric 回答非 parse 请求是否成功、耗时如何、返回规模如何。++```text+search.finished.count+search.duration_bucket.count+search.results_bucket.count++find.finished.count+find.duration_bucket.count+find.results_bucket.count++content.finished.count+content.duration_bucket.count+```++口径:++- `search.finished.count`: 全文搜索请求结果,不记录 query 或结果内容。+- `search.duration_bucket.count`: 全文搜索耗时分布。+- `search.results_bucket.count`: 全文搜索返回数量分布。+- `find.finished.count`: 文件名搜索请求结果,不记录 query 或结果内容。+- `find.duration_bucket.count`: 文件名搜索耗时分布。+- `find.results_bucket.count`: 文件名搜索返回数量分布。+- `content.finished.count`: 内容读取或导出请求结果,不记录内容。+- `content.duration_bucket.count`: 内容读取或导出耗时分布。+- 第一版 content 指标不记录输出大小。即使 `output_format=image` 生成本地 temp asset,也只记录 `content_mode`、`output_format`、`tier`、`status` 和耗时。++推荐状态:++```text+status = succeeded | failed+```++`content.*` 应带:++```text+tier+content_mode = read | parse_output | export+output_format = markdown | image | other+```++`content_mode=read` 表示 `/content` locator 读取,`parse_output` 表示 `/docs/{sha256}/content` 读取 parse 输出,`export` 表示 `/docs/{sha256}/exports` 写出文件。++`output_format` 映射规则:++- `GET /docs/{sha256}/content` 根据调用方传入的 raw format 归一化:`markdown -> markdown`,`image -> image`,其它值 -> `other`。当前实现里只有 `markdown` 会成功,`image` 和 `other` 都会按原逻辑报错。+- `GET /content` 使用 `request.format`,当前合法值是 `markdown | image`。+- `POST /docs/{sha256}/exports` 当前实现只支持导出 markdown 文件;`request.format=="markdown"` 记为 `markdown`,`request.format=="image"` 记为 `image`,其余值记为 `other`。+- `other` 主要用于 route 已进入 handler,但请求中的 format 不是第一版已知枚举的失败场景;不是一个鼓励成功使用的输出格式。++采集点位:++- `DoclibServer.search` 进入 handler 后记录 `search.request.count {source, caller}`。+- `DoclibServer.search` 返回或抛出异常时记录 `search.finished.count {source, caller, status}`。+- `DoclibServer.search` 返回或抛出异常时记录 `search.duration_bucket.count {source, caller, status}`。+- `DoclibServer.search` 正常返回后记录 `search.results_bucket.count {source, caller, bucket}`,bucket 根据返回结果总数计算。+- `DoclibServer.find` 同理记录 `find.request.count`、`find.finished.count`、`find.duration_bucket.count`、`find.results_bucket.count`。+- `DoclibServer.get_doc_content` 使用 `content_mode=parse_output`。+- `DoclibServer.read_content` 使用 `content_mode=read`。+- `DoclibServer.export_doc_content` 使用 `content_mode=export`。+- content route 进入 handler 后记录 `content.request.count {source, caller, content_mode, output_format}`。+- content route 返回或抛出异常时记录 `content.finished.count {source, caller, content_mode, output_format, tier, status}`。+- content route 返回或抛出异常时记录 `content.duration_bucket.count {source, caller, content_mode, output_format, tier, status}`。+- search / find 不记录 query、snippet、filename、path 或结果内容。+- content 不记录正文、图片内容、输出路径或输出大小。++## 16. Scan / Watch 轻量体验++第一版记录 scan 入口请求、复用、最终结果和文件处理结果。watch 只记录配置请求,不展开完整 watch event 流。++```text+scan.finished.count+scan.duration_bucket.count+scan.reuse.count+scan.files.count++watch.add.finished.count+watch.remove.finished.count+```++口径:++- `scan.finished.count`: scan task 完成结果,包括 manual scan 和 watch scan。+- `scan.duration_bucket.count`: scan task 耗时分布。+- `scan.reuse.count`: scan 请求是否复用已有 pending / running scan task。+- `scan.files.count`: scan task 处理的文件数,按结果分类累计。+- `watch.add.finished.count`: watch add 配置请求结果。+- `watch.remove.finished.count`: watch remove 配置请求结果。++推荐状态:++```text+scan.finished.count:+ status = succeeded | failed++scan.reuse.count:+ status = hit | miss++scan.files.count:+ result = seen | refreshed | new | changed | deleted | unreachable | error | unsupported | excluded++watch.add.finished.count:+ status = succeeded | failed++watch.remove.finished.count:+ status = succeeded | failed+```++说明:++- `mineru watch rescan` 记为 `scan.request.count` / `scan.finished.count`,不记为 `watch.add.count` 或 `watch.remove.count`。+- watch loop initial scan 也记为 scan,`source=watch`、`caller=system`。+- watch filesystem event 直接 refresh 文件,第一版不展开为 `watch_task.*`。+- `scan.files.count` 的 `value` 为对应 `result` 的文件数,不是 scan task 次数。++采集点位:++- `DoclibServer.create_scan` 进入 handler 后记录 `scan.request.count {source, caller}`。+- watch initial scan 和 watch rescan 在内部创建 scan task 时也记录 `scan.request.count {source=watch, caller=system}`。+- `ScanService.create_scan` 发现已有 pending / running scan 并复用时,记录 `scan.reuse.count {status=hit}`。+- `ScanService.create_scan` 新建 scan row 时,记录 `scan.reuse.count {status=miss}`。+- `ScanService.process_scan` 完成后记录 `scan.finished.count {status=succeeded|failed}`。+- `ScanService.process_scan` 完成后记录 `scan.duration_bucket.count {status=succeeded|failed}`。+- `ScanService.process_scan` 完成后根据 `_ScanCounters` 记录 `scan.files.count {result=...}`,value 为对应文件数量。+- `_ScanCounters.files_seen` -> `scan.files.count {result=seen}`。+- `_ScanCounters.files_refreshed` -> `scan.files.count {result=refreshed}`。+- `_ScanCounters.files_new` -> `scan.files.count {result=new}`。+- `_ScanCounters.files_changed` -> `scan.files.count {result=changed}`。+- `_ScanCounters.files_deleted` -> `scan.files.count {result=deleted}`。+- `_ScanCounters.files_unreachable` -> `scan.files.count {result=unreachable}`。+- `_ScanCounters.files_error` -> `scan.files.count {result=error}`。+- `_ScanCounters.files_unsupported` -> `scan.files.count {result=unsupported}`。+- `_ScanCounters.files_excluded` -> `scan.files.count {result=excluded}`。+- `DoclibServer.add_watch` 进入 handler 后记录 `watch.add.count {source, caller}`。+- `DoclibServer.add_watch` 返回或抛出异常时记录 `watch.add.finished.count {source, caller, status}`。+- `DoclibServer.remove_watch` 进入 handler 后记录 `watch.remove.count {source, caller}`。+- `DoclibServer.remove_watch` 返回或抛出异常时记录 `watch.remove.finished.count {source, caller, status}`。++## 17. Bucket++耗时:++```text+lt_1s | 1_5s | 5_30s | 30_120s | 2_10m | gt_10m+```++页数:++```text+1 | 2_5 | 6_20 | 21_100 | 101_500 | gt_500+```++文件大小:++```text+lt_1mb | 1_10mb | 10_50mb | 50_200mb | gt_200mb+```++搜索结果数:++```text+0 | 1_5 | 6_20 | 21_100 | gt_100+```++Bucket 边界统一使用左闭右开区间,最后一个 bucket 右侧无界。例如 `1_5s` 表示 `[1s, 5s)`,`gt_10m` 表示 `[10m, +inf)`。++## 18. 测试与验收++第一版测试分四层,不要求做真实外网端到端测试。++Unit tests:++- `buckets.py`: duration、pages、file size、results bucket 边界。+- `context.py` / `caller.py`: contextvars set/get/reset、missing header 默认值、invalid header 降级、caller 推断失败返回 `unknown`。+- `store.py`: 初始化生成 `installation_id`、默认 `consent_state=unset`、aggregate upsert 累加、disabled 后 record no-op、disable 清空 aggregates 但不删除 `installation_id`。+- `payload.py`: preview payload schema、dimensions 稳定排序/hash、不包含 forbidden fields、空 metrics 仍返回合法 batch。++Route / service tests:++- telemetry management API: status、preview、enable、disable、flush 在 unset/disabled 返回 `executed=false`。+- observations: valid `parse_wait` -> `recorded=true`;disabled -> `recorded=false, reason=telemetry_disabled`;invalid duration / empty parse_ids -> HTTP 4xx;parse_ids 查不到 -> `recorded=false, reason=parse_refs_not_found`;缺少必要维度 -> `recorded=false, reason=missing_dimensions`。+- parse route: `parse.request.count`、`parse.finished.count` 的 cached/direct/reused/queued/failed 映射、`parse.duration_bucket.count` 带 status。+- scan/search/content/watch route: request / finished / duration 基本打点、search/find results bucket、content mode 映射、watch add/remove success/failed。++CLI prompt tests:++- unset + TTY + user -> prompt。+- unset + `--json` -> no prompt。+- unset + CI -> no prompt。+- unset + caller agent -> no prompt。+- user chooses yes / Enter -> calls enable。+- user chooses no -> calls disable。+- EOF / invalid input -> remains unset and continues original command。+- Ctrl-C -> remains unset and exits via original CLI cancellation path。++Worker / service tests:++- parse task created / started / finished。+- execute succeeded / failed。+- write succeeded / failed。+- FTS 或 docs metadata 失败时同时记录 `parse_task.write.count {status=failed}` 和 `parse_task.finished.count {status=failed}`。+- scan files counters 正确映射到 `scan.files.count`。++Flush tests:++- unset 不外发。+- disabled 不外发。+- enabled + no metrics 不外发。+- enabled + metrics 调用 fake endpoint。+- 2xx 删除 rows。+- 5xx 保留 rows。+- 4xx 删除对应 batch rows,不更新 `last_flush_at`,记录 warning log。+- 至少一个 batch 2xx 成功时更新 `last_flush_at`。+- 全部 batch 失败时不更新 `last_flush_at`。+- `sent_batch_count` 和 `sent_metric_count` 只统计 2xx 成功接收的 batch / aggregate rows。+- flush lock 存在时跳过。+- 一次 flush 最多发送 10 个 period。+- 一个 HTTP 请求只包含一个 period。++验收标准:++- telemetry disabled 时不新增 aggregate rows。+- telemetry unset 时能写 aggregate,但不会外发。+- telemetry enabled 时能 preview 和 flush。+- 所有 telemetry 写入失败不影响业务 API。+- external payload 不包含 path、filename、query、sha256、parse_id、exception message、traceback。+- CLI `mineru telemetry status|enable|disable|preview|flush` 可用。+- CLI `parse --wait` 成功、失败、超时、取消路径都会尽量提交 `parse_wait` observation。++## 19. 第一版不做++以下指标延后:++- `cli.request.count`: CLI 进入 doclib 前的入口漏斗和早失败。+- `rules.*`: exclude / parsing rule 命中统计。+- `cleanup.*`: cleanup 用户请求和清理结果。+- `compaction.*`: parse batch compaction 维护指标。+- `watch_task.*`: watch loop 自动事件、文件发现、自动解析。+- `parse_server.*`: 使用 `parse_task.execute.*` + `server` 维度替代。+- `server.shutdown.count`、`server.recovered_stale_lock.count`: server 生命周期补充指标。+- blocking wait API: 第一版用 client polling + `/observations` 采集等待体验,不让 `POST /parses` 长时间阻塞。++这些后续可以作为新增 metric 加入,不影响第一版 schema。diff --git a/mineru/cli/commands/__init__.py b/mineru/cli/commands/__init__.pyindex e4223616..6b528a81 100644--- a/mineru/cli/commands/__init__.py+++ b/mineru/cli/commands/__init__.py@@ -12,6 +12,7 @@ from . import (search,server,show,+ telemetry,watch,)@@ -27,5 +28,6 @@ __all__ = ["search","server","show",+ "telemetry","watch",]diff --git a/mineru/cli/commands/parse.py b/mineru/cli/commands/parse.pyindex 133a2595..b7d3b746 100644--- a/mineru/cli/commands/parse.py+++ b/mineru/cli/commands/parse.py@@ -13,7 +13,15 @@ import typerfrom ...errors import MineruErrorfrom ...doclib.client import DoclibClient-from ...doclib.types import ContentNextRequest, DocContentExportRequest, DocContentResponse, ParseRequest, ParseResponse+from ...doclib.types import (+ ContentNextRequest,+ DocContentExportRequest,+ DocContentResponse,+ ParseRequest,+ ParseResponse,+ TelemetryObservation,+ TelemetryObservationsRequest,+)from ...types import Tierfrom ..json_errors import exit_with_errorfrom ..output import format_parse_result, print_error, print_info, print_json, print_success@@ -137,6 +145,7 @@ def parse_cmd(if verbose:print_info(f"Parse queued (tier={req_tier}). Waiting up to {wait}s...")+ wait_started_at = time.time()deadline = time.time() + waitinterval = 0.5while time.time() < deadline:@@ -155,6 +164,7 @@ def parse_cmd(print_info(f" Parse status: {st}")if st == "done":+ _record_parse_wait(client, wait_parse_ids, "succeeded", wait_started_at)done_result = result.model_copy(update={"status": "done"})_output_parse_result(client,@@ -170,11 +180,13 @@ def parse_cmd(returnif st == "failed":failed = next((row for row in parse_rows if row.status == "failed"), None)+ _record_parse_wait(client, wait_parse_ids, "failed", wait_started_at)exit_with_error(MineruError(failed.error_code if failed else "parse_failed", failed.error_msg if failed else "", None),json_mode=json_mode,)+ _record_parse_wait(client, wait_parse_ids, "timeout", wait_started_at)if json_mode:timeout_result = result.model_copy(update={"status": "parsing", "tip": "Re-run the same command to continue waiting."})_print_parse_json_response(timeout_result, None)@@ -182,6 +194,25 @@ def parse_cmd(print_info(f"Parse still in progress (tier={req_tier}). Check status with: mineru show file {file_path}")+def _record_parse_wait(client: DoclibClient, parse_ids: list[int], status: str, started_at: float) -> None:+ duration_ms = max(0, int((time.time() - started_at) * 1000))+ try:+ client.record_observations(+ TelemetryObservationsRequest(+ observations=[+ TelemetryObservation(+ metric_name="parse.wait",+ parse_ids=parse_ids,+ duration_ms=duration_ms,+ dimensions={"status": status},+ )+ ]+ )+ )+ except Exception:+ pass++if __name__ != "__main__":def _register(app: typer.Typer) -> None:diff --git a/mineru/cli/commands/server.py b/mineru/cli/commands/server.pyindex 339f1417..965b4226 100644--- a/mineru/cli/commands/server.py+++ b/mineru/cli/commands/server.py@@ -6,11 +6,13 @@ import osimport subprocessimport sysimport time+import uuidimport typerfrom ...config import config-from ...doclib.types import ServerStatusResponse+from ...doclib.endpoint import remove_endpoint_file+from ...doclib.types import ServerStatusResponse, TCPServerStatusfrom ...version import __version__from ..json_errors import exit_with_errorfrom ..output import format_server_status, print_error, print_info, print_success@@ -22,14 +24,112 @@ def _socket_path() -> str:return config.doclib.uds.path+def _endpoint_path() -> str:+ return config.doclib.endpoint_path++def _server_log_path() -> str:return os.path.expanduser(config.doclib.log.path)+def _server_start_lock_path() -> str:+ endpoint_dir = os.path.dirname(os.path.expanduser(_endpoint_path()))+ return os.path.join(endpoint_dir or ".", "doclib.start.lock")+++class _ServerStartLock:+ def __init__(self, path: str, *, timeout: float = 20.0, stale_after: float = 60.0) -> None:+ self._path = os.path.expanduser(path)+ self._timeout = timeout+ self._stale_after = stale_after+ self._token = f"{os.getpid()}:{time.time_ns()}:{uuid.uuid4().hex}"+ self._fd: int | None = None+ self.acquired = False++ def __enter__(self) -> "_ServerStartLock":+ parent = os.path.dirname(self._path)+ if parent:+ os.makedirs(parent, exist_ok=True)++ deadline = time.time() + self._timeout+ while time.time() < deadline:+ try:+ self._fd = os.open(self._path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)+ except FileExistsError:+ if _server_running():+ return self+ stale_token = self._stale_token()+ if stale_token is not None:+ self._remove_if_token(stale_token)+ continue+ time.sleep(0.2)+ else:+ self.acquired = True+ self._write_owner()+ return self++ if _server_running():+ return self+ raise RuntimeError("Another mineru server start is already in progress.")++ def __exit__(self, exc_type: object, exc: object, tb: object) -> None:+ if self.acquired:+ self._close_fd()+ self._remove_if_token(self._token)++ def _stale_token(self) -> str | None:+ if not self._is_stale_path(self._path):+ return None+ return self._read_token()++ def _is_stale_path(self, path: str) -> bool:+ try:+ return time.time() - os.path.getmtime(path) > self._stale_after+ except OSError:+ return False++ def _write_owner(self) -> None:+ try:+ if self._fd is None:+ return+ payload = f"token={self._token}\npid={os.getpid()}\ncreated_at={int(time.time())}\n"+ os.write(self._fd, payload.encode("utf-8"))+ os.fsync(self._fd)+ except OSError:+ pass++ def _read_token(self) -> str | None:+ try:+ with open(self._path, encoding="utf-8") as f:+ first_line = f.readline().strip()+ except OSError:+ return None+ if not first_line.startswith("token="):+ return None+ return first_line.removeprefix("token=")++ def _remove_if_token(self, expected_token: str | None) -> None:+ if expected_token is None:+ return+ if self._read_token() != expected_token:+ return+ try:+ os.unlink(self._path)+ except OSError:+ pass++ def _close_fd(self) -> None:+ if self._fd is None:+ return+ try:+ os.close(self._fd)+ except OSError:+ pass+ finally:+ self._fd = None++def _server_running() -> bool:- socket_path = _socket_path()- if not os.path.exists(socket_path):- return Falsetry:from ...doclib.client import DoclibClient@@ -40,18 +140,19 @@ def _server_running() -> bool:return False-def _wait_for_sock(timeout: float = 15.0) -> bool:- socket_path = _socket_path()+def _wait_for_server(timeout: float = 15.0) -> bool:deadline = time.time() + timeoutwhile time.time() < deadline:- if os.path.exists(socket_path):- time.sleep(0.3)- if _server_running():- return True+ if _server_running():+ return Truetime.sleep(0.3)return False+def _wait_for_sock(timeout: float = 15.0) -> bool:+ return _wait_for_server(timeout)++@app.command()def start() -> None:"""Start the mineru server in the background."""@@ -59,46 +160,53 @@ def start() -> None:print_info("Server is already running.")return- socket_path = _socket_path()- # Clean stale socket- try:- os.unlink(socket_path)- except OSError:- pass-log_path = _server_log_path()log_dir = os.path.dirname(log_path)if log_dir:os.makedirs(log_dir, exist_ok=True)try:- with open(log_path, "a", encoding="utf-8") as log_file:- log_file.write("\n--- mineru server start ---\n")- log_file.flush()- proc = subprocess.Popen(- [sys.executable, "-m", "mineru.doclib.app"],- stdout=log_file,- stderr=log_file,- start_new_session=True,- )-- if not _wait_for_sock():- proc.kill()- print_error(f"Server failed to start within 15 seconds. See log: {log_path}")- raise typer.Exit(1)+ with _ServerStartLock(_server_start_lock_path()) as start_lock:+ if not start_lock.acquired or _server_running():+ print_info("Server is already running.")+ return++ socket_path = _socket_path()+ # Clean stale socket+ try:+ os.unlink(socket_path)+ except OSError:+ pass+ remove_endpoint_file(_endpoint_path())++ with open(log_path, "a", encoding="utf-8") as log_file:+ log_file.write("\n--- mineru server start ---\n")+ log_file.flush()+ proc = subprocess.Popen(+ [sys.executable, "-m", "mineru.doclib.app"],+ stdout=log_file,+ stderr=log_file,+ start_new_session=True,+ )++ if not _wait_for_server():+ proc.kill()+ print_error(f"Server failed to start within 15 seconds. See log: {log_path}")+ raise typer.Exit(1)except typer.Exit:raiseexcept Exception as exc:print_error(f"Server failed to start: {exc}. See log: {log_path}")raise typer.Exit(1) from None- print_success(f"Server started (PID {proc.pid}). Socket: {socket_path}")+ print_success(f"Server started (PID {proc.pid}).")@app.command()def stop() -> None:"""Stop the mineru server gracefully."""if not _server_running():+ _cleanup_local_endpoint_files()print_info("Server is not running.")return@@ -111,10 +219,7 @@ def stop() -> None:passtime.sleep(0.5)- try:- os.unlink(_socket_path())- except OSError:- pass+ _cleanup_local_endpoint_files()print_success("Server stopped.")@@ -143,6 +248,7 @@ def status(json_mode: bool = typer.Option(False, "--json", help="JSON output"))data_dir=os.path.expanduser(config.doclib.data_dir),sqlite_path=os.path.expanduser(config.doclib.sqlite.path),log_path=os.path.expanduser(config.doclib.log.path),+ tcp=TCPServerStatus(enabled=False, host=None, port=None),),json_mode=True,)@@ -158,3 +264,11 @@ def status(json_mode: bool = typer.Option(False, "--json", help="JSON output"))format_server_status(data, json_mode=json_mode)except Exception as exc:exit_with_error(exc, json_mode=json_mode)+++def _cleanup_local_endpoint_files() -> None:+ try:+ os.unlink(_socket_path())+ except OSError:+ pass+ remove_endpoint_file(_endpoint_path())diff --git a/mineru/cli/commands/telemetry.py b/mineru/cli/commands/telemetry.pynew file mode 100644index 00000000..d7e01b42--- /dev/null+++ b/mineru/cli/commands/telemetry.py@@ -0,0 +1,80 @@+"""mineru telemetry — manage doclib telemetry."""++from __future__ import annotations++import json++import typer++from ...doclib.client import DoclibClient+from ..json_errors import exit_with_error+from ..output import print_json, print_success++app = typer.Typer(help="Telemetry management", no_args_is_help=True)++[email protected]("status")+def telemetry_status(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:+ """Show telemetry status."""+ try:+ data = _client().get_telemetry_status()+ except Exception as exc:+ exit_with_error(exc, json_mode=json_mode)+ if json_mode:+ print_json(data)+ return+ last_flush = data.last_flush_at if data.last_flush_at is not None else "never"+ print(f"state: {data.state}")+ print(f"installation_id: {data.installation_id}")+ print(f"pending_periods: {data.pending_periods}")+ print(f"pending_metrics: {data.pending_metrics}")+ print(f"last_flush_at: {last_flush}")++[email protected]("preview")+def telemetry_preview() -> None:+ """Print the next telemetry request body without sending it."""+ try:+ data = _client().get_telemetry_preview()+ except Exception as exc:+ exit_with_error(exc, json_mode=False)+ print(json.dumps(data.body.model_dump(mode="json"), ensure_ascii=False, indent=2, sort_keys=True))++[email protected]("enable")+def telemetry_enable(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:+ """Enable telemetry."""+ _run_action("enable", json_mode=json_mode)++[email protected]("disable")+def telemetry_disable(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:+ """Disable telemetry and clear pending local aggregates."""+ _run_action("disable", json_mode=json_mode)++[email protected]("flush")+def telemetry_flush(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:+ """Flush pending telemetry now when telemetry is enabled."""+ _run_action("flush", json_mode=json_mode)+++def _run_action(action: str, *, json_mode: bool) -> None:+ try:+ data = _client().telemetry_action(action)+ except Exception as exc:+ exit_with_error(exc, json_mode=json_mode)+ if json_mode:+ print_json(data)+ return+ if action == "flush":+ print_success(f"telemetry flush: {data.reason or 'success'}")+ return+ print_success(f"telemetry {data.state}")+++def _client() -> DoclibClient:+ return DoclibClient(timeout=30)+++__all__ = ["app"]diff --git a/mineru/cli/main.py b/mineru/cli/main.pyindex 441f8502..389cf447 100644--- a/mineru/cli/main.py+++ b/mineru/cli/main.py@@ -9,7 +9,8 @@ from click.core import Contextfrom typer.core import TyperGroupfrom ..types import Tier-from .commands import cleanup, config, list_resources, server, show, watch+from .commands import cleanup, config, list_resources, server, show, telemetry, watch+from .telemetry import prepare_cli_telemetryTOP_LEVEL_COMMAND_ORDER = ["parse",@@ -20,6 +21,7 @@ TOP_LEVEL_COMMAND_ORDER = ["find","list","show",+ "telemetry","server","config","invalidate",@@ -42,6 +44,11 @@ app = typer.Typer()+def root(ctx: typer.Context) -> None:+ prepare_cli_telemetry(ctx)++# top-level commands@app.command()def parse(@@ -152,6 +159,7 @@ def find(app.add_typer(list_resources.app, name="list")app.add_typer(show.app, name="show")+app.add_typer(telemetry.app, name="telemetry")app.add_typer(server.app, name="server")app.add_typer(config.app, name="config")diff --git a/mineru/cli/output.py b/mineru/cli/output.pyindex bf001027..3aed8114 100644--- a/mineru/cli/output.py+++ b/mineru/cli/output.py@@ -138,17 +138,15 @@ def format_server_status(data: Any, json_mode: bool = False) -> None:table.add_row("SQLite", _get(data, "sqlite_path", ""))table.add_row("SQLite size", _format_bytes(_get(data, "sqlite_size_bytes")))table.add_row("Log", _get(data, "log_path", ""))- http_data = _get(data, "http")- http_enabled = bool(_get(http_data, "enabled", False))- http_host = _get(http_data, "host", "") or "-"- http_port = _get(http_data, "port")- if http_enabled:- http_value = (- f"http://{http_host}:{http_port}" if http_port is not None else f"http://{http_host}:(pending)"- )+ tcp_data = _get(data, "tcp")+ tcp_enabled = bool(_get(tcp_data, "enabled", False))+ tcp_host = _get(tcp_data, "host", "") or "-"+ tcp_port = _get(tcp_data, "port")+ if tcp_enabled:+ tcp_value = f"http://{tcp_host}:{tcp_port}" if tcp_port is not None else f"http://{tcp_host}:(pending)"else:- http_value = "disabled"- table.add_row("HTTP", http_value)+ tcp_value = "disabled"+ table.add_row("TCP", tcp_value)table.add_row("Files tracked", str(_get(data, "files_total", 0)))table.add_row("Docs indexed", str(_get(data, "docs_total", 0)))table.add_row("Active scans", str(_get(data, "active_scan_count", 0)))diff --git a/mineru/cli/telemetry.py b/mineru/cli/telemetry.pynew file mode 100644index 00000000..784a1c83--- /dev/null+++ b/mineru/cli/telemetry.py@@ -0,0 +1,67 @@+"""CLI telemetry context and first-run prompt."""++from __future__ import annotations++import sys++import typer++from ..doclib.client import DoclibClient+from ..doclib.telemetry import infer_default_client_context, reset_telemetry_context, set_telemetry_context++PROMPT_COMMANDS = {+ "parse",+ "read",+ "scan",+ "watch",+ "search",+ "find",+ "list",+ "show",+ "invalidate",+ "forget",+ "cleanup",+}+++def prepare_cli_telemetry(ctx: typer.Context) -> None:+ token = set_telemetry_context(infer_default_client_context(source="cli"))+ ctx.call_on_close(lambda: reset_telemetry_context(token))+ command = _top_level_command(ctx)+ if command not in PROMPT_COMMANDS:+ return+ maybe_prompt_telemetry_consent()+++def maybe_prompt_telemetry_consent() -> None:+ if not _is_interactive():+ return+ try:+ client = DoclibClient(timeout=5)+ status = client.get_telemetry_status()+ except Exception:+ return+ if status.state != "unset":+ return++ typer.echo("MinerU can send anonymous, aggregated telemetry to help improve doclib.")+ enabled = typer.confirm("Enable telemetry?", default=True)+ try:+ client.telemetry_action("enable" if enabled else "disable")+ except Exception:+ return+++def _top_level_command(ctx: typer.Context) -> str | None:+ command = ctx.invoked_subcommand+ if command:+ return command+ args = list(getattr(ctx, "args", []) or [])+ return args[0] if args else None+++def _is_interactive() -> bool:+ return sys.stdin.isatty() and sys.stdout.isatty()+++__all__ = ["maybe_prompt_telemetry_consent", "prepare_cli_telemetry"]diff --git a/mineru/config.py b/mineru/config.pyindex cd57dea2..88b8edcb 100644--- a/mineru/config.py+++ b/mineru/config.py@@ -8,7 +8,7 @@ import osimport platformimport reimport socket-from typing import Any+from typing import Any, Literalimport yamlfrom pydantic import BaseModel, Field@@ -20,6 +20,8 @@ MINERU_HOME_ENV = "MINERU_HOME"MINERU_CONFIG_ENV = "MINERU_CONFIG"MINERU_ENV_PREFIX = "MINERU_"+AutoBool = Literal["auto"] | bool+_INTERPOLATION_RE = re.compile(r"\$\{(\w+)(?::-([^${}]*))?\}")@@ -46,11 +48,27 @@ def _default_uds_path() -> str:system = platform.system().lower()if system not in ("windows", "darwin", "linux"):raise RuntimeError(f"System [{system}] is not supported.")- if not _uds_available():- raise RuntimeError("Unix domain socket is not available.")return os.path.join(_mineru_home(), "doclib.sock")+def resolve_uds_enabled(cfg: "Config") -> bool:+ value = cfg.doclib.uds.enabled+ if value == "auto":+ return _uds_available()+ return value+++def resolve_tcp_enabled(cfg: "Config") -> bool:+ value = cfg.doclib.tcp.enabled+ if value == "auto":+ return not _uds_available()+ return value+++def _default_endpoint_path() -> str:+ return os.path.join(_mineru_home(), "doclib.endpoint.json")++def _default_log_path() -> str:return os.path.join(_mineru_home(), "doclib.log")@@ -166,7 +184,7 @@ def _apply_env_overrides(cfg: "Config", prefix: str = MINERU_ENV_PREFIX) -> "Conrebuilding Config.Examples:- MINERU_DOCLIB_HTTP_PORT=15981 -> config.doclib.http.port+ MINERU_DOCLIB_TCP_PORT=15981 -> config.doclib.tcp.portMINERU_DOCLIB_SQLITE_MMAP_SIZE=0 -> config.doclib.sqlite.mmap_size"""prefix_upper = prefix.upper()@@ -194,12 +212,13 @@ def _apply_env_overrides(cfg: "Config", prefix: str = MINERU_ENV_PREFIX) -> "Conclass UDSConfig(BaseModel):+ enabled: AutoBool = "auto"path: str = Field(default_factory=_default_uds_path)permission: int = 0o600-class HTTPConfig(BaseModel):- enabled: bool = False+class TCPConfig(BaseModel):+ enabled: AutoBool = "auto"host: str = "127.0.0.1"port: int = 15980strict_port: bool = False@@ -231,9 +250,10 @@ class DoclibConfig(BaseModel):"""uds: UDSConfig = Field(default_factory=UDSConfig)- http: HTTPConfig = Field(default_factory=HTTPConfig)+ tcp: TCPConfig = Field(default_factory=TCPConfig)log: LogConfig = Field(default_factory=LogConfig)sqlite: SQLiteConfig = Field(default_factory=SQLiteConfig)+ endpoint_path: str = Field(default_factory=_default_endpoint_path)data_dir: str = Field(default_factory=_default_data_path)ingest_workers: int = 2parse_workers: int = 2@@ -265,10 +285,11 @@ def PatchedConfig(**kwargs: Any) -> Config:__all__ = [+ "AutoBool","config","Config","DoclibConfig",- "HTTPConfig",+ "TCPConfig","LogConfig","SQLiteConfig","UDSConfig",@@ -276,4 +297,6 @@ __all__ = ["MINERU_HOME_ENV","MINERU_CONFIG_ENV","MINERU_ENV_PREFIX",+ "resolve_tcp_enabled",+ "resolve_uds_enabled",]diff --git a/mineru/doclib/app.py b/mineru/doclib/app.pyindex 439e666d..61e59625 100644--- a/mineru/doclib/app.py+++ b/mineru/doclib/app.py@@ -19,7 +19,8 @@ from fastapi import FastAPI, Requestfrom fastapi.responses import JSONResponsefrom ..errors import MineruError, error_response, http_status_for-from ..config import Config, LogConfig, _mineru_home, config+from ..config import Config, LogConfig, _mineru_home, config, resolve_tcp_enabled, resolve_uds_enabled+from .endpoint import EndpointTransport, remove_endpoint_file, uds_available, write_endpoint_filefrom .server import DoclibServerfrom .types import PARSE_STATUS_FAILED, PARSE_STATUS_PARSING@@ -42,6 +43,7 @@ def create_app(cfg: Config | None = None) -> FastAPI:from .background.parse_server_health import ParseServerHealthCheck, api_server_args_for_tier, get_healthfrom .background.parse_worker import ParseWorkerPoolfrom .background.scan_worker import ScanWorkerPool+ from .background.telemetry_flush import TelemetryFlushLoopfrom .background.watch import WatchLoopfrom .core.db import DatabaseManagerfrom .core.fts import FTSManager@@ -50,6 +52,7 @@ def create_app(cfg: Config | None = None) -> FastAPI:from .services.parse_svc import ParseServicefrom .services.scan_svc import ScanServicefrom .services.search_svc import SearchService+ from .telemetry import TelemetryService, TelemetryStoredata_dir = os.path.expanduser(cfg.doclib.data_dir)os.makedirs(data_dir, exist_ok=True)@@ -66,18 +69,22 @@ def create_app(cfg: Config | None = None) -> FastAPI:state.fts = FTSManager(state.db)state.config_svc = ConfigService(state.db)+ state.telemetry_svc = TelemetryService(TelemetryStore(state.db))+ await state.telemetry_svc.initialize()state.parse_svc = ParseService(state.db,state.fts,state.config_svc,data_dir,parse_lock_timeout_sec=cfg.doclib.parse_lock_timeout_sec,+ telemetry_svc=state.telemetry_svc,)state.scan_svc = ScanService(state.db,state.config_svc,state.parse_svc,scan_lock_timeout_sec=cfg.doclib.scan_lock_timeout_sec,+ telemetry_svc=state.telemetry_svc,)state.search_svc = SearchService(state.db, state.fts)state.cleanup_svc = CleanupService(state.db, data_dir)@@ -139,6 +146,7 @@ def create_app(cfg: Config | None = None) -> FastAPI:startup_grace_sec=cfg.doclib.parse_server_startup_grace_sec,stop_timeout_sec=cfg.doclib.parse_server_stop_timeout_sec,)+ state.telemetry_flush = TelemetryFlushLoop(state.telemetry_svc)_create_background_task(state, "watch", state.watch.run)_create_background_task(state, "scan_workers", state.scan_workers.run)@@ -147,6 +155,7 @@ def create_app(cfg: Config | None = None) -> FastAPI:_create_background_task(state, "device_monitor", state.device_monitor.run)_create_background_task(state, "compaction", state.compaction.run)_create_background_task(state, "health_check", state.health_check.run)+ _create_background_task(state, "telemetry_flush", state.telemetry_flush.run)state.start_time = time.time()state.pid = os.getpid()@@ -155,8 +164,8 @@ def create_app(cfg: Config | None = None) -> FastAPI:state.sqlite_path = db_pathstate.log_path = os.path.expanduser(cfg.doclib.log.path)state.socket_path = os.path.expanduser(cfg.doclib.uds.path)- state.http_enabled = cfg.doclib.http.enabled- state.http_host = cfg.doclib.http.host+ state.tcp_enabled = resolve_tcp_enabled(cfg)+ state.tcp_host = cfg.doclib.tcp.hoststate.config = cfg@app.on_event("shutdown")@@ -182,6 +191,7 @@ def create_app(cfg: Config | None = None) -> FastAPI:"device_monitor","compaction","health_check",+ "telemetry_flush",]:c = getattr(state, comp, None)if c and hasattr(c, "stop"):@@ -193,7 +203,19 @@ def create_app(cfg: Config | None = None) -> FastAPI:@app.middleware("http")async def attach_state(request: Request, call_next: Callable) -> Any:request.state.app = state- return await call_next(request)+ from .telemetry import TelemetryContext, reset_telemetry_context, set_telemetry_context++ source = request.headers.get("X-MinerU-Telemetry-Source") or "http_api"+ caller = request.headers.get("X-MinerU-Telemetry-Caller") or "http_client"+ if source not in {"cli", "sdk", "http_api", "watch", "background", "unknown"}:+ source = "unknown"+ if caller not in {"agent", "user", "sdk", "http_client", "system", "unknown"}:+ caller = "unknown"+ token = set_telemetry_context(TelemetryContext(source=source, caller=caller))+ try:+ return await call_next(request)+ finally:+ reset_telemetry_context(token)@app.exception_handler(MineruError)async def mineru_error_handler(_request: Request, exc: MineruError) -> JSONResponse:@@ -224,6 +246,7 @@ class AppState:self.scan_svc: Any = Noneself.search_svc: Any = Noneself.cleanup_svc: Any = None+ self.telemetry_svc: Any = Noneself.db_ready: asyncio.Event | None = Noneself.parse_server_proc: Any = Noneself.watch: Any = None@@ -233,6 +256,7 @@ class AppState:self.device_monitor: Any = Noneself.compaction: Any = Noneself.health_check: Any = None+ self.telemetry_flush: Any = Noneself.start_time: float = 0.0self.pid: int = 0self.mineru_home: str = ""@@ -240,9 +264,9 @@ class AppState:self.data_dir: str = ""self.sqlite_path: str = ""self.log_path: str = ""- self.http_enabled: bool = False- self.http_host: str = ""- self.http_port: int | None = None+ self.tcp_enabled: bool = False+ self.tcp_host: str = ""+ self.tcp_port: int | None = Noneself.config: Config | None = None@@ -257,6 +281,8 @@ REQUIRED_SCHEMA_TABLES = {"parses","parsing_rules","scans",+ "telemetry_aggregates",+ "telemetry_state","watches",}@@ -280,51 +306,71 @@ async def _run_after_db_ready(state: AppState, name: str, runner: Callable[[], Aawait runner()+def _format_transport(transport: EndpointTransport) -> str:+ if transport.type == "uds":+ return f"UDS {transport.path}"+ return f"TCP {transport.base_url}"++def main() -> None:"""Entry point: python -m mineru.doclib.app"""cfg = config- uds_path = cfg.doclib.uds.path+ uds_path = os.path.expanduser(cfg.doclib.uds.path)+ endpoint_path = os.path.expanduser(cfg.doclib.endpoint_path)+ uds_enabled = resolve_uds_enabled(cfg)+ tcp_enabled = resolve_tcp_enabled(cfg)- try:- os.unlink(uds_path)- except OSError:- pass+ if not uds_enabled and not tcp_enabled:+ raise RuntimeError("At least one doclib local transport must be enabled.")+ if uds_enabled and not uds_available():+ raise RuntimeError("Unix domain socket is enabled but is not available in this Python runtime. Enable doclib.tcp or disable doclib.uds.")app = create_app(cfg)uv_config = uvicorn.Config(app,lifespan="on",- timeout_keep_alive=cfg.doclib.http.timeout,+ timeout_keep_alive=cfg.doclib.tcp.timeout,)server = uvicorn.Server(uv_config)- uds_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- uds_sock.bind(uds_path)- os.chmod(uds_path, cfg.doclib.uds.permission)- uds_sock.listen(cfg.doclib.http.backlog)- sockets = [uds_sock]+ sockets: list[socket.socket] = []+ transports: list[EndpointTransport] = []- if cfg.doclib.http.enabled:+ if uds_enabled:+ try:+ os.unlink(uds_path)+ except OSError:+ pass+ uds_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ uds_sock.bind(uds_path)+ os.chmod(uds_path, cfg.doclib.uds.permission)+ uds_sock.listen(cfg.doclib.tcp.backlog)+ sockets.append(uds_sock)+ transports.append(EndpointTransport(type="uds", path=uds_path))++ if tcp_enabled:tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)tcp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)try:- tcp_sock.bind((cfg.doclib.http.host, cfg.doclib.http.port))+ tcp_sock.bind((cfg.doclib.tcp.host, cfg.doclib.tcp.port))except OSError as exc:- if exc.errno == errno.EADDRINUSE and not cfg.doclib.http.strict_port:- tcp_sock.bind((cfg.doclib.http.host, 0))+ if exc.errno == errno.EADDRINUSE and not cfg.doclib.tcp.strict_port:+ tcp_sock.bind((cfg.doclib.tcp.host, 0))port = tcp_sock.getsockname()[1]- print(f"Port {cfg.doclib.http.port} in use, using {port}")+ print(f"Port {cfg.doclib.tcp.port} in use, using {port}")else:raiseelse:- port = cfg.doclib.http.port- tcp_sock.listen(cfg.doclib.http.backlog)+ port = tcp_sock.getsockname()[1]+ tcp_sock.listen(cfg.doclib.tcp.backlog)sockets.append(tcp_sock)- app.state.doclib_state.http_port = port- print(f"MinerU server listening on UDS {uds_path} and TCP {cfg.doclib.http.host}:{port}")+ app.state.doclib_state.tcp_port = port+ transports.append(EndpointTransport(type="tcp", base_url=f"http://{cfg.doclib.tcp.host}:{port}"))else:- app.state.doclib_state.http_port = None- print(f"MinerU server listening on UDS {uds_path}")+ app.state.doclib_state.tcp_port = None++ write_endpoint_file(endpoint_path, pid=os.getpid(), transports=transports)+ print("MinerU server listening on " + " and ".join(_format_transport(transport) for transport in transports))loop = asyncio.new_event_loop()@@ -336,10 +382,12 @@ def main() -> None:except KeyboardInterrupt:passfinally:- try:- os.unlink(uds_path)- except OSError:- pass+ if uds_enabled:+ try:+ os.unlink(uds_path)+ except OSError:+ pass+ remove_endpoint_file(endpoint_path)loop.close()diff --git a/mineru/doclib/background/ingest.py b/mineru/doclib/background/ingest.pyindex 706eec8d..f883a19c 100644--- a/mineru/doclib/background/ingest.py+++ b/mineru/doclib/background/ingest.py@@ -49,7 +49,7 @@ class IngestWorkerPool:no_task_count = 0try:- await self.parse_svc.ingest_file(task["path"], watch_id=task.get("watch_id"))+ await self.parse_svc.ingest_file(task["path"], watch_id=task.get("watch_id"), trigger="background")processed += 1if processed % 100 == 0:logger.info(f"Ingest worker {worker_id} ingested {processed} files")diff --git a/mineru/doclib/background/parse_server_health.py b/mineru/doclib/background/parse_server_health.pyindex 883304df..c6038e67 100644--- a/mineru/doclib/background/parse_server_health.py+++ b/mineru/doclib/background/parse_server_health.py@@ -12,6 +12,7 @@ from typing import castimport httpx+from ...parser.api_client import should_trust_env_for_urlfrom ...types import TIERS, Tierlogger = logging.getLogger("mineru.health_check")@@ -155,7 +156,10 @@ class ParseServerHealthCheck:async def _probe(self, base_url: str) -> tuple[bool, list[Tier]]:try:- async with httpx.AsyncClient(timeout=self.probe_timeout_sec) as client:+ async with httpx.AsyncClient(+ timeout=self.probe_timeout_sec,+ trust_env=should_trust_env_for_url(base_url),+ ) as client:resp = await client.get(f"{base_url}/v1/tiers")if resp.status_code == 200:data = resp.json()diff --git a/mineru/doclib/background/telemetry_flush.py b/mineru/doclib/background/telemetry_flush.pynew file mode 100644index 00000000..fad75704--- /dev/null+++ b/mineru/doclib/background/telemetry_flush.py@@ -0,0 +1,40 @@+"""Background telemetry flush loop."""++from __future__ import annotations++import asyncio+import logging+from typing import Any++from ..telemetry.constants import TELEMETRY_FLUSH_INTERVAL_SEC++logger = logging.getLogger("mineru.doclib.telemetry")+++class TelemetryFlushLoop:+ def __init__(self, telemetry_svc: Any, *, interval_sec: int = TELEMETRY_FLUSH_INTERVAL_SEC) -> None:+ self.telemetry_svc = telemetry_svc+ self.interval_sec = interval_sec+ self.running = False+ self._stop_event = asyncio.Event()++ async def run(self) -> None:+ self.running = True+ try:+ while not self._stop_event.is_set():+ try:+ await self.telemetry_svc.flush_once()+ except Exception as exc:+ logger.debug("Telemetry flush loop failed: %s", exc)+ try:+ await asyncio.wait_for(self._stop_event.wait(), timeout=self.interval_sec)+ except TimeoutError:+ continue+ finally:+ self.running = False++ async def stop(self) -> None:+ self._stop_event.set()+++__all__ = ["TelemetryFlushLoop"]diff --git a/mineru/doclib/base.py b/mineru/doclib/base.pyindex 333c2fd0..e33f887d 100644--- a/mineru/doclib/base.py+++ b/mineru/doclib/base.py@@ -53,6 +53,12 @@ from .types import (SearchResponse,ServerStatusResponse,ShutdownResponse,+ TelemetryAction,+ TelemetryActionResponse,+ TelemetryObservationsRequest,+ TelemetryObservationsResponse,+ TelemetryPreviewResponse,+ TelemetryStatusResponse,WatchInfo,WatchListResponse,WatchRequest,@@ -500,6 +506,26 @@ class DoclibInterface(ABC):"""raise NotImplementedError()+ @abstractmethod+ def get_telemetry_status(self) -> TelemetryStatusResponse:+ """Return local telemetry state and pending aggregate counts."""+ raise NotImplementedError()++ @abstractmethod+ def get_telemetry_preview(self) -> TelemetryPreviewResponse:+ """Return the next telemetry request body without signing or sending it."""+ raise NotImplementedError()++ @abstractmethod+ def telemetry_action(self, action: TelemetryAction) -> TelemetryActionResponse:+ """Enable or disable telemetry."""+ raise NotImplementedError()++ @abstractmethod+ def record_observations(self, request: TelemetryObservationsRequest) -> TelemetryObservationsResponse:+ """Record client-side telemetry observations."""+ raise NotImplementedError()+class AsyncDoclibInterface(ABC):"""Asynchronous contract matching ``DoclibInterface`` method-for-method.@@ -748,3 +774,23 @@ class AsyncDoclibInterface(ABC):async def cleanup_temp_files(self, request: CleanupTempRequest) -> CleanupTempResponse:"""Async version of ``DoclibInterface.cleanup_temp_files``."""raise NotImplementedError()++ @abstractmethod+ async def get_telemetry_status(self) -> TelemetryStatusResponse:+ """Async version of ``DoclibInterface.get_telemetry_status``."""+ raise NotImplementedError()++ @abstractmethod+ async def get_telemetry_preview(self) -> TelemetryPreviewResponse:+ """Async version of ``DoclibInterface.get_telemetry_preview``."""+ raise NotImplementedError()++ @abstractmethod+ async def telemetry_action(self, action: TelemetryAction) -> TelemetryActionResponse:+ """Async version of ``DoclibInterface.telemetry_action``."""+ raise NotImplementedError()++ @abstractmethod+ async def record_observations(self, request: TelemetryObservationsRequest) -> TelemetryObservationsResponse:+ """Async version of ``DoclibInterface.record_observations``."""+ raise NotImplementedError()diff --git a/mineru/doclib/client.py b/mineru/doclib/client.pyindex 799a21d3..cf43491d 100644--- a/mineru/doclib/client.py+++ b/mineru/doclib/client.py@@ -3,16 +3,24 @@from __future__ import annotationsfrom collections.abc import Callable+from pathlib import Pathfrom typing import Any, Final, TypeVarimport httpxfrom pydantic import BaseModelfrom pydantic_core import to_jsonable_python-from ..config import configfrom ..errors import MineruError, ServerNotRunningErrorfrom ..types import Tierfrom .base import DoclibInterface+from .endpoint import (+ DOCLIB_UDS_BASE_URL,+ EndpointTransport,+ config_transports,+ default_endpoint_path,+ read_endpoint_file,+ uds_available,+)from .types import (CleanupDeletedRequest,CleanupDeletedResponse,@@ -61,14 +69,22 @@ from .types import (SearchResponse,ServerStatusResponse,ShutdownResponse,+ TelemetryAction,+ TelemetryActionResponse,+ TelemetryObservationsRequest,+ TelemetryObservationsResponse,+ TelemetryPreviewResponse,+ TelemetryStatusResponse,WatchInfo,WatchListResponse,WatchRequest,)+from .telemetry import get_telemetry_context, infer_default_client_context+from .telemetry.context import TelemetryContextfrom .utils.route_utils import get_route_info, routeT = TypeVar("T", bound=BaseModel)-_CONFIG_UDS_PATH: Final = object()+_DISCOVER_ENDPOINT: Final = object()class DoclibClient(DoclibInterface):@@ -77,19 +93,27 @@ class DoclibClient(DoclibInterface):def __init__(self,*,- base_url: str = "http://mineru",- socket_path: str | None | object = _CONFIG_UDS_PATH,+ endpoint_path: str | Path | None = None,+ socket_path: str | Path | None = None,+ base_url: str | None = None,timeout: int = 60,api_prefix: str = "/api/v1",) -> None:- if socket_path is _CONFIG_UDS_PATH:- socket_path = config.doclib.uds.path- transport = httpx.HTTPTransport(uds=socket_path) if isinstance(socket_path, str) and socket_path else None- self._client = httpx.Client(transport=transport, base_url=base_url, timeout=timeout)+ if socket_path is not None and base_url is not None:+ raise ValueError("socket_path and base_url cannot both be provided.")+ self._clients = _build_clients(+ endpoint_path=endpoint_path,+ socket_path=socket_path,+ base_url=base_url,+ timeout=timeout,+ )+ self._active_client: httpx.Client | None = self._clients[0] if self._clients else Noneself._api_prefix = api_prefix.rstrip("/")+ self._default_telemetry_context = infer_default_client_context(source="sdk")def close(self) -> None:- self._client.close()+ for client in self._clients:+ client.close()@route("GET", "/server/status", tags=("server",))def get_server_status(self) -> ServerStatusResponse:@@ -343,6 +367,22 @@ class DoclibClient(DoclibInterface):def cleanup_temp_files(self, request: CleanupTempRequest) -> CleanupTempResponse:return self._request_model(CleanupTempResponse, body=request)+ @route("GET", "/telemetry/status", tags=("telemetry",))+ def get_telemetry_status(self) -> TelemetryStatusResponse:+ return self._request_model(TelemetryStatusResponse)++ @route("GET", "/telemetry/preview", tags=("telemetry",))+ def get_telemetry_preview(self) -> TelemetryPreviewResponse:+ return self._request_model(TelemetryPreviewResponse)++ @route("POST", "/telemetry/actions/{action}", tags=("telemetry",))+ def telemetry_action(self, action: TelemetryAction) -> TelemetryActionResponse:+ return self._request_model(TelemetryActionResponse, path_params={"action": action})++ @route("POST", "/observations", tags=("telemetry",))+ def record_observations(self, request: TelemetryObservationsRequest) -> TelemetryObservationsResponse:+ return self._request_model(TelemetryObservationsResponse, body=request)+def _request_model(self,response_model: type[T],@@ -356,23 +396,59 @@ class DoclibClient(DoclibInterface):query_params = _compact_params(params or {})json_data = to_jsonable_python(body) if body is not None else None- try:- if route_info.method == "GET":- resp = self._client.get(path, params=query_params)- elif route_info.method == "POST":- resp = self._client.post(path, params=query_params, json=json_data or {})- elif route_info.method == "PUT":- resp = self._client.put(path, params=query_params, json=json_data or {})- elif route_info.method == "DELETE":- resp = self._client.delete(path, params=query_params)- else:- raise MineruError("internal_error", f"Unsupported client method: {route_info.method}")- except httpx.ConnectError:- raise ServerNotRunningError() from None+ resp = self._send_request(+ route_info.method,+ path,+ params=query_params,+ json_data=json_data,+ )data = _decode_response(resp)return response_model.model_validate(data)+ def _send_request(+ self,+ method: str,+ path: str,+ *,+ params: dict[str, Any],+ json_data: Any,+ ) -> httpx.Response:+ if not self._clients:+ raise ServerNotRunningError()+ clients = self._ordered_clients()+ for client in clients:+ try:+ if method == "GET":+ resp = client.get(path, params=params, headers=self._telemetry_headers())+ elif method == "POST":+ resp = client.post(path, params=params, json=json_data or {}, headers=self._telemetry_headers())+ elif method == "PUT":+ resp = client.put(path, params=params, json=json_data or {}, headers=self._telemetry_headers())+ elif method == "DELETE":+ resp = client.delete(path, params=params, headers=self._telemetry_headers())+ else:+ raise MineruError("internal_error", f"Unsupported client method: {method}")+ except httpx.ConnectError:+ continue+ self._active_client = client+ return resp+ raise ServerNotRunningError() from None++ def _ordered_clients(self) -> list[httpx.Client]:+ if self._active_client is None:+ return list(self._clients)+ return [self._active_client, *[client for client in self._clients if client is not self._active_client]]++ def _telemetry_headers(self) -> dict[str, str]:+ ctx = get_telemetry_context()+ if ctx == TelemetryContext():+ ctx = self._default_telemetry_context+ return {+ "X-MinerU-Telemetry-Source": ctx.source,+ "X-MinerU-Telemetry-Caller": ctx.caller,+ }+def _calling_route_method(self) -> Callable[..., Any]:import inspect@@ -393,6 +469,48 @@ def _compact_params(params: dict[str, Any]) -> dict[str, Any]:return {key: value for key, value in params.items() if value is not None}+def _build_clients(+ *,+ endpoint_path: str | Path | None,+ socket_path: str | Path | None,+ base_url: str | None,+ timeout: int,+) -> list[httpx.Client]:+ if socket_path is not None:+ client = _client_for_transport(EndpointTransport(type="uds", path=str(socket_path)), timeout=timeout)+ return [client] if client is not None else []+ if base_url is not None:+ client = _client_for_transport(EndpointTransport(type="tcp", base_url=base_url), timeout=timeout)+ return [client] if client is not None else []++ discovery_path = str(endpoint_path) if endpoint_path is not None else default_endpoint_path()+ transports = read_endpoint_file(discovery_path)+ if not transports:+ transports = config_transports()++ clients: list[httpx.Client] = []+ for transport in sorted(transports, key=lambda item: 0 if item.type == "uds" else 1):+ client = _client_for_transport(transport, timeout=timeout)+ if client is not None:+ clients.append(client)+ return clients+++def _client_for_transport(transport: EndpointTransport, *, timeout: int) -> httpx.Client | None:+ if transport.type == "uds":+ if not transport.path or not uds_available():+ return None+ return httpx.Client(+ transport=httpx.HTTPTransport(uds=transport.path),+ base_url=DOCLIB_UDS_BASE_URL,+ timeout=timeout,+ trust_env=False,+ )+ if not transport.base_url:+ return None+ return httpx.Client(base_url=transport.base_url, timeout=timeout, trust_env=False)++def _decode_response(resp: httpx.Response) -> dict[str, Any]:try:data = resp.json()diff --git a/mineru/doclib/endpoint.py b/mineru/doclib/endpoint.pynew file mode 100644index 00000000..c8dc9941--- /dev/null+++ b/mineru/doclib/endpoint.py@@ -0,0 +1,114 @@+"""Local doclib endpoint discovery helpers."""++from __future__ import annotations++import json+import os+import socket+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Literal++from ..config import Config, config, resolve_tcp_enabled, resolve_uds_enabled++TransportType = Literal["uds", "tcp"]+++@dataclass(frozen=True)+class EndpointTransport:+ type: TransportType+ path: str | None = None+ base_url: str | None = None+++DOCLIB_UDS_BASE_URL = "http://mineru"+ENDPOINT_VERSION = 1+++def uds_available() -> bool:+ try:+ socket.socket(socket.AF_UNIX, socket.SOCK_STREAM).close()+ return True+ except Exception:+ return False+++def default_endpoint_path(cfg: Config | None = None) -> str:+ cfg = config if cfg is None else cfg+ return os.path.expanduser(cfg.doclib.endpoint_path)+++def write_endpoint_file(path: str | os.PathLike[str], *, pid: int, transports: list[EndpointTransport]) -> None:+ endpoint_path = Path(path).expanduser()+ endpoint_path.parent.mkdir(parents=True, exist_ok=True)+ payload = {+ "version": ENDPOINT_VERSION,+ "pid": pid,+ "transports": [_transport_to_payload(transport) for transport in transports],+ }+ tmp_path = endpoint_path.with_name(f"{endpoint_path.name}.tmp")+ tmp_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")+ try:+ os.chmod(tmp_path, 0o600)+ except OSError:+ pass+ os.replace(tmp_path, endpoint_path)+++def remove_endpoint_file(path: str | os.PathLike[str]) -> None:+ try:+ Path(path).expanduser().unlink()+ except OSError:+ pass+++def read_endpoint_file(path: str | os.PathLike[str]) -> list[EndpointTransport]:+ endpoint_path = Path(path).expanduser()+ try:+ payload = json.loads(endpoint_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return []+ transports = payload.get("transports")+ if not isinstance(transports, list):+ return []+ return [_parse_transport(item) for item in transports if isinstance(item, dict)]+++def config_transports(cfg: Config | None = None) -> list[EndpointTransport]:+ cfg = config if cfg is None else cfg+ transports: list[EndpointTransport] = []+ if resolve_uds_enabled(cfg) and uds_available():+ transports.append(EndpointTransport(type="uds", path=os.path.expanduser(cfg.doclib.uds.path)))+ if resolve_tcp_enabled(cfg):+ transports.append(EndpointTransport(type="tcp", base_url=f"http://{cfg.doclib.tcp.host}:{cfg.doclib.tcp.port}"))+ return transports+++def _transport_to_payload(transport: EndpointTransport) -> dict[str, str]:+ if transport.type == "uds":+ return {"type": "uds", "path": transport.path or ""}+ return {"type": "tcp", "base_url": transport.base_url or ""}+++def _parse_transport(item: dict[str, Any]) -> EndpointTransport:+ transport_type = item.get("type")+ if transport_type == "uds":+ path = item.get("path")+ return EndpointTransport(type="uds", path=path if isinstance(path, str) else None)+ if transport_type == "tcp":+ base_url = item.get("base_url")+ return EndpointTransport(type="tcp", base_url=base_url if isinstance(base_url, str) else None)+ return EndpointTransport(type="tcp", base_url=None)+++__all__ = [+ "DOCLIB_UDS_BASE_URL",+ "ENDPOINT_VERSION",+ "EndpointTransport",+ "config_transports",+ "default_endpoint_path",+ "read_endpoint_file",+ "remove_endpoint_file",+ "uds_available",+ "write_endpoint_file",+]diff --git a/mineru/doclib/migrations/001_init.sql b/mineru/doclib/migrations/001_init.sqlindex 1b62db20..cce7d850 100644--- a/mineru/doclib/migrations/001_init.sql+++ b/mineru/doclib/migrations/001_init.sql@@ -152,6 +152,27 @@ CREATE TABLE IF NOT EXISTS config (value TEXT NOT NULL);+CREATE TABLE IF NOT EXISTS telemetry_state (+ key TEXT PRIMARY KEY,+ value TEXT NOT NULL,+ updated_at INTEGER NOT NULL+);++CREATE TABLE IF NOT EXISTS telemetry_aggregates (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ period_start INTEGER NOT NULL,+ period_end INTEGER NOT NULL,+ metric_name TEXT NOT NULL,+ metric_value INTEGER NOT NULL DEFAULT 0,+ dimensions TEXT NOT NULL,+ dimensions_hash TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ UNIQUE(period_start, period_end, metric_name, dimensions_hash)+);+CREATE INDEX IF NOT EXISTS idx_telemetry_aggregates_period+ON telemetry_aggregates(period_start, period_end);+CREATE TABLE IF NOT EXISTS _migrations (version INTEGER PRIMARY KEY,applied_at INTEGER NOT NULL,diff --git a/mineru/doclib/server.py b/mineru/doclib/server.pyindex 9ff9b69d..8f6e8ca0 100644--- a/mineru/doclib/server.py+++ b/mineru/doclib/server.py@@ -4,8 +4,8 @@ from __future__ import annotationsimport asyncioimport base64-import reimport os+import reimport signalimport sysimport time@@ -54,6 +54,7 @@ from .services.parse_svc import (parse_page_range_set,resolve_image_sidecar_path,)+from .telemetry.buckets import pages_bucket, results_bucketfrom .types import (FILE_STATUS_ACTIVE,FILE_STATUS_DELETED,@@ -99,7 +100,6 @@ from .types import (ForgetPathResponse,InvalidateRequest,InvalidateResponse,- HTTPServerStatus,ListDocsResponse,ListFilesResponse,ListParsesResponse,@@ -126,6 +126,15 @@ from .types import (SearchResult,ServerStatusResponse,ShutdownResponse,+ TCPServerStatus,+ TelemetryAction,+ TelemetryActionResponse,+ TelemetryObservation,+ TelemetryObservationsRequest,+ TelemetryObservationsResponse,+ TelemetryPayload,+ TelemetryPreviewResponse,+ TelemetryStatusResponse,TierParseInfo,WatchInfo,WatchListResponse,@@ -241,10 +250,10 @@ class DoclibServer(AsyncDoclibInterface):data_dir=getattr(self.state, "data_dir", ""),sqlite_path=sqlite_path,log_path=getattr(self.state, "log_path", ""),- http=HTTPServerStatus(- enabled=bool(getattr(self.state, "http_enabled", False)),- host=getattr(self.state, "http_host", "") or None,- port=getattr(self.state, "http_port", None),+ tcp=TCPServerStatus(+ enabled=bool(getattr(self.state, "tcp_enabled", False)),+ host=getattr(self.state, "tcp_host", "") or None,+ port=getattr(self.state, "tcp_port", None),),active_scan_count=active_scans["cnt"] if active_scans else 0,last_scan_at=last_scan["ts"] if last_scan else None,@@ -294,14 +303,27 @@ class DoclibServer(AsyncDoclibInterface):@route("POST", "/parses", tags=("parse",))async def ensure_parse(self, request: ParseRequest) -> ParseResponse:- result = await self.state.parse_svc.request_parse(- request.path,- tier=request.tier,- page_range=request.page_range,- force=request.force,- remote=request.remote,- )- return ParseResponse.model_validate(result)+ start_ms = _now_ms()+ await _record_telemetry_count(self.state, "parse.request.count")+ try:+ result = await self.state.parse_svc.request_parse(+ request.path,+ tier=request.tier,+ page_range=request.page_range,+ force=request.force,+ remote=request.remote,+ )+ response = ParseResponse.model_validate(result)+ status = _parse_route_status(response)+ dims = {"status": status, "tier": response.tier}+ await _record_telemetry_count(self.state, "parse.finished.count", dimensions=dims)+ await _record_telemetry_duration(self.state, "parse.duration_bucket.count", start_ms, dimensions=dims)+ return response+ except Exception as exc:+ dims = {"status": "failed", "tier": request.tier or "default", "error_code": _telemetry_error_code(exc)}+ await _record_telemetry_count(self.state, "parse.finished.count", dimensions=dims)+ await _record_telemetry_duration(self.state, "parse.duration_bucket.count", start_ms, dimensions=dims)+ raise@route("GET", "/parses", tags=("parse",))async def list_parses(@@ -362,6 +384,7 @@ class DoclibServer(AsyncDoclibInterface):@route("POST", "/scans", tags=("scan",))async def create_scan(self, request: ScanRequest) -> ScanInfo:+ await _record_telemetry_count(self.state, "scan.request.count")return await self.state.scan_svc.create_scan(request.path,kind=request.kind,@@ -485,17 +508,30 @@ class DoclibServer(AsyncDoclibInterface):format: str = "markdown",no_marker: bool = False,) -> DocContentResponse:- return await self._execute_read_plan(- await self._build_read_plan_from_parse(- sha256,- tier=tier,- page_range=page_range,- after=after,- limit=limit,- format=format,- no_marker=no_marker,+ start_ms = _now_ms()+ dims = {"content_mode": "read", "output_format": _telemetry_output_format(format), "tier": tier}+ await _record_telemetry_count(self.state, "content.request.count", dimensions=dims)+ try:+ response = await self._execute_read_plan(+ await self._build_read_plan_from_parse(+ sha256,+ tier=tier,+ page_range=page_range,+ after=after,+ limit=limit,+ format=format,+ no_marker=no_marker,+ ))- )+ finished_dims = dims | {"status": "succeeded"}+ await _record_telemetry_count(self.state, "content.finished.count", dimensions=finished_dims)+ await _record_telemetry_duration(self.state, "content.duration_bucket.count", start_ms, dimensions=finished_dims)+ return response+ except Exception:+ finished_dims = dims | {"status": "failed"}+ await _record_telemetry_count(self.state, "content.finished.count", dimensions=finished_dims)+ await _record_telemetry_duration(self.state, "content.duration_bucket.count", start_ms, dimensions=finished_dims)+ raise@route("GET", "/content", tags=("docs",))async def read_content(@@ -507,15 +543,28 @@ class DoclibServer(AsyncDoclibInterface):format: ContentFormat = "markdown",no_marker: bool = False,) -> DocContentResponse:- return await self._execute_read_plan(- await self._build_read_plan_from_locator(- locator,- context=context,- limit=limit,- format=format,- no_marker=no_marker,+ start_ms = _now_ms()+ dims = {"content_mode": "read", "output_format": _telemetry_output_format(format), "tier": "unknown"}+ await _record_telemetry_count(self.state, "content.request.count", dimensions=dims)+ try:+ response = await self._execute_read_plan(+ await self._build_read_plan_from_locator(+ locator,+ context=context,+ limit=limit,+ format=format,+ no_marker=no_marker,+ ))- )+ finished_dims = dims | {"status": "succeeded", "tier": response.tier}+ await _record_telemetry_count(self.state, "content.finished.count", dimensions=finished_dims)+ await _record_telemetry_duration(self.state, "content.duration_bucket.count", start_ms, dimensions=finished_dims)+ return response+ except Exception:+ finished_dims = dims | {"status": "failed"}+ await _record_telemetry_count(self.state, "content.finished.count", dimensions=finished_dims)+ await _record_telemetry_duration(self.state, "content.duration_bucket.count", start_ms, dimensions=finished_dims)+ raiseasync def _build_read_plan_from_parse(self,@@ -604,18 +653,30 @@ class DoclibServer(AsyncDoclibInterface):@route("POST", "/docs/{sha256}/exports", tags=("docs",))async def export_doc_content(self, sha256: str, request: DocContentExportRequest) -> DocContentExportResponse:- content = await self._render_doc_content(- sha256,- tier=request.tier,- page_range=request.page_range,- format=request.format,- no_marker=request.no_marker,- )- output_path = os.path.abspath(request.output)- os.makedirs(os.path.dirname(output_path), exist_ok=True)- with open(output_path, "w", encoding="utf-8") as f:- f.write(content)- return DocContentExportResponse(sha256=sha256, tier=request.tier, output=output_path)+ start_ms = _now_ms()+ dims = {"content_mode": "export", "output_format": _telemetry_output_format(request.format), "tier": request.tier}+ await _record_telemetry_count(self.state, "content.request.count", dimensions=dims)+ try:+ content = await self._render_doc_content(+ sha256,+ tier=request.tier,+ page_range=request.page_range,+ format=request.format,+ no_marker=request.no_marker,+ )+ output_path = os.path.abspath(request.output)+ os.makedirs(os.path.dirname(output_path), exist_ok=True)+ with open(output_path, "w", encoding="utf-8") as f:+ f.write(content)+ finished_dims = dims | {"status": "succeeded"}+ await _record_telemetry_count(self.state, "content.finished.count", dimensions=finished_dims)+ await _record_telemetry_duration(self.state, "content.duration_bucket.count", start_ms, dimensions=finished_dims)+ return DocContentExportResponse(sha256=sha256, tier=request.tier, output=output_path)+ except Exception:+ finished_dims = dims | {"status": "failed"}+ await _record_telemetry_count(self.state, "content.finished.count", dimensions=finished_dims)+ await _record_telemetry_duration(self.state, "content.duration_bucket.count", start_ms, dimensions=finished_dims)+ raise@route("GET", "/search", tags=("search",))async def search(@@ -628,22 +689,50 @@ class DoclibServer(AsyncDoclibInterface):limit: int = 20,offset: int = 0,) -> SearchResponse:- results, total = await self.state.search_svc.search(- query=query,- file_type=file_type,- tier=tier,- min_tier=min_tier,- limit=limit,- offset=offset,- )- return SearchResponse(- results=[_search_result(row) for row in results if row.get("tier") in TIERS], total=total, query=query- )+ start_ms = _now_ms()+ await _record_telemetry_count(self.state, "search.request.count")+ try:+ results, total = await self.state.search_svc.search(+ query=query,+ file_type=file_type,+ tier=tier,+ min_tier=min_tier,+ limit=limit,+ offset=offset,+ )+ response = SearchResponse(+ results=[_search_result(row) for row in results if row.get("tier") in TIERS], total=total, query=query+ )+ dims = {"status": "succeeded"}+ await _record_telemetry_count(self.state, "search.finished.count", dimensions=dims)+ await _record_telemetry_duration(self.state, "search.duration_bucket.count", start_ms, dimensions=dims)+ await _record_telemetry_count(+ self.state, "search.results_bucket.count", dimensions={"bucket": results_bucket(total)}+ )+ return response+ except Exception:+ dims = {"status": "failed"}+ await _record_telemetry_count(self.state, "search.finished.count", dimensions=dims)+ await _record_telemetry_duration(self.state, "search.duration_bucket.count", start_ms, dimensions=dims)+ raise@route("GET", "/find", tags=("search",))async def find(self, query: str, *, ext: str | None = None, limit: int = 50) -> FindResponse:- results, total = await self.state.search_svc.search_filenames(query=query, ext=ext, limit=limit)- return FindResponse(results=[_find_result(row) for row in results], total=total, query=query)+ start_ms = _now_ms()+ await _record_telemetry_count(self.state, "find.request.count")+ try:+ results, total = await self.state.search_svc.search_filenames(query=query, ext=ext, limit=limit)+ response = FindResponse(results=[_find_result(row) for row in results], total=total, query=query)+ dims = {"status": "succeeded"}+ await _record_telemetry_count(self.state, "find.finished.count", dimensions=dims)+ await _record_telemetry_duration(self.state, "find.duration_bucket.count", start_ms, dimensions=dims)+ await _record_telemetry_count(self.state, "find.results_bucket.count", dimensions={"bucket": results_bucket(total)})+ return response+ except Exception:+ dims = {"status": "failed"}+ await _record_telemetry_count(self.state, "find.finished.count", dimensions=dims)+ await _record_telemetry_duration(self.state, "find.duration_bucket.count", start_ms, dimensions=dims)+ raise@route("GET", "/files/by-path", tags=("files",))async def get_file_by_path(self, path: str) -> FileInfoResponse:@@ -696,8 +785,14 @@ class DoclibServer(AsyncDoclibInterface):@route("POST", "/watches", tags=("watches",))async def add_watch(self, request: WatchRequest) -> WatchInfo:- row = await self.state.config_svc.add_watch(request.path, removable=request.removable, label=request.label)- return _watch_info(row)+ await _record_telemetry_count(self.state, "watch.add.count")+ try:+ row = await self.state.config_svc.add_watch(request.path, removable=request.removable, label=request.label)+ await _record_telemetry_count(self.state, "watch.add.finished.count", dimensions={"status": "succeeded"})+ return _watch_info(row)+ except Exception:+ await _record_telemetry_count(self.state, "watch.add.finished.count", dimensions={"status": "failed"})+ raise@route("GET", "/watches", tags=("watches",))async def list_watches(self) -> WatchListResponse:@@ -705,11 +800,17 @@ class DoclibServer(AsyncDoclibInterface):@route("DELETE", "/watches/{watch_id}", tags=("watches",))async def remove_watch(self, watch_id: int) -> RemoveWatchResponse:- existing = await self.state.db.fetchone("SELECT id FROM watches WHERE id=?", (watch_id,))- if existing is None:- raise NotFoundError("watch_not_found", f"Watch target {watch_id} not found.", "watch_id")- await self.state.config_svc.remove_watch_by_id(watch_id)- return RemoveWatchResponse(watch_id=watch_id, removed=True)+ await _record_telemetry_count(self.state, "watch.remove.count")+ try:+ existing = await self.state.db.fetchone("SELECT id FROM watches WHERE id=?", (watch_id,))+ if existing is None:+ raise NotFoundError("watch_not_found", f"Watch target {watch_id} not found.", "watch_id")+ await self.state.config_svc.remove_watch_by_id(watch_id)+ await _record_telemetry_count(self.state, "watch.remove.finished.count", dimensions={"status": "succeeded"})+ return RemoveWatchResponse(watch_id=watch_id, removed=True)+ except Exception:+ await _record_telemetry_count(self.state, "watch.remove.finished.count", dimensions={"status": "failed"})+ raise@route("POST", "/exclude-rules", tags=("rules",))async def add_exclude_rule(self, request: ExcludeRuleRequest) -> ExcludeRuleInfo:@@ -777,6 +878,104 @@ class DoclibServer(AsyncDoclibInterface):count = await self.state.cleanup_svc.cleanup_temp_files(older_than_days=request.older_than_days)return CleanupTempResponse(temp_files_removed=count)+ @route("GET", "/telemetry/status", tags=("telemetry",))+ async def get_telemetry_status(self) -> TelemetryStatusResponse:+ status = await self.state.telemetry_svc.status()+ return TelemetryStatusResponse.model_validate(status)++ @route("GET", "/telemetry/preview", tags=("telemetry",))+ async def get_telemetry_preview(self) -> TelemetryPreviewResponse:+ body = await self.state.telemetry_svc.preview_body()+ return TelemetryPreviewResponse(body=TelemetryPayload.model_validate(body))++ @route("POST", "/telemetry/actions/{action}", tags=("telemetry",))+ async def telemetry_action(self, action: TelemetryAction) -> TelemetryActionResponse:+ if action == "enable":+ result = await self.state.telemetry_svc.set_consent("enabled")+ return TelemetryActionResponse(action=action, **result)+ if action == "disable":+ result = await self.state.telemetry_svc.set_consent("disabled")+ return TelemetryActionResponse(action=action, **result)+ status = await self.state.telemetry_svc.status()+ if status["state"] != "enabled":+ return TelemetryActionResponse(+ action=action,+ state=status["state"],+ installation_id=status["installation_id"],+ executed=False,+ reason="telemetry_not_enabled",+ )+ flush_result = await self.state.telemetry_svc.flush_once()+ return TelemetryActionResponse(+ action=action,+ state=status["state"],+ installation_id=status["installation_id"],+ executed=flush_result.status not in {"disabled", "locked", "no_metrics", "failed"},+ reason=None if flush_result.status == "success" else flush_result.status,+ flush_result={+ "status": flush_result.status,+ "attempted": flush_result.attempted,+ "succeeded": flush_result.succeeded,+ "discarded": flush_result.discarded,+ },+ )++ @route("POST", "/observations", tags=("telemetry",))+ async def record_observations(self, request: TelemetryObservationsRequest) -> TelemetryObservationsResponse:+ accepted = 0+ for observation in request.observations:+ if observation.metric_name == "parse.wait":+ await self._record_parse_wait_observation(observation)+ accepted += 1+ continue+ if observation.duration_ms is None:+ await self.state.telemetry_svc.record_count(+ observation.metric_name,+ value=observation.value,+ dimensions=observation.dimensions,+ )+ else:+ await self.state.telemetry_svc.record_duration_bucket(+ observation.metric_name,+ duration_ms=observation.duration_ms,+ dimensions=observation.dimensions,+ )+ accepted += 1+ return TelemetryObservationsResponse(accepted=accepted)++ async def _record_parse_wait_observation(self, observation: TelemetryObservation) -> None:+ if observation.duration_ms is None or not observation.parse_ids:+ return+ placeholders = ",".join("?" * len(observation.parse_ids))+ rows = cast(+ list[ParseRow],+ await self.state.db.fetchall(+ f"SELECT * FROM parses WHERE id IN ({placeholders}) ORDER BY id ASC",+ tuple(observation.parse_ids),+ ),+ )+ if not rows:+ return+ tier = rows[0]["tier"] if rows[0].get("tier") else "unknown"+ page_numbers: set[int] = set()+ for row in rows:+ try:+ page_numbers |= parse_page_range_set(row["page_range"])+ except Exception:+ continue+ status = observation.dimensions.get("status") or "unknown"+ dims = {+ "status": status,+ "tier": tier,+ "pages_bucket": pages_bucket(len(page_numbers) or 1),+ }+ await self.state.telemetry_svc.record_count("parse.wait.count", dimensions=dims)+ await self.state.telemetry_svc.record_duration_bucket(+ "parse.wait_duration_bucket.count",+ duration_ms=observation.duration_ms,+ dimensions=dims,+ )+async def _select_parse_rows(self,*,@@ -989,7 +1188,9 @@ class DoclibServer(AsyncDoclibInterface):raise NotFoundError("no_accessible_file", "No active source file found for this document.", "locator")source_path = file_row["path"]if not source_path.lower().endswith(".pdf"):- raise InvalidRequestError("format_not_supported", "image format for page/block is only supported for PDF sources.", "format")+ raise InvalidRequestError(+ "format_not_supported", "image format for page/block is only supported for PDF sources.", "format"+ )pdf_bytes = Path(source_path).read_bytes()with PDFDocument(pdf_bytes) as doc:if plan.target.block_no is None:@@ -1004,7 +1205,9 @@ class DoclibServer(AsyncDoclibInterface):raise InvalidRequestError("bbox_not_available", "Block bbox is not available for image output.", "locator")image_bytes = doc.crop_image(block.bbox, plan.target.page_no - 1, scale=2)width, height = _image_size_from_bytes(image_bytes)- return _write_temp_asset(self.state.data_dir, plan.short_id, "jpg", image_bytes, mime_type="image/jpeg", width=width, height=height)+ return _write_temp_asset(+ self.state.data_dir, plan.short_id, "jpg", image_bytes, mime_type="image/jpeg", width=width, height=height+ )async def _render_office_image_asset(self, plan: _ReadPlan, page: PageInfo) -> ContentAsset:if plan.target is None or plan.target.block_no is None:@@ -1014,7 +1217,9 @@ class DoclibServer(AsyncDoclibInterface):raise NotFoundError("block_not_found", f"Block {plan.target.block_no} not found.", "locator")image_span = _first_image_span(block)if image_span is None:- raise InvalidRequestError("format_not_supported", "Office image output is only supported for image blocks.", "format")+ raise InvalidRequestError(+ "format_not_supported", "Office image output is only supported for image blocks.", "format"+ )image_bytes, ext, mime_type = _span_image_bytes(image_span)if image_bytes is None and image_span.image_path:image_dir = parse_image_sidecar_dir(self.state.data_dir, plan.sha256, plan.tier)@@ -1026,7 +1231,9 @@ class DoclibServer(AsyncDoclibInterface):if image_bytes is None:raise NotFoundError("asset_not_available", "Office image asset is not available.", "locator")width, height = _image_size_from_bytes(image_bytes)- return _write_temp_asset(self.state.data_dir, plan.short_id, ext or "png", image_bytes, mime_type=mime_type, width=width, height=height)+ return _write_temp_asset(+ self.state.data_dir, plan.short_id, ext or "png", image_bytes, mime_type=mime_type, width=width, height=height+ )_READ_LOCATOR_RE = re.compile(@@ -1068,7 +1275,9 @@ def _locator_after(locator: _LocatorParts) -> str | None:return Noneif locator.block_no is None:return None- return _canonical_locator(locator.short_id, locator.tier or "standard", locator) if locator.char_offset is not None else None+ return (+ _canonical_locator(locator.short_id, locator.tier or "standard", locator) if locator.char_offset is not None else None+ )def _locator_page_range(locator: _LocatorParts, doc: DocRow, context: int) -> str | None:@@ -1729,6 +1938,54 @@ async def _recent_scans(db: DatabaseManager, limit: int = 5) -> list[ScanInfo]:return [ScanInfo.model_validate(row) for row in rows]+async def _record_telemetry_count(state: Any, metric_name: str, *, dimensions: dict[str, str] | None = None) -> None:+ telemetry_svc = getattr(state, "telemetry_svc", None)+ if telemetry_svc is None:+ return+ await telemetry_svc.record_count(metric_name, dimensions=dimensions)+++async def _record_telemetry_duration(+ state: Any,+ metric_name: str,+ start_ms: int,+ *,+ dimensions: dict[str, str] | None = None,+) -> None:+ telemetry_svc = getattr(state, "telemetry_svc", None)+ if telemetry_svc is None:+ return+ await telemetry_svc.record_duration_bucket(metric_name, duration_ms=max(0, _now_ms() - start_ms), dimensions=dimensions)+++def _parse_route_status(response: ParseResponse) -> str:+ if response.cache_hit:+ return "cached"+ if response.created_parse_ids:+ return "queued"+ if response.reused_parse_ids:+ return "reused"+ return "direct"+++def _telemetry_error_code(exc: Exception) -> str:+ if isinstance(exc, MineruError):+ return exc.code+ return "internal_error"+++def _telemetry_output_format(value: str) -> str:+ if value == "markdown":+ return "markdown"+ if value == "image":+ return "image"+ return "other"+++def _now_ms() -> int:+ return int(time.time() * 1000)++async def _error_buckets(db: DatabaseManager, table: str) -> list[ErrorBucket]:sql_by_table = {"files": (diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.pyindex a6ff078f..7c333a29 100644--- a/mineru/doclib/services/parse_svc.py+++ b/mineru/doclib/services/parse_svc.py@@ -10,6 +10,7 @@ from collections.abc import Sequencefrom dataclasses import dataclassfrom pathlib import Path, PurePosixPathfrom typing import Literal, cast+from urllib.parse import urlparsefrom ...errors import MineruErrorfrom ...parser.base import ParseResult@@ -247,12 +248,14 @@ class ParseService:data_dir: str,*,parse_lock_timeout_sec: int,+ telemetry_svc: object | None = None,) -> None:self.db = dbself.fts = ftsself.config_svc = config_svcself.data_dir = os.path.expanduser(data_dir)self.parse_lock_timeout_ms = parse_lock_timeout_sec * 1000+ self.telemetry_svc = telemetry_svc# ── discovery / ingestion (shared) ──────────────────────@@ -413,8 +416,22 @@ class ParseService:return Nonereturn cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,)))- async def ingest_file(self, path: str, watch_id: int | None = None) -> FileRow | None:+ async def ingest_file(self, path: str, watch_id: int | None = None, *, trigger: str = "parse") -> FileRow | None:"""Ingest a discovered file: SHA-256 + metadata + trigger default parse."""+ start_ms = _now_ms()+ status = "succeeded"+ try:+ return await self._ingest_file(path, watch_id=watch_id)+ except Exception:+ status = "failed"+ raise+ finally:+ dimensions = {"status": status, "trigger": trigger}+ await self._record_count("ingest.finished.count", dimensions=dimensions)+ await self._record_duration("ingest.duration_bucket.count", start_ms, dimensions=dimensions)++ async def _ingest_file(self, path: str, watch_id: int | None = None) -> FileRow | None:+ """Ingest implementation without telemetry wrapper."""ext = Path(path).suffix.lower().lstrip(".")if ext not in ALLOWED_EXTENSIONS:return None@@ -576,6 +593,7 @@ class ParseService:"INSERT INTO parses (sha256, tier, page_range, status, priority, created_at, updated_at) VALUES (?, ?, ?, ?, 0, ?, ?)",(sha256, tier, parse_page_range, PARSE_STATUS_PENDING, now, now),)+ await self._record_count("parse_task.created.count", dimensions={"tier": tier})await self.db.execute("UPDATE files SET sha256=?, locked_at=NULL, updated_at=? WHERE path=?",@@ -688,6 +706,7 @@ class ParseService:"VALUES (?, ?, ?, ?, ?, 1, ?, ?)",(sha256, requested_tier, uncovered_page_range, PARSE_STATUS_PENDING, privacy, now, now),)+ await self._record_count("parse_task.created.count", dimensions={"tier": requested_tier})created_parse_ids = [parse_id]return ParseResponse(sha256=sha256,@@ -713,7 +732,7 @@ class ParseService:async def acquire_task(self) -> ParseRow | None:now = _now_ms()timeout = now - self.parse_lock_timeout_ms- return cast(+ task = cast(ParseRow | None,await self.db.fetchone("UPDATE parses SET locked_at=?, status=? "@@ -725,9 +744,13 @@ class ParseService:(now, PARSE_STATUS_PARSING, PARSE_STATUS_PENDING, timeout),),)+ if task is not None:+ await self._record_count("parse_task.started.count", dimensions={"tier": task["tier"]})+ return taskasync def process_doc(self, task: ParseRow) -> bool:"""Execute parse for a batch. Returns True on success."""+ task_start_ms = _now_ms()sha256 = task["sha256"]tier = task["tier"]page_range = task["page_range"]@@ -748,33 +771,61 @@ class ParseService:)if file_row is None:await self._fail_task(task["id"], "no_accessible_file", "No active file found for this document")+ await self._record_parse_task_finished(+ task_start_ms,+ tier=tier,+ status="failed",+ error_code="no_accessible_file",+ )return Falseoutput_dir = os.path.join(self.data_dir, "parsed", sha256[:2], sha256, tier)# route parse based on tiervia = "local"+ execute_start_ms = _now_ms()+ server_dim = "local(flash)" if tier == "flash" else "unknown"try:if tier == "flash":result = await self._parse_via_local(file_row, tier, page_range)else:result, via = await self._parse_via_api(file_row, tier, page_range, privacy)+ server_dim = await self._telemetry_server_dim(via=via, tier=tier)except ParseFailure as exc:+ await self._record_execute(+ execute_start_ms,+ tier=tier,+ server=server_dim,+ status="failed",+ error_code=exc.code,+ )await self._fail_task(task["id"], exc.code, exc.message)+ await self._record_parse_task_finished(task_start_ms, tier=tier, status="failed", error_code=exc.code)return Falseexcept Exception as exc:+ await self._record_execute(+ execute_start_ms,+ tier=tier,+ server=server_dim,+ status="failed",+ error_code="parse_failed",+ )await self._fail_task(task["id"], "parse_failed", str(exc)[:500])+ await self._record_parse_task_finished(task_start_ms, tier=tier, status="failed", error_code="parse_failed")return False+ await self._record_execute(execute_start_ms, tier=tier, server=server_dim, status="succeeded")export_payload = result.to_export_dict(skip_defaults=True)new_pages = export_payload["pages"]if not new_pages:await self._fail_task(task["id"], "parse_empty", "Parse completed but returned no pages")+ await self._record_parse_task_finished(task_start_ms, tier=tier, status="failed", error_code="parse_failed")return False# save per-batch JSON (markdown is generated on read from /docs/{sha256}/content)done_at_ms = _now_ms()json_path = os.path.join(output_dir, _safe_filename(page_range, done_at_ms))+ write_start_ms = _now_ms()try:os.makedirs(output_dir, exist_ok=True)_write_cached_image_sidecars(parse_image_sidecar_dir(self.data_dir, sha256, tier), result.images())@@ -782,24 +833,57 @@ class ParseService:json.dump(export_payload, f, ensure_ascii=False, indent=4)except Exception as exc:await self._fail_task(task["id"], "parse_json_write_failed", str(exc)[:500])+ await self._record_write(+ write_start_ms,+ tier=tier,+ status="failed",+ error_code="parse_json_write_failed",+ )+ await self._record_parse_task_finished(+ task_start_ms,+ tier=tier,+ status="failed",+ error_code="parse_json_write_failed",+ )return False- # generate markdown for FTS (not persisted, only for search indexing)- md_text = ""- md = result.markdown(add_markers=False) if hasattr(result, "markdown") else ""- md_text += md + "\n"+ try:+ # generate markdown for FTS (not persisted, only for search indexing)+ md_text = ""+ md = result.markdown(add_markers=False) if hasattr(result, "markdown") else ""+ md_text += md + "\n"- # update fts_contents (tier-gated)- await self._maybe_update_fts(sha256, tier, md_text, file_row)+ # update fts_contents (tier-gated)+ await self._maybe_update_fts(sha256, tier, md_text, file_row)- # update docs metadata (tier-gated)- await self._maybe_update_docs_meta(sha256, tier)+ # update docs metadata (tier-gated)+ await self._maybe_update_docs_meta(sha256, tier)- # mark done- await self.db.execute(- "UPDATE parses SET status=?, done_at=?, locked_at=NULL, via=?, updated_at=? WHERE id=?",- (PARSE_STATUS_DONE, done_at_ms, via, done_at_ms, task["id"]),- )+ # mark done+ await self.db.execute(+ "UPDATE parses SET status=?, done_at=?, locked_at=NULL, via=?, updated_at=? WHERE id=?",+ (PARSE_STATUS_DONE, done_at_ms, via, done_at_ms, task["id"]),+ )+ except Exception as exc:+ await self._fail_task(task["id"], "parse_json_write_failed", str(exc)[:500])+ await self._record_write(+ write_start_ms,+ tier=tier,+ status="failed",+ error_code="parse_json_write_failed",+ )+ await self._record_parse_task_finished(+ task_start_ms,+ tier=tier,+ status="failed",+ error_code="parse_json_write_failed",+ )+ return False++ await self._record_write(write_start_ms, tier=tier, status="succeeded")+ await self._record_count("parse_task.files.count", dimensions={"tier": tier})+ await self._record_count("parse_task.pages.count", value=len(new_pages), dimensions={"tier": tier})+ await self._record_parse_task_finished(task_start_ms, tier=tier, status="succeeded")return True# ── parse routing helpers ─────────────────────────────────────@@ -911,6 +995,84 @@ class ParseService:(PARSE_STATUS_FAILED, code, message, now, task_id),)+ async def _telemetry_server_dim(self, *, via: str, tier: Tier) -> str:+ if tier == "flash":+ return "local(flash)"+ if via == "local":+ local_mode = (await self.config_svc.get("parse_server.local.mode")) or "disabled"+ if local_mode == "managed":+ return "local(managed)"+ if local_mode == "self_hosted":+ return "local(self-hosted)"+ return "unknown"+ if via == "remote":+ url = cast(str | None, await self.config_svc.get("parse_server.remote.url"))+ return "remote(official)" if _is_official_remote_url(url or "") else "remote(custom)"+ return "unknown"++ async def _record_parse_task_finished(+ self,+ start_ms: int,+ *,+ tier: str,+ status: str,+ error_code: str | None = None,+ ) -> None:+ dimensions = {"status": status, "tier": tier}+ if error_code:+ dimensions["error_code"] = error_code+ await self._record_count("parse_task.finished.count", dimensions=dimensions)+ await self._record_duration("parse_task.duration_bucket.count", start_ms, dimensions=dimensions)++ async def _record_execute(+ self,+ start_ms: int,+ *,+ tier: str,+ server: str,+ status: str,+ error_code: str | None = None,+ ) -> None:+ dimensions = {"status": status, "tier": tier, "server": server}+ if error_code:+ dimensions["error_code"] = error_code+ await self._record_count("parse_task.execute.count", dimensions=dimensions)+ await self._record_duration("parse_task.execute_duration_bucket.count", start_ms, dimensions=dimensions)++ async def _record_write(+ self,+ start_ms: int,+ *,+ tier: str,+ status: str,+ error_code: str | None = None,+ ) -> None:+ dimensions = {"status": status, "tier": tier}+ if error_code:+ dimensions["error_code"] = error_code+ await self._record_count("parse_task.write.count", dimensions=dimensions)+ await self._record_duration("parse_task.write_duration_bucket.count", start_ms, dimensions=dimensions)++ async def _record_count(+ self,+ metric_name: str,+ *,+ value: int = 1,+ dimensions: dict[str, str] | None = None,+ ) -> None:+ if self.telemetry_svc is None:+ return+ record = getattr(self.telemetry_svc, "record_count", None)+ if record is not None:+ await record(metric_name, value=value, dimensions=dimensions)++ async def _record_duration(self, metric_name: str, start_ms: int, *, dimensions: dict[str, str] | None = None) -> None:+ if self.telemetry_svc is None:+ return+ record = getattr(self.telemetry_svc, "record_duration_bucket", None)+ if record is not None:+ await record(metric_name, duration_ms=max(0, _now_ms() - start_ms), dimensions=dimensions)+async def get_parse_record(self, parse_id: int) -> dict | None:row = cast(ParseRow | None, await self.db.fetchone("SELECT * FROM parses WHERE id=?", (parse_id,)))return _parse_record_response(row) if row else None@@ -1251,6 +1413,12 @@ def _local_parse_server_url(mode: str, health: object) -> str | None:return None+def _is_official_remote_url(url: str) -> bool:+ host = urlparse(url).hostname or ""+ host = host.lower().rstrip(".")+ return host in {"mineru.net", "mineru.org.cn"} or host.endswith(".mineru.net") or host.endswith(".mineru.org.cn")++def _file_info(row: FileRow | None) -> FileInfo | None:return FileInfo.model_validate(row) if row is not None else Nonediff --git a/mineru/doclib/services/scan_svc.py b/mineru/doclib/services/scan_svc.pyindex 07ea2640..d0ec2b04 100644--- a/mineru/doclib/services/scan_svc.py+++ b/mineru/doclib/services/scan_svc.py@@ -71,11 +71,13 @@ class ScanService:parse_svc: ParseService,*,scan_lock_timeout_sec: int,+ telemetry_svc: object | None = None,) -> None:self.db = dbself.config_svc = config_svcself.parse_svc = parse_svcself.scan_lock_timeout_ms = scan_lock_timeout_sec * 1000+ self.telemetry_svc = telemetry_svcasync def create_scan(self,@@ -101,8 +103,12 @@ class ScanService:),)if active is not None:+ await self._record_count("scan.reuse.count", dimensions={"status": "reused"})return _scan_info(active)+ if source == "watch":+ await self._record_count("scan.request.count", dimensions={"source": "watch", "caller": "system"})+now = _now_ms()scan_id = await self.db.execute_insert("INSERT INTO scans (path, kind, source, watch_id, status, created_at, updated_at) "@@ -170,6 +176,7 @@ class ScanService:)async def process_scan(self, task: ScanRow) -> bool:+ start_ms = _now_ms()try:counters = await self._run_scan(task)except Exception as exc:@@ -179,6 +186,8 @@ class ScanService:(SCAN_STATUS_FAILED, "scan_failed", str(exc)[:500], now, now, task["id"]),)await self.cleanup_terminal_scan_logs()+ await self._record_count("scan.finished.count", dimensions={"status": "failed"})+ await self._record_duration("scan.duration_bucket.count", start_ms, dimensions={"status": "failed"})return Falsenow = _now_ms()@@ -206,6 +215,9 @@ class ScanService:if task["kind"] == SCAN_KIND_WATCH and task_watch_id is not None:await self.config_svc.update_watch_scan_stats(task_watch_id, counters.files_refreshed)await self.cleanup_terminal_scan_logs()+ await self._record_count("scan.finished.count", dimensions={"status": "succeeded"})+ await self._record_duration("scan.duration_bucket.count", start_ms, dimensions={"status": "succeeded"})+ await self._record_scan_file_counts(counters)return Trueasync def cleanup_terminal_scan_logs(self, *, keep: int = SCAN_LOG_RETENTION_LIMIT) -> None:@@ -335,6 +347,42 @@ class ScanService:raise NotFoundError("watch_not_found", "Watch target not found.", "watch_id")return watch+ async def _record_scan_file_counts(self, counters: "_ScanCounters") -> None:+ values = {+ "seen": counters.files_seen,+ "refreshed": counters.files_refreshed,+ "new": counters.files_new,+ "changed": counters.files_changed,+ "deleted": counters.files_deleted,+ "unreachable": counters.files_unreachable,+ "error": counters.files_error,+ "unsupported": counters.files_unsupported,+ "excluded": counters.files_excluded,+ }+ for result, value in values.items():+ if value:+ await self._record_count("scan.files.count", value=value, dimensions={"result": result})++ async def _record_count(+ self,+ metric_name: str,+ *,+ value: int = 1,+ dimensions: dict[str, str] | None = None,+ ) -> None:+ if self.telemetry_svc is None:+ return+ record = getattr(self.telemetry_svc, "record_count", None)+ if record is not None:+ await record(metric_name, value=value, dimensions=dimensions)++ async def _record_duration(self, metric_name: str, start_ms: int, *, dimensions: dict[str, str] | None = None) -> None:+ if self.telemetry_svc is None:+ return+ record = getattr(self.telemetry_svc, "record_duration_bucket", None)+ if record is not None:+ await record(metric_name, duration_ms=max(0, _now_ms() - start_ms), dimensions=dimensions)+class _ScanCounters:def __init__(self) -> None:diff --git a/mineru/doclib/telemetry/__init__.py b/mineru/doclib/telemetry/__init__.pynew file mode 100644index 00000000..0472c31a--- /dev/null+++ b/mineru/doclib/telemetry/__init__.py@@ -0,0 +1,26 @@+"""Doclib telemetry primitives."""++from .buckets import duration_bucket, file_size_bucket, pages_bucket, results_bucket+from .context import (+ TelemetryContext,+ get_telemetry_context,+ infer_default_client_context,+ reset_telemetry_context,+ set_telemetry_context,+)+from .service import TelemetryService+from .store import TelemetryStore++__all__ = [+ "TelemetryContext",+ "TelemetryService",+ "TelemetryStore",+ "duration_bucket",+ "file_size_bucket",+ "get_telemetry_context",+ "infer_default_client_context",+ "pages_bucket",+ "reset_telemetry_context",+ "results_bucket",+ "set_telemetry_context",+]diff --git a/mineru/doclib/telemetry/buckets.py b/mineru/doclib/telemetry/buckets.pynew file mode 100644index 00000000..2dc20e08--- /dev/null+++ b/mineru/doclib/telemetry/buckets.py@@ -0,0 +1,65 @@+"""Telemetry bucket helpers."""++from __future__ import annotations++DURATION_BUCKETS = ("lt_1s", "1_5s", "5_30s", "30_120s", "2_10m", "gt_10m")+PAGES_BUCKETS = ("1", "2_5", "6_20", "21_100", "101_500", "gt_500")+FILE_SIZE_BUCKETS = ("lt_1mb", "1_10mb", "10_50mb", "50_200mb", "gt_200mb")+RESULTS_BUCKETS = ("0", "1_5", "6_20", "21_100", "gt_100")+++def duration_bucket(duration_ms: int) -> str:+ seconds = max(0, duration_ms) / 1000+ if seconds < 1:+ return "lt_1s"+ if seconds < 5:+ return "1_5s"+ if seconds < 30:+ return "5_30s"+ if seconds < 120:+ return "30_120s"+ if seconds < 600:+ return "2_10m"+ return "gt_10m"+++def pages_bucket(pages: int) -> str:+ value = max(1, pages)+ if value == 1:+ return "1"+ if value <= 5:+ return "2_5"+ if value <= 20:+ return "6_20"+ if value <= 100:+ return "21_100"+ if value <= 500:+ return "101_500"+ return "gt_500"+++def file_size_bucket(size_bytes: int) -> str:+ value = max(0, size_bytes)+ mb = 1024 * 1024+ if value < mb:+ return "lt_1mb"+ if value < 10 * mb:+ return "1_10mb"+ if value < 50 * mb:+ return "10_50mb"+ if value < 200 * mb:+ return "50_200mb"+ return "gt_200mb"+++def results_bucket(results: int) -> str:+ value = max(0, results)+ if value == 0:+ return "0"+ if value <= 5:+ return "1_5"+ if value <= 20:+ return "6_20"+ if value <= 100:+ return "21_100"+ return "gt_100"diff --git a/mineru/doclib/telemetry/caller.py b/mineru/doclib/telemetry/caller.pynew file mode 100644index 00000000..70b9c652--- /dev/null+++ b/mineru/doclib/telemetry/caller.py@@ -0,0 +1,122 @@+"""Best-effort caller/source inference for telemetry."""++from __future__ import annotations++import os+import platform+import sys+from pathlib import Path++from .constants import TelemetryCaller++_AGENT_PROCESS_MARKERS = (+ "claude",+ "codex",+ "cursor",+ "cline",+ "copilot",+ "gemini",+ "goose",+ "opencode",+ "roo",+ "trae",+ "windsurf",+)+_MAX_PARENT_DEPTH = 8+++def infer_caller_from_process_tree(max_depth: int = _MAX_PARENT_DEPTH) -> TelemetryCaller:+ """Infer whether the current process was launched by a common agent tool.++ The implementation intentionally inspects process names only. It avoids+ command-line arguments, paths, and environment variables because those can+ contain user data.+ """+ names = _parent_process_names(max_depth)+ if any(_is_agent_name(name) for name in names):+ return "agent"+ if sys.stdin is not None and sys.stdin.isatty():+ return "user"+ return "unknown"+++def _parent_process_names(max_depth: int) -> list[str]:+ names = _parent_process_names_psutil(max_depth)+ if names:+ return names+ if platform.system() == "Linux":+ return _parent_process_names_procfs(max_depth)+ return []+++def _parent_process_names_psutil(max_depth: int) -> list[str]:+ try:+ import psutil # type: ignore[import-not-found]+ except Exception:+ return []++ try:+ proc = psutil.Process(os.getpid())+ except Exception:+ return []++ names: list[str] = []+ for _ in range(max(0, max_depth)):+ try:+ proc = proc.parent()+ except Exception:+ break+ if proc is None:+ break+ try:+ name = str(proc.name() or "").strip().lower()+ except Exception:+ name = ""+ if name:+ names.append(name)+ return names+++def _parent_process_names_procfs(max_depth: int) -> list[str]:+ names: list[str] = []+ pid = os.getpid()+ for _ in range(max(0, max_depth)):+ stat = _read_proc_stat(pid)+ if stat is None:+ break+ parent_pid, name = stat+ if name:+ names.append(name.lower())+ if parent_pid <= 1 or parent_pid == pid:+ break+ pid = parent_pid+ return names+++def _read_proc_stat(pid: int) -> tuple[int, str] | None:+ try:+ raw = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8", errors="ignore")+ except OSError:+ return None++ left = raw.find("(")+ right = raw.rfind(")")+ if left < 0 or right <= left:+ return None+ name = raw[left + 1 : right]+ rest = raw[right + 2 :].split()+ if len(rest) < 2:+ return None+ try:+ parent_pid = int(rest[1])+ except ValueError:+ return None+ return parent_pid, name+++def _is_agent_name(name: str) -> bool:+ lowered = name.lower()+ return any(marker in lowered for marker in _AGENT_PROCESS_MARKERS)+++__all__ = ["infer_caller_from_process_tree"]diff --git a/mineru/doclib/telemetry/constants.py b/mineru/doclib/telemetry/constants.pynew file mode 100644index 00000000..eccfc87b--- /dev/null+++ b/mineru/doclib/telemetry/constants.py@@ -0,0 +1,198 @@+"""Telemetry constants and schema."""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Literal++TelemetryConsentState = Literal["unset", "enabled", "disabled"]+TelemetrySource = Literal["cli", "sdk", "http_api", "watch", "background", "unknown"]+TelemetryCaller = Literal["agent", "user", "sdk", "http_client", "system", "unknown"]++CONSENT_UNSET: TelemetryConsentState = "unset"+CONSENT_ENABLED: TelemetryConsentState = "enabled"+CONSENT_DISABLED: TelemetryConsentState = "disabled"++TELEMETRY_ENDPOINT = "https://staging.mineru.org.cn/metrics/v2/metrics"+TELEMETRY_APP_KEY = "213a83db-44c8-4218-90c0-ded685cca86e"+TELEMETRY_APP_SECRET = "sec_5f8d9a2b"+TELEMETRY_API_VERSION = "v2"+TELEMETRY_SCHEMA_VERSION = "1"+TELEMETRY_HTTP_TIMEOUT_SEC = 10+TELEMETRY_FLUSH_INTERVAL_SEC = 7200+TELEMETRY_FLUSH_LOCK_TTL_SEC = 1800+TELEMETRY_MAX_FLUSH_PERIODS = 10++OFFICIAL_REMOTE_HOST_SUFFIXES = ("mineru.net", "mineru.org.cn")++DIM_SOURCE_VALUES = frozenset({"cli", "sdk", "http_api", "watch", "background", "unknown"})+DIM_CALLER_VALUES = frozenset({"agent", "user", "sdk", "http_client", "system", "unknown"})+DIM_STATUS_VALUES = frozenset(+ {+ "cached",+ "canceled",+ "changed",+ "deleted",+ "direct",+ "excluded",+ "failed",+ "hit",+ "miss",+ "new",+ "queued",+ "refreshed",+ "reused",+ "seen",+ "skipped",+ "succeeded",+ "timeout",+ "unreachable",+ "unsupported",+ }+)+DIM_TIER_VALUES = frozenset({"default", "flash", "standard", "pro", "standard(default)", "pro(default)", "unknown"})+DIM_SERVER_VALUES = frozenset(+ {"local(flash)", "local(managed)", "local(self-hosted)", "remote(official)", "remote(custom)", "none", "unknown"}+)+DIM_CONTENT_MODE_VALUES = frozenset({"read", "parse_output", "export", "unknown"})+DIM_OUTPUT_FORMAT_VALUES = frozenset({"markdown", "image", "other"})+DIM_TRIGGER_VALUES = frozenset({"parse", "scan", "watch", "show", "background", "unknown"})+DIM_RESULT_VALUES = frozenset(+ {"seen", "refreshed", "new", "changed", "deleted", "unreachable", "error", "unsupported", "excluded", "hit", "miss", "unknown"}+)+DIM_ERROR_CODE_VALUES = frozenset(+ {+ "internal_error",+ "invalid_request",+ "file_not_found",+ "file_permission_denied",+ "not_cached",+ "no_accessible_file",+ "quality_tier_unavailable",+ "no_engine",+ "engine_unavailable",+ "parse_server_unavailable",+ "tier_mismatch",+ "parse_failed",+ "parse_timeout",+ "metadata_failed",+ "parse_json_write_failed",+ "ingest_failed",+ "scan_failed",+ }+)+DIM_DURATION_BUCKET_VALUES = frozenset(+ {+ "lt_1s",+ "1_5s",+ "5_30s",+ "30_120s",+ "2_10m",+ "gt_10m",+ }+)+DIM_PAGES_BUCKET_VALUES = frozenset(+ {+ "1",+ "2_5",+ "6_20",+ "21_100",+ "101_500",+ "gt_500",+ }+)+DIM_FILE_SIZE_BUCKET_VALUES = frozenset(+ {+ "lt_1mb",+ "1_10mb",+ "10_50mb",+ "50_200mb",+ "gt_200mb",+ }+)+DIM_RESULTS_BUCKET_VALUES = frozenset(+ {+ "0",+ "1_5",+ "6_20",+ "21_100",+ "gt_100",+ }+)+DIM_BUCKET_VALUES = (+ DIM_DURATION_BUCKET_VALUES | DIM_PAGES_BUCKET_VALUES | DIM_FILE_SIZE_BUCKET_VALUES | DIM_RESULTS_BUCKET_VALUES+)++DIMENSION_VALUES: dict[str, frozenset[str]] = {+ "source": DIM_SOURCE_VALUES,+ "caller": DIM_CALLER_VALUES,+ "status": DIM_STATUS_VALUES,+ "tier": DIM_TIER_VALUES,+ "server": DIM_SERVER_VALUES,+ "error_code": DIM_ERROR_CODE_VALUES,+ "bucket": DIM_BUCKET_VALUES,+ "pages_bucket": DIM_PAGES_BUCKET_VALUES,+ "result": DIM_RESULT_VALUES,+ "content_mode": DIM_CONTENT_MODE_VALUES,+ "output_format": DIM_OUTPUT_FORMAT_VALUES,+ "trigger": DIM_TRIGGER_VALUES,+}+++@dataclass(frozen=True)+class MetricSpec:+ allowed_dimensions: frozenset[str]+ required_dimensions: frozenset[str] = field(default_factory=frozenset)+++REQ_CONTEXT = frozenset({"source", "caller"})+STATUS = frozenset({"status"})+TIER = frozenset({"tier"})+ERROR = frozenset({"error_code"})+BUCKET = frozenset({"bucket"})+SERVER = frozenset({"server"})++METRIC_SPECS: dict[str, MetricSpec] = {+ "parse.request.count": MetricSpec(REQ_CONTEXT),+ "parse.finished.count": MetricSpec(REQ_CONTEXT | STATUS | TIER | ERROR),+ "parse.duration_bucket.count": MetricSpec(REQ_CONTEXT | STATUS | TIER | BUCKET),+ "parse.wait.count": MetricSpec(REQ_CONTEXT | STATUS | TIER | frozenset({"pages_bucket"})),+ "parse.wait_duration_bucket.count": MetricSpec(REQ_CONTEXT | STATUS | TIER | frozenset({"pages_bucket", "bucket"})),+ "parse.files.count": MetricSpec(REQ_CONTEXT | TIER),+ "parse.pages.count": MetricSpec(REQ_CONTEXT | TIER),+ "parse.file_size_bucket.count": MetricSpec(REQ_CONTEXT | TIER | BUCKET),+ "parse.pages_bucket.count": MetricSpec(REQ_CONTEXT | TIER | BUCKET),+ "parse.invalidate.count": MetricSpec(STATUS),+ "parse_task.created.count": MetricSpec(TIER),+ "parse_task.started.count": MetricSpec(TIER),+ "parse_task.finished.count": MetricSpec(STATUS | TIER | ERROR),+ "parse_task.duration_bucket.count": MetricSpec(STATUS | TIER | BUCKET),+ "parse_task.execute.count": MetricSpec(STATUS | TIER | SERVER | ERROR),+ "parse_task.execute_duration_bucket.count": MetricSpec(STATUS | TIER | SERVER | BUCKET),+ "parse_task.write.count": MetricSpec(STATUS | TIER | ERROR),+ "parse_task.write_duration_bucket.count": MetricSpec(STATUS | TIER | BUCKET),+ "parse_task.files.count": MetricSpec(TIER),+ "parse_task.pages.count": MetricSpec(TIER),+ "ingest.finished.count": MetricSpec(STATUS | frozenset({"trigger"})),+ "ingest.duration_bucket.count": MetricSpec(STATUS | frozenset({"trigger", "bucket"})),+ "search.request.count": MetricSpec(REQ_CONTEXT),+ "search.finished.count": MetricSpec(REQ_CONTEXT | STATUS),+ "search.duration_bucket.count": MetricSpec(REQ_CONTEXT | STATUS | BUCKET),+ "search.results_bucket.count": MetricSpec(REQ_CONTEXT | BUCKET),+ "find.request.count": MetricSpec(REQ_CONTEXT),+ "find.finished.count": MetricSpec(REQ_CONTEXT | STATUS),+ "find.duration_bucket.count": MetricSpec(REQ_CONTEXT | STATUS | BUCKET),+ "find.results_bucket.count": MetricSpec(REQ_CONTEXT | BUCKET),+ "content.request.count": MetricSpec(REQ_CONTEXT | frozenset({"content_mode", "output_format"})),+ "content.finished.count": MetricSpec(REQ_CONTEXT | STATUS | TIER | frozenset({"content_mode", "output_format"})),+ "content.duration_bucket.count": MetricSpec(REQ_CONTEXT | STATUS | TIER | BUCKET | frozenset({"content_mode", "output_format"})),+ "scan.request.count": MetricSpec(REQ_CONTEXT),+ "scan.finished.count": MetricSpec(STATUS),+ "scan.duration_bucket.count": MetricSpec(STATUS | BUCKET),+ "scan.reuse.count": MetricSpec(STATUS),+ "scan.files.count": MetricSpec(frozenset({"result"})),+ "watch.add.count": MetricSpec(REQ_CONTEXT),+ "watch.remove.count": MetricSpec(REQ_CONTEXT),+ "watch.add.finished.count": MetricSpec(REQ_CONTEXT | STATUS),+ "watch.remove.finished.count": MetricSpec(REQ_CONTEXT | STATUS),+}diff --git a/mineru/doclib/telemetry/context.py b/mineru/doclib/telemetry/context.pynew file mode 100644index 00000000..88329994--- /dev/null+++ b/mineru/doclib/telemetry/context.py@@ -0,0 +1,49 @@+"""Telemetry request context helpers."""++from __future__ import annotations++from contextvars import ContextVar, Token+from dataclasses import dataclass++from .caller import infer_caller_from_process_tree+from .constants import TelemetryCaller, TelemetrySource++_DEFAULT_CONTEXT = None+_TELEMETRY_CONTEXT: ContextVar["TelemetryContext | None"] = ContextVar("doclib_telemetry_context", default=_DEFAULT_CONTEXT)+++@dataclass(frozen=True)+class TelemetryContext:+ source: TelemetrySource = "unknown"+ caller: TelemetryCaller = "unknown"++ def dimensions(self) -> dict[str, str]:+ return {"source": self.source, "caller": self.caller}+++def get_telemetry_context() -> TelemetryContext:+ ctx = _TELEMETRY_CONTEXT.get()+ if ctx is None:+ return TelemetryContext()+ return ctx+++def set_telemetry_context(context: TelemetryContext) -> Token[TelemetryContext | None]:+ return _TELEMETRY_CONTEXT.set(context)+++def reset_telemetry_context(token: Token[TelemetryContext | None]) -> None:+ _TELEMETRY_CONTEXT.reset(token)+++def infer_default_client_context(source: TelemetrySource = "sdk") -> TelemetryContext:+ return TelemetryContext(source=source, caller=infer_caller_from_process_tree())+++__all__ = [+ "TelemetryContext",+ "get_telemetry_context",+ "infer_default_client_context",+ "reset_telemetry_context",+ "set_telemetry_context",+]diff --git a/mineru/doclib/telemetry/observation.py b/mineru/doclib/telemetry/observation.pynew file mode 100644index 00000000..9a2d7ba6--- /dev/null+++ b/mineru/doclib/telemetry/observation.py@@ -0,0 +1,16 @@+"""Telemetry observation helpers."""++from __future__ import annotations++from dataclasses import dataclass, field+++@dataclass(frozen=True)+class TelemetryObservation:+ metric_name: str+ value: int = 1+ duration_ms: int | None = None+ dimensions: dict[str, str] = field(default_factory=dict)+++__all__ = ["TelemetryObservation"]diff --git a/mineru/doclib/telemetry/payload.py b/mineru/doclib/telemetry/payload.pynew file mode 100644index 00000000..727666d2--- /dev/null+++ b/mineru/doclib/telemetry/payload.py@@ -0,0 +1,223 @@+"""Telemetry payload and environment context builders."""++from __future__ import annotations++import hashlib+import json+import os+import platform+import sys+from datetime import UTC, datetime+from importlib import metadata+from pathlib import Path+from typing import Any++from ...version import __version__+from .constants import TELEMETRY_API_VERSION, TELEMETRY_SCHEMA_VERSION+++def canonical_dimensions(dimensions: dict[str, str]) -> dict[str, str]:+ return {key: dimensions[key] for key in sorted(dimensions)}+++def dimensions_hash(dimensions: dict[str, str]) -> str:+ raw = json.dumps(canonical_dimensions(dimensions), ensure_ascii=False, separators=(",", ":"))+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()+++def utc_iso_from_ms(value_ms: int) -> str:+ return datetime.fromtimestamp(value_ms / 1000, tz=UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")+++def compact_json_bytes(payload: dict[str, Any]) -> bytes:+ return json.dumps(payload, ensure_ascii=False, separators=(",", ":"), sort_keys=True).encode("utf-8")+++def build_period_payload(+ *,+ batch_id: str,+ installation_id: str,+ period_start: int,+ period_end: int,+ context: dict[str, str],+ metrics: list[dict[str, Any]],+) -> dict[str, Any]:+ return {+ "api_version": TELEMETRY_API_VERSION,+ "batch_id": batch_id,+ "schema_version": TELEMETRY_SCHEMA_VERSION,+ "installation_id": installation_id,+ "period_start": utc_iso_from_ms(period_start),+ "period_end": utc_iso_from_ms(period_end),+ "context": context,+ "metrics": metrics,+ }+++def collect_environment_context() -> dict[str, str]:+ return {+ "app": "mineru",+ "app_version": __version__,+ "os": _os_name(),+ "arch": platform.machine().lower() or "unknown",+ "python": _python_version(),+ "install_channel": _install_channel(),+ "cpu_count_bucket": _cpu_count_bucket(os.cpu_count()),+ "gpu_vendor": _gpu_vendor(),+ }+++def _os_name() -> str:+ system = platform.system().lower()+ if system == "darwin":+ return "macos"+ if system == "windows":+ return "windows"+ if system == "linux":+ return "linux"+ return system or "unknown"+++def _python_version() -> str:+ return f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"+++def _cpu_count_bucket(cpu_count: int | None) -> str:+ if cpu_count is None or cpu_count <= 0:+ return "unknown"+ if cpu_count <= 2:+ return "1_2"+ if cpu_count <= 4:+ return "3_4"+ if cpu_count <= 8:+ return "5_8"+ if cpu_count <= 16:+ return "9_16"+ return "gt_16"+++def _install_channel() -> str:+ if _running_in_docker():+ return "docker"+ if _looks_like_source_checkout():+ return "source"++ installer = _metadata_value("INSTALLER")+ if installer in {"uv", "pip"}:+ return installer++ direct_url = _metadata_value("direct_url.json")+ if '"editable":true' in direct_url.replace(" ", ""):+ return "source"+ return "unknown"+++def _running_in_docker() -> bool:+ if Path("/.dockerenv").exists():+ return True+ try:+ cgroup = Path("/proc/1/cgroup").read_text(encoding="utf-8", errors="ignore")+ except OSError:+ return False+ return "docker" in cgroup or "kubepods" in cgroup or "containerd" in cgroup+++def _looks_like_source_checkout() -> bool:+ root = Path(__file__).resolve().parents[3]+ return (root / "pyproject.toml").is_file() and (root / ".git").exists()+++def _metadata_value(name: str) -> str:+ for distribution in ("mineru", "mineru-vl-utils"):+ try:+ text = metadata.distribution(distribution).read_text(name)+ except metadata.PackageNotFoundError:+ continue+ if text:+ return text.strip().lower()+ return ""+++def _gpu_vendor() -> str:+ system = platform.system()+ machine = platform.machine().lower()+ if system == "Darwin" and machine in {"arm64", "aarch64"}:+ return "apple"+ if system == "Linux":+ return _linux_gpu_vendor()+ if system == "Windows":+ return _windows_gpu_vendor()+ return "unknown"+++def _linux_gpu_vendor() -> str:+ vendor_ids: list[str] = []+ for vendor_path in Path("/sys/class/drm").glob("card*/device/vendor"):+ try:+ vendor_ids.append(vendor_path.read_text(encoding="utf-8", errors="ignore").strip().lower())+ except OSError:+ continue+ if not vendor_ids:+ for vendor_path in Path("/sys/bus/pci/devices").glob("*/vendor"):+ try:+ vendor_ids.append(vendor_path.read_text(encoding="utf-8", errors="ignore").strip().lower())+ except OSError:+ continue+ if "0x10de" in vendor_ids:+ return "nvidia"+ if "0x1002" in vendor_ids:+ return "amd"+ if "0x8086" in vendor_ids:+ return "intel"+ return "unknown"+++def _windows_gpu_vendor() -> str:+ try:+ import winreg+ except Exception:+ return "unknown"++ key_path = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"+ try:+ root = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path)+ except OSError:+ return "unknown"++ with root:+ index = 0+ while True:+ try:+ subkey_name = winreg.EnumKey(root, index)+ except OSError:+ break+ index += 1+ try:+ subkey = winreg.OpenKey(root, subkey_name)+ except OSError:+ continue+ with subkey:+ values = []+ for value_name in ("DriverDesc", "ProviderName", "MatchingDeviceId"):+ try:+ values.append(str(winreg.QueryValueEx(subkey, value_name)[0]).lower())+ except OSError:+ continue+ joined = " ".join(values)+ if "nvidia" in joined or "ven_10de" in joined:+ return "nvidia"+ if "amd" in joined or "radeon" in joined or "ven_1002" in joined:+ return "amd"+ if "intel" in joined or "ven_8086" in joined:+ return "intel"+ return "unknown"+++__all__ = [+ "build_period_payload",+ "canonical_dimensions",+ "collect_environment_context",+ "compact_json_bytes",+ "dimensions_hash",+ "utc_iso_from_ms",+]diff --git a/mineru/doclib/telemetry/service.py b/mineru/doclib/telemetry/service.pynew file mode 100644index 00000000..184fe39b--- /dev/null+++ b/mineru/doclib/telemetry/service.py@@ -0,0 +1,271 @@+"""Telemetry recording facade."""++from __future__ import annotations++import logging+import time+from dataclasses import dataclass+from typing import Any++from .buckets import duration_bucket+from .constants import CONSENT_DISABLED, CONSENT_ENABLED, DIMENSION_VALUES, METRIC_SPECS, TELEMETRY_MAX_FLUSH_PERIODS, TelemetryConsentState+from .context import get_telemetry_context+from .payload import build_period_payload, collect_environment_context+from .store import TelemetryStore, period_bounds++logger = logging.getLogger("mineru.doclib.telemetry")+++@dataclass(frozen=True)+class TelemetryFlushResult:+ status: str+ attempted: int = 0+ succeeded: int = 0+ discarded: int = 0+++class TelemetryService:+ def __init__(self, store: TelemetryStore) -> None:+ self.store = store++ async def initialize(self) -> None:+ await self.store.initialize()++ async def record_count(+ self,+ metric_name: str,+ *,+ value: int = 1,+ dimensions: dict[str, str] | None = None,+ timestamp_ms: int | None = None,+ ) -> None:+ await self._record(metric_name, value=value, dimensions=dimensions or {}, timestamp_ms=timestamp_ms)++ async def record_duration_bucket(+ self,+ metric_name: str,+ *,+ duration_ms: int,+ dimensions: dict[str, str] | None = None,+ timestamp_ms: int | None = None,+ ) -> None:+ dims = dict(dimensions or {})+ dims["bucket"] = duration_bucket(duration_ms)+ await self._record(metric_name, value=1, dimensions=dims, timestamp_ms=timestamp_ms)++ async def status(self) -> dict[str, Any]:+ pending_periods, pending_metrics = await self.store.pending_counts()+ last_flush_at = await self.store.get_state("last_flush_at")+ return {+ "state": await self.store.consent_state(),+ "installation_id": await self.store.installation_id(),+ "pending_periods": pending_periods,+ "pending_metrics": pending_metrics,+ "last_flush_at": _int_or_none(last_flush_at),+ }++ async def set_consent(self, state: TelemetryConsentState) -> dict[str, Any]:+ await self.store.set_consent_state(state)+ return {+ "state": await self.store.consent_state(),+ "installation_id": await self.store.installation_id(),+ }++ async def preview_body(self) -> dict[str, Any]:+ periods = await self.store.list_periods_for_flush(limit=1)+ if periods:+ period_start, period_end = periods[0]+ aggregates = await self.store.list_aggregates(period_start, period_end)+ else:+ period_start, period_end = period_bounds(int(time.time() * 1000))+ aggregates = []+ metrics = [+ {+ "name": aggregate.metric_name,+ "value": aggregate.metric_value,+ "dimensions": aggregate.dimensions,+ }+ for aggregate in aggregates+ ]+ return build_period_payload(+ batch_id="tb_preview",+ installation_id=await self.store.installation_id(),+ period_start=period_start,+ period_end=period_end,+ context=collect_environment_context(),+ metrics=metrics,+ )++ async def flush_once(self) -> TelemetryFlushResult:+ if await self.store.consent_state() != CONSENT_ENABLED:+ return TelemetryFlushResult(status="disabled")+ if not await self.store.try_acquire_flush_lock():+ return TelemetryFlushResult(status="locked")+ attempted = 0+ succeeded = 0+ discarded = 0+ try:+ periods = await self.store.list_periods_for_flush(limit=TELEMETRY_MAX_FLUSH_PERIODS)+ if not periods:+ return TelemetryFlushResult(status="no_metrics")+ for period_start, period_end in periods:+ aggregates = await self.store.list_aggregates(period_start, period_end)+ if not aggregates:+ await self.store.delete_period(period_start, period_end)+ continue+ attempted += 1+ metrics = [+ {+ "name": aggregate.metric_name,+ "value": aggregate.metric_value,+ "dimensions": aggregate.dimensions,+ }+ for aggregate in aggregates+ ]+ payload = build_period_payload(+ batch_id=_new_batch_id(),+ installation_id=await self.store.installation_id(),+ period_start=period_start,+ period_end=period_end,+ context=collect_environment_context(),+ metrics=metrics,+ )+ send_result = await send_payload(payload)+ if send_result == "success":+ succeeded += 1+ await self.store.delete_period(period_start, period_end)+ elif send_result == "discard":+ discarded += 1+ await self.store.delete_period(period_start, period_end)+ else:+ logger.debug("Telemetry flush deferred for period %s-%s", period_start, period_end)+ if succeeded or discarded:+ await self.store.mark_flushed_now()+ if attempted == succeeded + discarded:+ return TelemetryFlushResult(+ status="success" if discarded == 0 else "partial_success",+ attempted=attempted,+ succeeded=succeeded,+ discarded=discarded,+ )+ if succeeded or discarded:+ return TelemetryFlushResult(+ status="partial_success",+ attempted=attempted,+ succeeded=succeeded,+ discarded=discarded,+ )+ return TelemetryFlushResult(status="failed", attempted=attempted)+ finally:+ await self.store.release_flush_lock()++ async def _record(+ self,+ metric_name: str,+ *,+ value: int,+ dimensions: dict[str, str],+ timestamp_ms: int | None,+ ) -> None:+ try:+ if await self.store.consent_state() == CONSENT_DISABLED:+ return+ normalized = _normalize_dimensions(metric_name, dimensions)+ await self.store.increment(+ metric_name=metric_name,+ value=value,+ dimensions=normalized,+ timestamp_ms=timestamp_ms,+ )+ except Exception as exc:+ logger.debug("Telemetry record failed for %s: %s", metric_name, exc)+++def _normalize_dimensions(metric_name: str, dimensions: dict[str, str]) -> dict[str, str]:+ spec = METRIC_SPECS.get(metric_name)+ if spec is None:+ raise ValueError(f"Unknown telemetry metric: {metric_name}")++ ctx = get_telemetry_context()+ raw = {str(key): str(value) for key, value in dimensions.items() if value is not None}+ if "source" in spec.allowed_dimensions and "source" not in raw:+ raw["source"] = ctx.source+ if "caller" in spec.allowed_dimensions and "caller" not in raw:+ raw["caller"] = ctx.caller++ normalized: dict[str, str] = {}+ for key in sorted(spec.allowed_dimensions):+ if key not in raw:+ continue+ value = _normalize_dimension_value(key, raw[key])+ if key == "error_code" and value == "":+ continue+ normalized[key] = value++ missing = sorted(spec.required_dimensions - normalized.keys())+ if missing:+ raise ValueError(f"Telemetry metric {metric_name} missing required dimensions: {', '.join(missing)}")+ return normalized+++def _normalize_dimension_value(key: str, value: str) -> str:+ allowed = DIMENSION_VALUES.get(key)+ if allowed is None:+ return value+ if value in allowed:+ return value+ if key == "error_code":+ return "internal_error"+ if "unknown" in allowed:+ return "unknown"+ return value+++def _int_or_none(value: str | None) -> int | None:+ try:+ parsed = int(value or "0")+ except ValueError:+ return None+ if parsed <= 0:+ return None+ return parsed+++async def send_payload(payload: dict[str, Any]) -> str:+ import httpx++ from .transport import signed_headers+ from .payload import compact_json_bytes+ from .constants import TELEMETRY_ENDPOINT, TELEMETRY_HTTP_TIMEOUT_SEC++ body = compact_json_bytes(payload)+ headers = signed_headers(body)+ try:+ async with httpx.AsyncClient(timeout=TELEMETRY_HTTP_TIMEOUT_SEC) as client:+ response = await client.post(TELEMETRY_ENDPOINT, content=body, headers=headers)+ except Exception as exc:+ logger.debug("Telemetry upload failed: %s", exc)+ return "retry"+ if 200 <= response.status_code < 300:+ return "success"+ if 400 <= response.status_code < 500:+ logger.debug("Telemetry upload discarded after HTTP %s", response.status_code)+ return "discard"+ logger.debug("Telemetry upload retry after HTTP %s", response.status_code)+ return "retry"+++def _new_batch_id() -> str:+ import secrets++ return f"tb_{secrets.token_hex(16)}"+++def service_from_state(state: Any) -> TelemetryService | None:+ telemetry = getattr(state, "telemetry_svc", None)+ if isinstance(telemetry, TelemetryService):+ return telemetry+ return None+++__all__ = ["TelemetryFlushResult", "TelemetryService", "send_payload", "service_from_state"]diff --git a/mineru/doclib/telemetry/store.py b/mineru/doclib/telemetry/store.pynew file mode 100644index 00000000..38968f8e--- /dev/null+++ b/mineru/doclib/telemetry/store.py@@ -0,0 +1,234 @@+"""SQLite-backed telemetry state and aggregate storage."""++from __future__ import annotations++import secrets+import time+from dataclasses import dataclass+from typing import Any++from .constants import (+ CONSENT_DISABLED,+ CONSENT_ENABLED,+ CONSENT_UNSET,+ TELEMETRY_FLUSH_LOCK_TTL_SEC,+ TELEMETRY_MAX_FLUSH_PERIODS,+ TelemetryConsentState,+)+from .payload import canonical_dimensions, dimensions_hash+++@dataclass(frozen=True)+class TelemetryAggregate:+ id: int+ period_start: int+ period_end: int+ metric_name: str+ metric_value: int+ dimensions: dict[str, str]+ dimensions_hash: str+++class TelemetryStore:+ def __init__(self, db: Any) -> None:+ self.db = db++ async def initialize(self) -> None:+ now = _now_ms()+ await self._ensure_state("installation_id", _new_installation_id(), now)+ await self._ensure_state("consent_state", CONSENT_UNSET, now)+ await self._ensure_state("last_flush_at", "0", now)+ await self._ensure_state("flush_locked_at", "0", now)++ async def installation_id(self) -> str:+ value = await self.get_state("installation_id")+ if value:+ return value+ installation_id = _new_installation_id()+ await self.set_state("installation_id", installation_id)+ return installation_id++ async def consent_state(self) -> TelemetryConsentState:+ value = await self.get_state("consent_state")+ if value in {CONSENT_UNSET, CONSENT_ENABLED, CONSENT_DISABLED}:+ return value # type: ignore[return-value]+ return CONSENT_UNSET++ async def set_consent_state(self, state: TelemetryConsentState) -> None:+ await self.set_state("consent_state", state)+ if state == CONSENT_DISABLED:+ await self.clear_aggregates()++ async def get_state(self, key: str) -> str | None:+ row = await self.db.fetchone("SELECT value FROM telemetry_state WHERE key=?", (key,))+ if row is None:+ return None+ return str(row["value"])++ async def set_state(self, key: str, value: str) -> None:+ now = _now_ms()+ await self.db.execute(+ """+ INSERT INTO telemetry_state (key, value, updated_at)+ VALUES (?, ?, ?)+ ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at+ """,+ (key, value, now),+ )++ async def increment(+ self,+ *,+ metric_name: str,+ value: int,+ dimensions: dict[str, str],+ timestamp_ms: int | None = None,+ ) -> None:+ if value == 0:+ return+ period_start, period_end = period_bounds(timestamp_ms or _now_ms())+ canonical = canonical_dimensions(dimensions)+ dim_hash = dimensions_hash(canonical)+ now = _now_ms()+ await self.db.execute(+ """+ INSERT INTO telemetry_aggregates (+ period_start, period_end, metric_name, metric_value,+ dimensions, dimensions_hash, created_at, updated_at+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(period_start, period_end, metric_name, dimensions_hash)+ DO UPDATE SET+ metric_value=telemetry_aggregates.metric_value + excluded.metric_value,+ updated_at=excluded.updated_at+ """,+ (+ period_start,+ period_end,+ metric_name,+ int(value),+ _encode_dimensions(canonical),+ dim_hash,+ now,+ now,+ ),+ )++ async def list_periods_for_flush(self, *, limit: int = TELEMETRY_MAX_FLUSH_PERIODS) -> list[tuple[int, int]]:+ rows = await self.db.fetchall(+ """+ SELECT period_start, period_end+ FROM telemetry_aggregates+ GROUP BY period_start, period_end+ ORDER BY period_start ASC, period_end ASC+ LIMIT ?+ """,+ (limit,),+ )+ return [(int(row["period_start"]), int(row["period_end"])) for row in rows]++ async def list_aggregates(self, period_start: int, period_end: int) -> list[TelemetryAggregate]:+ rows = await self.db.fetchall(+ """+ SELECT id, period_start, period_end, metric_name, metric_value, dimensions, dimensions_hash+ FROM telemetry_aggregates+ WHERE period_start=? AND period_end=?+ ORDER BY metric_name ASC, dimensions_hash ASC+ """,+ (period_start, period_end),+ )+ return [_row_to_aggregate(row) for row in rows]++ async def pending_counts(self) -> tuple[int, int]:+ row = await self.db.fetchone(+ """+ SELECT+ COUNT(DISTINCT period_start || ':' || period_end) AS period_count,+ COUNT(*) AS aggregate_count+ FROM telemetry_aggregates+ """+ )+ if row is None:+ return 0, 0+ return int(row["period_count"] or 0), int(row["aggregate_count"] or 0)++ async def delete_period(self, period_start: int, period_end: int) -> None:+ await self.db.execute(+ "DELETE FROM telemetry_aggregates WHERE period_start=? AND period_end=?",+ (period_start, period_end),+ )++ async def clear_aggregates(self) -> None:+ await self.db.execute("DELETE FROM telemetry_aggregates")++ async def try_acquire_flush_lock(self) -> bool:+ now = _now_ms()+ locked_at_text = await self.get_state("flush_locked_at")+ try:+ locked_at = int(locked_at_text or "0")+ except ValueError:+ locked_at = 0+ if locked_at and now - locked_at < TELEMETRY_FLUSH_LOCK_TTL_SEC * 1000:+ return False+ await self.set_state("flush_locked_at", str(now))+ return True++ async def release_flush_lock(self) -> None:+ await self.set_state("flush_locked_at", "0")++ async def mark_flushed_now(self) -> None:+ await self.set_state("last_flush_at", str(_now_ms()))++ async def _ensure_state(self, key: str, value: str, now: int) -> None:+ await self.db.execute(+ """+ INSERT INTO telemetry_state (key, value, updated_at)+ SELECT ?, ?, ?+ WHERE NOT EXISTS (SELECT 1 FROM telemetry_state WHERE key=?)+ """,+ (key, value, now, key),+ )+++def period_bounds(timestamp_ms: int) -> tuple[int, int]:+ hour_ms = 60 * 60 * 1000+ start = timestamp_ms - (timestamp_ms % hour_ms)+ return start, start + hour_ms+++def _now_ms() -> int:+ return int(time.time() * 1000)+++def _new_installation_id() -> str:+ return f"inst_{secrets.token_hex(16)}"+++def _encode_dimensions(dimensions: dict[str, str]) -> str:+ import json++ return json.dumps(canonical_dimensions(dimensions), ensure_ascii=False, separators=(",", ":"))+++def _decode_dimensions(raw: str) -> dict[str, str]:+ import json++ value = json.loads(raw)+ if not isinstance(value, dict):+ return {}+ return {str(key): str(item) for key, item in value.items()}+++def _row_to_aggregate(row: dict[str, Any]) -> TelemetryAggregate:+ return TelemetryAggregate(+ id=int(row["id"]),+ period_start=int(row["period_start"]),+ period_end=int(row["period_end"]),+ metric_name=str(row["metric_name"]),+ metric_value=int(row["metric_value"]),+ dimensions=_decode_dimensions(str(row["dimensions"])),+ dimensions_hash=str(row["dimensions_hash"]),+ )+++__all__ = ["TelemetryAggregate", "TelemetryStore", "period_bounds"]diff --git a/mineru/doclib/telemetry/transport.py b/mineru/doclib/telemetry/transport.pynew file mode 100644index 00000000..47e3318c--- /dev/null+++ b/mineru/doclib/telemetry/transport.py@@ -0,0 +1,24 @@+"""Telemetry upload transport helpers."""++from __future__ import annotations++import hmac+import time+from hashlib import sha256++from .constants import TELEMETRY_APP_KEY, TELEMETRY_APP_SECRET+++def signed_headers(body: bytes, *, timestamp: int | None = None) -> dict[str, str]:+ ts = int(time.time() * 1000) if timestamp is None else timestamp+ message = TELEMETRY_APP_KEY.encode("utf-8") + str(ts).encode("utf-8") + body+ signature = hmac.new(TELEMETRY_APP_SECRET.encode("utf-8"), message, sha256).hexdigest()+ return {+ "Content-Type": "application/json",+ "X-Track-App-Key": TELEMETRY_APP_KEY,+ "X-Track-Ts": str(ts),+ "X-Track-Sign": signature,+ }+++__all__ = ["signed_headers"]diff --git a/mineru/doclib/types.py b/mineru/doclib/types.pyindex fa7a919b..9ba0a6be 100644--- a/mineru/doclib/types.py+++ b/mineru/doclib/types.py@@ -2,7 +2,7 @@from __future__ import annotations-from typing import Literal+from typing import Any, Literalfrom pydantic import BaseModel, Field@@ -15,6 +15,8 @@ ScanKind = Literal["manual", "watch"]ScanSource = Literal["unknown", "cli", "sdk", "api", "watch", "system"]RuleType = Literal["exclude", "parsing_rule"]WatchStatus = Literal["active", "unreachable"]+TelemetryConsentState = Literal["unset", "enabled", "disabled"]+TelemetryAction = Literal["enable", "disable", "flush"]InvalidateTarget = Literal["parses"]ForgetMatchedAs = Literal["file", "directory", "none"]ConfigSource = Literal["default", "override"]@@ -489,7 +491,7 @@ class ParseServerStatus(DoclibModel):remote: RemoteParseServerStatus = Field(default_factory=RemoteParseServerStatus)-class HTTPServerStatus(DoclibModel):+class TCPServerStatus(DoclibModel):enabled: bool = Falsehost: str | None = Noneport: int | None = None@@ -551,7 +553,7 @@ class ServerStatusResponse(DoclibModel):data_dir: strsqlite_path: strlog_path: str- http: HTTPServerStatus = Field(default_factory=HTTPServerStatus)+ tcp: TCPServerStatus = Field(default_factory=TCPServerStatus)active_scan_count: int = 0last_scan_at: int | None = Nonesqlite_journal_mode: str | None = None@@ -595,3 +597,58 @@ class CleanupTempRequest(DoclibModel):class CleanupTempResponse(DoclibModel):temp_files_removed: int+++class TelemetryMetric(DoclibModel):+ name: str+ value: int = 1+ dimensions: dict[str, str] = Field(default_factory=dict)+++class TelemetryPayload(DoclibModel):+ api_version: str+ batch_id: str+ schema_version: str+ installation_id: str+ period_start: str+ period_end: str+ context: dict[str, str] = Field(default_factory=dict)+ metrics: list[dict[str, Any]] = Field(default_factory=list)+++class TelemetryStatusResponse(DoclibModel):+ state: TelemetryConsentState+ installation_id: str+ pending_periods: int = 0+ pending_metrics: int = 0+ last_flush_at: int | None = None+++class TelemetryPreviewResponse(DoclibModel):+ body: TelemetryPayload+++class TelemetryActionResponse(DoclibModel):+ action: TelemetryAction+ state: TelemetryConsentState+ installation_id: str+ accepted: bool = True+ executed: bool = True+ reason: str | None = None+ flush_result: dict[str, Any] | None = None+++class TelemetryObservation(DoclibModel):+ metric_name: str+ value: int = 1+ duration_ms: int | None = None+ parse_ids: list[int] = Field(default_factory=list)+ dimensions: dict[str, str] = Field(default_factory=dict)+++class TelemetryObservationsRequest(DoclibModel):+ observations: list[TelemetryObservation] = Field(default_factory=list)+++class TelemetryObservationsResponse(DoclibModel):+ accepted: intdiff --git a/mineru/parser/api_client.py b/mineru/parser/api_client.pyindex 42e4e56a..b6617572 100644--- a/mineru/parser/api_client.py+++ b/mineru/parser/api_client.py@@ -10,11 +10,13 @@ from __future__ import annotationsimport asyncioimport hashlib+import ipaddressimport jsonimport osimport timefrom pathlib import Pathfrom typing import Any+from urllib.parse import urlparseimport httpx@@ -56,7 +58,8 @@ class MinerUApiParser(DocumentParser):api_url = api_url or os.environ.get("MINERU_API_URL", "https://mineru.net/api")self._base = api_url.rstrip("/")self._api_key = api_key- self._local = self._is_localhost(self._base)+ self._local = _is_local_network_url(self._base)+ self._trust_env = should_trust_env_for_url(self._base)self.tier = tier# ── DocumentParser interface ─────────────────────────────────────@@ -117,16 +120,7 @@ class MinerUApiParser(DocumentParser):@staticmethoddef _is_localhost(base: str) -> bool:- return any(- base.startswith(p)- for p in (- "http://localhost",- "http://127.",- "http://192.168.",- "http://10.",- "http://172.",- )- )+ return _is_local_network_url(base)@staticmethoddef _check(r: Any) -> dict[str, Any]:@@ -150,7 +144,7 @@ class MinerUApiParser(DocumentParser):size = file_path.stat().st_sizesha = _sha256_file(file_path)- with httpx.Client(timeout=httpx.Timeout(120, connect=30)) as cli:+ with httpx.Client(timeout=httpx.Timeout(120, connect=30), trust_env=self._trust_env) as cli:r = cli.post(f"{self._base}/v1/uploads",headers=self._headers(),@@ -185,7 +179,7 @@ class MinerUApiParser(DocumentParser):size = file_path.stat().st_sizesha = _sha256_file(file_path)- async with httpx.AsyncClient(timeout=httpx.Timeout(120, connect=30)) as cli:+ async with httpx.AsyncClient(timeout=httpx.Timeout(120, connect=30), trust_env=self._trust_env) as cli:r = await cli.post(f"{self._base}/v1/uploads",headers=self._headers(),@@ -219,7 +213,7 @@ class MinerUApiParser(DocumentParser):# ── parse execution ──────────────────────────────────────────────def _do_parse(self, payload: dict[str, Any]) -> dict[str, Any]:- with httpx.Client(timeout=httpx.Timeout(120, connect=30)) as cli:+ with httpx.Client(timeout=httpx.Timeout(120, connect=30), trust_env=self._trust_env) as cli:r = cli.post(f"{self._base}/v1/parse/jobs", headers=self._headers(), json=payload)job = self._check(r)if job.get("status") not in ("completed", "partial", "failed", "canceled"):@@ -228,7 +222,7 @@ class MinerUApiParser(DocumentParser):return jobasync def _async_do_parse(self, payload: dict[str, Any]) -> dict[str, Any]:- async with httpx.AsyncClient(timeout=httpx.Timeout(120, connect=30)) as cli:+ async with httpx.AsyncClient(timeout=httpx.Timeout(120, connect=30), trust_env=self._trust_env) as cli:r = await cli.post(f"{self._base}/v1/parse/jobs", headers=self._headers(), json=payload)job = self._check(r)if job.get("status") not in ("completed", "partial", "failed", "canceled"):@@ -403,7 +397,7 @@ def _download_bytes(parser: MinerUApiParser, ref: dict[str, Any]) -> bytes:# TEMP(2026-06-12): staging server may return {"url": "..."} instead of# {"file_id": "...", "bytes": ...}. Keep this branch until staging aligns.if ref.get("url"):- with httpx.Client(timeout=httpx.Timeout(120, connect=30), follow_redirects=True) as cli:+ with httpx.Client(timeout=httpx.Timeout(120, connect=30), follow_redirects=True, trust_env=parser._trust_env) as cli:r = cli.get(ref["url"])_check_download_response(r)return r.content@@ -412,7 +406,7 @@ def _download_bytes(parser: MinerUApiParser, ref: dict[str, Any]) -> bytes:if not file_id:raise _V1APIError("invalid_response", "No file_id or url in output reference")- with httpx.Client(timeout=httpx.Timeout(120, connect=30), follow_redirects=True) as cli:+ with httpx.Client(timeout=httpx.Timeout(120, connect=30), follow_redirects=True, trust_env=parser._trust_env) as cli:r = cli.get(f"{parser._base}/v1/files/{file_id}/content", headers=parser._headers())_check_download_response(r)return r.content@@ -422,7 +416,7 @@ async def _async_download_bytes(parser: MinerUApiParser, ref: dict[str, Any]) -># TEMP(2026-06-12): staging server may return {"url": "..."} instead of# {"file_id": "...", "bytes": ...}. Keep this branch until staging aligns.if ref.get("url"):- async with httpx.AsyncClient(timeout=httpx.Timeout(120, connect=30), follow_redirects=True) as cli:+ async with httpx.AsyncClient(timeout=httpx.Timeout(120, connect=30), follow_redirects=True, trust_env=parser._trust_env) as cli:r = await cli.get(ref["url"])_check_download_response(r)return r.content@@ -431,12 +425,31 @@ async def _async_download_bytes(parser: MinerUApiParser, ref: dict[str, Any]) ->if not file_id:raise _V1APIError("invalid_response", "No file_id or url in output reference")- async with httpx.AsyncClient(timeout=httpx.Timeout(120, connect=30), follow_redirects=True) as cli:+ async with httpx.AsyncClient(timeout=httpx.Timeout(120, connect=30), follow_redirects=True, trust_env=parser._trust_env) as cli:r = await cli.get(f"{parser._base}/v1/files/{file_id}/content", headers=parser._headers())_check_download_response(r)return r.content+def should_trust_env_for_url(url: str) -> bool:+ return not _is_local_network_url(url)+++def _is_local_network_url(url: str) -> bool:+ parsed = urlparse(url if "://" in url else f"http://{url}")+ host = parsed.hostname+ if not host:+ return False+ normalized = host.lower()+ if normalized == "localhost" or normalized.endswith(".localhost"):+ return True+ try:+ address = ipaddress.ip_address(normalized)+ except ValueError:+ return False+ return address.is_loopback or address.is_private or address.is_link_local++def _check_download_response(r: httpx.Response) -> None:if r.status_code < 400:returndiff --git a/tests/unittest/test_cli_next_command_design.py b/tests/unittest/test_cli_next_command_design.pyindex 427cab0c..bd740543 100644--- a/tests/unittest/test_cli_next_command_design.py+++ b/tests/unittest/test_cli_next_command_design.py@@ -5,12 +5,14 @@ import osfrom pathlib import Pathfrom typing import Any+import pytestfrom typer.testing import CliRunner-from mineru.cli.commands import config, list_resources, parse, read, server, show+from mineru.cli.commands import config, list_resources, parse, read, server, show, telemetryfrom mineru.cli.commands import cleanup as cleanup_cmdfrom mineru.cli.commands import search as search_modfrom mineru.cli.commands import watch as watch_cmd+from mineru.cli import telemetry as cli_telemetryfrom mineru.cli.main import appfrom mineru.doclib.types import (ContentAsset,@@ -24,6 +26,8 @@ from mineru.doclib.types import (ListParsesResponse,ParseInfo,ParseResponse,+ TelemetryActionResponse,+ TelemetryStatusResponse,)@@ -54,6 +58,62 @@ def test_parse_and_read_help_document_output_parent_creation() -> None:assert "directories" in read_result.output+def test_telemetry_command_tree_is_available() -> None:+ result = runner.invoke(app, ["telemetry", "--help"])++ assert result.exit_code == 0+ assert "status" in result.output+ assert "preview" in result.output+ assert "flush" in result.output+++def test_telemetry_status_command_prints_installation_id(monkeypatch: Any) -> None:+ class _Client:+ def __init__(self, *, timeout: int) -> None:+ assert timeout == 30++ def get_telemetry_status(self) -> TelemetryStatusResponse:+ return TelemetryStatusResponse(+ state="unset",+ installation_id="inst_test",+ pending_periods=1,+ pending_metrics=2,+ last_flush_at=None,+ )++ monkeypatch.setattr(telemetry, "DoclibClient", _Client)++ result = runner.invoke(app, ["telemetry", "status"])++ assert result.exit_code == 0+ assert "state: unset" in result.output+ assert "installation_id: inst_test" in result.output+++def test_interactive_unset_prompt_enables_telemetry(monkeypatch: Any) -> None:+ actions: list[str] = []++ class _Client:+ def __init__(self, *, timeout: int) -> None:+ assert timeout == 5++ def get_telemetry_status(self) -> TelemetryStatusResponse:+ return TelemetryStatusResponse(state="unset", installation_id="inst_test")++ def telemetry_action(self, action: str) -> TelemetryActionResponse:+ actions.append(action)+ return TelemetryActionResponse(action=action, state="enabled", installation_id="inst_test")++ monkeypatch.setattr(cli_telemetry, "DoclibClient", _Client)+ monkeypatch.setattr(cli_telemetry, "_is_interactive", lambda: True)+ monkeypatch.setattr("typer.echo", lambda *args, **kwargs: None)+ monkeypatch.setattr("typer.confirm", lambda *args, **kwargs: True)++ cli_telemetry.maybe_prompt_telemetry_consent()++ assert actions == ["enable"]++def test_config_rules_tree_uses_explicit_resource_names_and_remove() -> None:exclude_rules = runner.invoke(app, ["config", "exclude-rules", "--help"])exclude_legacy = runner.invoke(app, ["config", "exclude", "--help"])@@ -466,8 +526,9 @@ def test_server_start_failure_points_to_log_and_does_not_discard_child_stderr(moreturn _Proc()monkeypatch.setattr(server, "_server_running", lambda: False)- monkeypatch.setattr(server, "_wait_for_sock", lambda: False)+ monkeypatch.setattr(server, "_wait_for_server", lambda: False)monkeypatch.setattr(server, "_socket_path", lambda: str(tmp_path / "doclib.sock"))+ monkeypatch.setattr(server, "_endpoint_path", lambda: str(tmp_path / "doclib.endpoint.json"))monkeypatch.setattr(server, "_server_log_path", lambda: str(log_path))monkeypatch.setattr(server.subprocess, "Popen", _popen)@@ -480,6 +541,20 @@ def test_server_start_failure_points_to_log_and_does_not_discard_child_stderr(moassert popen_calls[-1] == {"kill": True}+def test_server_start_lock_blocks_concurrent_start(monkeypatch: Any, tmp_path: Path) -> None:+ monkeypatch.setattr(server, "_server_running", lambda: False)+ lock_path = tmp_path / "doclib.start.lock"++ with server._ServerStartLock(str(lock_path), timeout=0.1, stale_after=60.0) as lock:+ assert lock.acquired is True+ assert lock_path.is_file()+ with pytest.raises(RuntimeError, match="already in progress"):+ with server._ServerStartLock(str(lock_path), timeout=0.1, stale_after=60.0):+ pass++ assert not lock_path.exists()++def test_parse_content_read_failure_exits_nonzero(monkeypatch: Any, tmp_path: Path) -> None:source = tmp_path / "demo.txt"source.write_text("hello", encoding="utf-8")@@ -765,5 +840,5 @@ def test_server_status_json_not_running_returns_state_json(monkeypatch: Any) ->assert payload["socket_path"] == "/tmp/doclib.sock"assert payload["sqlite_path"] == os.path.expanduser("~/.mineru/doclib.db")assert payload["log_path"] == os.path.expanduser("~/.mineru/doclib.log")- assert payload["http"] == {"enabled": False, "host": None, "port": None}+ assert payload["tcp"] == {"enabled": False, "host": None, "port": None}assert "Server is not running." not in result.outputdiff --git a/tests/unittest/test_doclib_app_startup.py b/tests/unittest/test_doclib_app_startup.pyindex 91743e46..df4de95a 100644--- a/tests/unittest/test_doclib_app_startup.py+++ b/tests/unittest/test_doclib_app_startup.py@@ -5,7 +5,7 @@ from pathlib import Pathimport pytestfrom fastapi.testclient import TestClient-from mineru.config import LogConfig, PatchedConfig, config as mineru_config+from mineru.config import LogConfig, PatchedConfig, config as mineru_config, resolve_tcp_enabledfrom mineru.doclib import app as doclib_appfrom mineru.doclib.app import _assert_required_schemafrom mineru.doclib.core.db import DatabaseManager@@ -66,7 +66,37 @@ def test_server_status_reports_configured_socket_path(monkeypatch, tmp_path) ->assert payload["socket_path"] == str(tmp_path / "doclib.sock")assert payload["sqlite_path"] == str(tmp_path / "doclib.db")assert payload["log_path"] == str(tmp_path / "doclib.log")- assert payload["http"] == {"enabled": cfg.doclib.http.enabled, "host": cfg.doclib.http.host, "port": None}+ assert payload["tcp"] == {"enabled": resolve_tcp_enabled(cfg), "host": cfg.doclib.tcp.host, "port": None}+++def test_telemetry_observation_route_uses_context_headers(monkeypatch, tmp_path) -> None:+ cfg = PatchedConfig(+ doclib={+ "data_dir": str(tmp_path),+ "sqlite": {"path": str(tmp_path / "doclib.db")},+ "log": {"path": str(tmp_path / "doclib.log")},+ "uds": {"path": str(tmp_path / "doclib.sock")},+ }+ )++ def _skip_background_task(*args, **kwargs):+ return None++ monkeypatch.setattr(doclib_app, "_create_background_task", _skip_background_task)++ with TestClient(doclib_app.create_app(cfg)) as client:+ response = client.post(+ "/api/v1/observations",+ headers={"X-MinerU-Telemetry-Source": "cli", "X-MinerU-Telemetry-Caller": "agent"},+ json={"observations": [{"metric_name": "parse.request.count"}]},+ )+ preview = client.get("/api/v1/telemetry/preview")++ assert response.status_code == 200+ assert response.json() == {"accepted": 1}+ assert preview.status_code == 200+ metrics = preview.json()["body"]["metrics"]+ assert metrics == [{"name": "parse.request.count", "value": 1, "dimensions": {"caller": "agent", "source": "cli"}}]def test_write_temp_asset_uses_temp_read_assets_directory(tmp_path: Path) -> None:diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.pyindex c06653be..90022a15 100644--- a/tests/unittest/test_doclib_cache_semantics.py+++ b/tests/unittest/test_doclib_cache_semantics.py@@ -13,7 +13,7 @@ import pytestfrom mineru.doclib.background.compaction import Compactionfrom mineru.doclib.background.device_monitor import DeviceMonitorfrom mineru.doclib.background.ingest import IngestWorkerPool-from mineru.doclib.background.parse_server_health import api_server_args_for_tier+from mineru.doclib.background.parse_server_health import ParseServerHealthCheck, api_server_args_for_tierfrom mineru.doclib.background.watch import WatchLoopfrom mineru.doclib.core.db import DatabaseManagerfrom mineru.doclib.core.file_io import FileStat, get_file_stat@@ -248,6 +248,36 @@ def test_managed_api_server_args_use_tier_for_process_start() -> None:assert api_server_args_for_tier("pro") == ["--tier", "pro", "--port", "15981"]+def test_parse_server_health_probe_disables_env_proxy_for_local_urls(monkeypatch: pytest.MonkeyPatch) -> None:+ calls: list[bool] = []++ class _Response:+ status_code = 200++ def json(self) -> dict[str, list[dict[str, str]]]:+ return {"data": [{"id": "standard"}]}++ class _AsyncClient:+ def __init__(self, *, timeout: int, trust_env: bool) -> None:+ calls.append(trust_env)++ async def __aenter__(self) -> "_AsyncClient":+ return self++ async def __aexit__(self, *args: object) -> None:+ return None++ async def get(self, url: str) -> _Response:+ return _Response()++ monkeypatch.setattr("mineru.doclib.background.parse_server_health.httpx.AsyncClient", _AsyncClient)+ checker = ParseServerHealthCheck(None, interval_sec=1, probe_timeout_sec=2, startup_grace_sec=3, stop_timeout_sec=4)++ assert asyncio.run(checker._probe("http://127.0.0.1:15981")) == (True, ["standard"])+ assert asyncio.run(checker._probe("https://staging.mineru.org.cn/api")) == (True, ["standard"])+ assert calls == [False, True]++def test_get_file_stat_returns_typed_file_stat(tmp_path: Path) -> None:source = tmp_path / "note.txt"source.write_text("content", encoding="utf-8")diff --git a/tests/unittest/test_doclib_config.py b/tests/unittest/test_doclib_config.pyindex 9484f85b..c60eb140 100644--- a/tests/unittest/test_doclib_config.py+++ b/tests/unittest/test_doclib_config.py@@ -12,6 +12,8 @@ from mineru.config import (_interpolate_env,_load_config,_read_config,+ resolve_tcp_enabled,+ resolve_uds_enabled,)from mineru.doclib.config_defaults import CONFIG_DEFAULTS@@ -52,7 +54,7 @@ def test_load_config_reads_yaml_and_interpolates_env(tmp_path, monkeypatch: pyte"""doclib:data_dir: ${MINERU_TEST_DATA}- http:+ tcp:enabled: trueport: 18080sqlite:@@ -64,15 +66,15 @@ doclib:data = _load_config(str(config_file))assert data["doclib"]["data_dir"] == str(tmp_path / "data")- assert data["doclib"]["http"]["enabled"] is True- assert data["doclib"]["http"]["port"] == 18080+ assert data["doclib"]["tcp"]["enabled"] is True+ assert data["doclib"]["tcp"]["port"] == 18080assert data["doclib"]["sqlite"]["path"] == str(tmp_path / "data" / "doclib.db")def test_apply_env_overrides_uses_greedy_field_path_matching(monkeypatch: pytest.MonkeyPatch) -> None:prefix = "TEST_MINERU_"- monkeypatch.setenv("TEST_MINERU_DOCLIB_HTTP_ENABLED", "true")- monkeypatch.setenv("TEST_MINERU_DOCLIB_HTTP_PORT", "15990")+ monkeypatch.setenv("TEST_MINERU_DOCLIB_TCP_ENABLED", "true")+ monkeypatch.setenv("TEST_MINERU_DOCLIB_TCP_PORT", "15990")monkeypatch.setenv("TEST_MINERU_DOCLIB_COMPACTION_INTERVAL_SEC", "5")monkeypatch.setenv("TEST_MINERU_DOCLIB_SCAN_INTERVAL_SEC", "7")monkeypatch.setenv("TEST_MINERU_DOCLIB_DEVICE_CHECK_INTERVAL_SEC", "11")@@ -89,8 +91,8 @@ def test_apply_env_overrides_uses_greedy_field_path_matching(monkeypatch: pytestcfg = _apply_env_overrides(Config(), prefix=prefix)- assert cfg.doclib.http.enabled is True- assert cfg.doclib.http.port == 15990+ assert cfg.doclib.tcp.enabled is True+ assert cfg.doclib.tcp.port == 15990assert cfg.doclib.compaction_interval_sec == 5assert cfg.doclib.scan_interval_sec == 7assert cfg.doclib.device_check_interval_sec == 11@@ -120,7 +122,7 @@ def test_read_config_uses_default_config_under_mineru_home(tmp_path, monkeypatch"""doclib:data_dir: /tmp/ignored-data-dir- http:+ tcp:port: 18080""",encoding="utf-8",@@ -128,7 +130,7 @@ doclib:data = _read_config()- assert data["doclib"]["http"]["port"] == 18080+ assert data["doclib"]["tcp"]["port"] == 18080assert data["doclib"]["data_dir"] == "/tmp/ignored-data-dir"@@ -143,7 +145,6 @@ def test_apply_env_overrides_can_override_doclib_data_dir(monkeypatch: pytest.Modef test_default_uds_path_uses_mineru_home_on_unix(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr("mineru.config._uds_available", lambda: True)monkeypatch.setattr("mineru.config.platform.system", lambda: "Linux")monkeypatch.setenv("MINERU_HOME", "/tmp/mineru-home")@@ -151,17 +152,68 @@ def test_default_uds_path_uses_mineru_home_on_unix(monkeypatch: pytest.MonkeyPatdef test_default_uds_path_uses_mineru_home_on_windows(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr("mineru.config._uds_available", lambda: True)monkeypatch.setattr("mineru.config.platform.system", lambda: "Windows")monkeypatch.setenv("MINERU_HOME", r"C:\MinerU")assert _default_uds_path() == r"C:\MinerU/doclib.sock"+def test_default_transport_prefers_uds_when_available(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("mineru.config._uds_available", lambda: True)++ cfg = Config()++ assert cfg.doclib.uds.enabled == "auto"+ assert cfg.doclib.tcp.enabled == "auto"+ assert resolve_uds_enabled(cfg) is True+ assert resolve_tcp_enabled(cfg) is False+++def test_default_transport_falls_back_to_tcp_when_uds_unavailable(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("mineru.config._uds_available", lambda: False)++ cfg = Config()++ assert cfg.doclib.uds.enabled == "auto"+ assert cfg.doclib.tcp.enabled == "auto"+ assert resolve_uds_enabled(cfg) is False+ assert resolve_tcp_enabled(cfg) is True+++def test_transport_enabled_accepts_auto_and_explicit_bool(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("mineru.config._uds_available", lambda: True)++ auto_cfg = Config(doclib={"uds": {"enabled": "auto"}, "tcp": {"enabled": "auto"}})+ explicit_cfg = Config(doclib={"uds": {"enabled": False}, "tcp": {"enabled": True}})++ assert auto_cfg.doclib.uds.enabled == "auto"+ assert auto_cfg.doclib.tcp.enabled == "auto"+ assert resolve_uds_enabled(auto_cfg) is True+ assert resolve_tcp_enabled(auto_cfg) is False+ assert explicit_cfg.doclib.uds.enabled is False+ assert explicit_cfg.doclib.tcp.enabled is True+ assert resolve_uds_enabled(explicit_cfg) is False+ assert resolve_tcp_enabled(explicit_cfg) is True+++def test_transport_enabled_accepts_auto_from_env(monkeypatch: pytest.MonkeyPatch) -> None:+ prefix = "TEST_MINERU_"+ monkeypatch.setattr("mineru.config._uds_available", lambda: True)+ monkeypatch.setenv("TEST_MINERU_DOCLIB_UDS_ENABLED", "auto")+ monkeypatch.setenv("TEST_MINERU_DOCLIB_TCP_ENABLED", "auto")++ cfg = _apply_env_overrides(Config(doclib={"uds": {"enabled": False}, "tcp": {"enabled": True}}), prefix=prefix)++ assert cfg.doclib.uds.enabled == "auto"+ assert cfg.doclib.tcp.enabled == "auto"+ assert resolve_uds_enabled(cfg) is True+ assert resolve_tcp_enabled(cfg) is False++def test_patched_config_returns_validated_deep_patch() -> None:- cfg = PatchedConfig(doclib={"http": {"port": "16000"}, "sqlite": {"cache_size": "-1"}})+ cfg = PatchedConfig(doclib={"tcp": {"port": "16000"}, "sqlite": {"cache_size": "-1"}})- assert cfg.doclib.http.port == 16000+ assert cfg.doclib.tcp.port == 16000assert cfg.doclib.sqlite.cache_size == -1diff --git a/tests/unittest/test_doclib_endpoint.py b/tests/unittest/test_doclib_endpoint.pynew file mode 100644index 00000000..76c73d6d--- /dev/null+++ b/tests/unittest/test_doclib_endpoint.py@@ -0,0 +1,88 @@+from __future__ import annotations++import json++import pytest++from mineru.config import PatchedConfig+from mineru.doclib import client as client_module+from mineru.doclib.client import DoclibClient+from mineru.doclib.endpoint import (+ DOCLIB_UDS_BASE_URL,+ EndpointTransport,+ config_transports,+ read_endpoint_file,+ write_endpoint_file,+)+++def test_endpoint_file_round_trips_transports(tmp_path) -> None:+ endpoint = tmp_path / "doclib.endpoint.json"++ write_endpoint_file(+ endpoint,+ pid=123,+ transports=[+ EndpointTransport(type="uds", path=str(tmp_path / "doclib.sock")),+ EndpointTransport(type="tcp", base_url="http://127.0.0.1:15980"),+ ],+ )++ payload = json.loads(endpoint.read_text(encoding="utf-8"))+ assert payload["version"] == 1+ assert payload["pid"] == 123+ assert read_endpoint_file(endpoint) == [+ EndpointTransport(type="uds", path=str(tmp_path / "doclib.sock")),+ EndpointTransport(type="tcp", base_url="http://127.0.0.1:15980"),+ ]+++def test_config_transports_uses_tcp_when_uds_disabled(tmp_path) -> None:+ cfg = PatchedConfig(+ doclib={+ "uds": {"enabled": False, "path": str(tmp_path / "doclib.sock")},+ "tcp": {"enabled": True, "host": "127.0.0.1", "port": 17000},+ }+ )++ assert config_transports(cfg) == [EndpointTransport(type="tcp", base_url="http://127.0.0.1:17000")]+++def test_doclib_client_rejects_explicit_uds_and_tcp() -> None:+ with pytest.raises(ValueError, match="socket_path and base_url"):+ DoclibClient(socket_path="/tmp/doclib.sock", base_url="http://127.0.0.1:15980")+++def test_doclib_client_discovers_uds_then_tcp(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:+ endpoint = tmp_path / "doclib.endpoint.json"+ write_endpoint_file(+ endpoint,+ pid=123,+ transports=[+ EndpointTransport(type="tcp", base_url="http://127.0.0.1:15980"),+ EndpointTransport(type="uds", path=str(tmp_path / "doclib.sock")),+ ],+ )+ calls: list[dict] = []++ class _Transport:+ def __init__(self, *, uds: str) -> None:+ self.uds = uds++ class _Client:+ def __init__(self, *, transport=None, base_url: str, timeout: int, trust_env: bool) -> None:+ calls.append({"transport": transport, "base_url": base_url, "timeout": timeout, "trust_env": trust_env})++ def close(self) -> None:+ pass++ monkeypatch.setattr(client_module, "uds_available", lambda: True)+ monkeypatch.setattr(client_module.httpx, "HTTPTransport", _Transport)+ monkeypatch.setattr(client_module.httpx, "Client", _Client)++ client = DoclibClient(endpoint_path=endpoint, timeout=5)+ client.close()++ assert calls[0]["base_url"] == DOCLIB_UDS_BASE_URL+ assert calls[0]["transport"].uds == str(tmp_path / "doclib.sock")+ assert calls[1] == {"transport": None, "base_url": "http://127.0.0.1:15980", "timeout": 5, "trust_env": False}diff --git a/tests/unittest/test_doclib_interface_contract.py b/tests/unittest/test_doclib_interface_contract.pyindex 9bbc3ca1..a2045027 100644--- a/tests/unittest/test_doclib_interface_contract.py+++ b/tests/unittest/test_doclib_interface_contract.py@@ -99,6 +99,10 @@ def test_doclib_interface_declares_expected_methods() -> None:"cleanup_deleted_files","cleanup_orphan_docs","cleanup_temp_files",+ "get_telemetry_status",+ "get_telemetry_preview",+ "telemetry_action",+ "record_observations",}assert DoclibInterface.__abstractmethods__ == expected@@ -181,6 +185,10 @@ def test_interface_app_uses_doclib_server_routes() -> None:route_paths = {getattr(route, "path", "") for route in app.routes}assert "/api/v1/server/status" in route_pathsassert "/api/v1/server/shutdown" in route_paths+ assert "/api/v1/telemetry/status" in route_paths+ assert "/api/v1/telemetry/preview" in route_paths+ assert "/api/v1/telemetry/actions/{action}" in route_paths+ assert "/api/v1/observations" in route_pathsassert "/api/v1/configs" in route_pathsassert "/api/v1/configs/{key}" in route_pathsassert "/api/v1/watches" in route_pathsdiff --git a/tests/unittest/test_doclib_telemetry_core.py b/tests/unittest/test_doclib_telemetry_core.pynew file mode 100644index 00000000..e6fb5eb6--- /dev/null+++ b/tests/unittest/test_doclib_telemetry_core.py@@ -0,0 +1,463 @@+from __future__ import annotations++import asyncio+from types import SimpleNamespace++from mineru.doclib.core.db import DatabaseManager+from mineru.doclib.server import DoclibServer+from mineru.doclib.services.config_svc import ConfigService+from mineru.doclib.services.parse_svc import ParseService+from mineru.doclib.services.scan_svc import ScanService, _ScanCounters+from mineru.doclib.telemetry import (+ TelemetryContext,+ TelemetryService,+ TelemetryStore,+ duration_bucket,+ file_size_bucket,+ pages_bucket,+ reset_telemetry_context,+ results_bucket,+ set_telemetry_context,+)+from mineru.doclib.telemetry.constants import CONSENT_DISABLED, CONSENT_UNSET+from mineru.doclib.telemetry.payload import build_period_payload, compact_json_bytes, dimensions_hash+from mineru.doclib.telemetry.transport import signed_headers+from mineru.doclib.telemetry import service as telemetry_service_module+from mineru.doclib.types import ParseRequest+from mineru.doclib.types import TelemetryObservation, TelemetryObservationsRequest+++def test_bucket_helpers_use_documented_boundaries() -> None:+ assert duration_bucket(999) == "lt_1s"+ assert duration_bucket(1_000) == "1_5s"+ assert duration_bucket(5_000) == "5_30s"+ assert duration_bucket(120_000) == "2_10m"+ assert duration_bucket(600_000) == "gt_10m"++ assert pages_bucket(0) == "1"+ assert pages_bucket(5) == "2_5"+ assert pages_bucket(501) == "gt_500"++ assert file_size_bucket(1024 * 1024 - 1) == "lt_1mb"+ assert file_size_bucket(10 * 1024 * 1024) == "10_50mb"+ assert results_bucket(0) == "0"+ assert results_bucket(101) == "gt_100"+++def test_store_initializes_installation_id_and_consent_state(tmp_path) -> None:+ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ store = TelemetryStore(db)+ await store.initialize()++ installation_id = await store.installation_id()+ assert installation_id.startswith("inst_")+ assert await store.installation_id() == installation_id+ assert await store.consent_state() == CONSENT_UNSET++ asyncio.run(_run())+++def test_status_counts_all_pending_periods_not_just_flush_limit(tmp_path) -> None:+ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ store = TelemetryStore(db)+ service = TelemetryService(store)+ await service.initialize()++ for index in range(12):+ await service.record_count("search.request.count", timestamp_ms=1_700_000_000_000 + index * 3_600_000)++ status = await service.status()++ assert status["pending_periods"] == 12+ assert status["pending_metrics"] == 12++ asyncio.run(_run())+++def test_service_records_aggregates_and_uses_context_dimensions(tmp_path) -> None:+ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ store = TelemetryStore(db)+ service = TelemetryService(store)+ await service.initialize()++ token = set_telemetry_context(TelemetryContext(source="cli", caller="agent"))+ try:+ await service.record_count("parse.request.count", timestamp_ms=1_700_000_000_000)+ await service.record_duration_bucket(+ "parse.duration_bucket.count",+ duration_ms=42_000,+ dimensions={"status": "succeeded", "tier": "flash"},+ timestamp_ms=1_700_000_000_000,+ )+ finally:+ reset_telemetry_context(token)++ periods = await store.list_periods_for_flush()+ assert len(periods) == 1+ aggregates = await store.list_aggregates(*periods[0])+ by_name = {item.metric_name: item for item in aggregates}++ assert by_name["parse.request.count"].metric_value == 1+ assert by_name["parse.request.count"].dimensions == {"caller": "agent", "source": "cli"}+ assert by_name["parse.duration_bucket.count"].dimensions == {+ "bucket": "30_120s",+ "caller": "agent",+ "source": "cli",+ "status": "succeeded",+ "tier": "flash",+ }++ asyncio.run(_run())+++def test_disabled_consent_clears_and_blocks_aggregates(tmp_path) -> None:+ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ store = TelemetryStore(db)+ service = TelemetryService(store)+ await service.initialize()++ await service.record_count("search.request.count")+ assert await store.list_periods_for_flush()++ await store.set_consent_state(CONSENT_DISABLED)+ assert await store.list_periods_for_flush() == []++ await service.record_count("search.request.count")+ assert await store.list_periods_for_flush() == []++ asyncio.run(_run())+++def test_payload_is_compact_and_dimension_hash_is_order_stable() -> None:+ first = dimensions_hash({"source": "cli", "caller": "agent"})+ second = dimensions_hash({"caller": "agent", "source": "cli"})+ assert first == second++ payload = build_period_payload(+ batch_id="tb_test",+ installation_id="inst_test",+ period_start=1_700_000_000_000,+ period_end=1_700_003_600_000,+ context={"app": "mineru"},+ metrics=[{"name": "parse.request.count", "value": 1, "dimensions": {"source": "cli"}}],+ )+ raw = compact_json_bytes(payload)+ assert b" " not in raw+ assert b'"api_version":"v2"' in raw+ assert b'"period_start":"2023-11-14T22:13:20.000Z"' in raw+++def test_telemetry_service_preview_returns_next_period_body(tmp_path) -> None:+ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ store = TelemetryStore(db)+ service = TelemetryService(store)+ await service.initialize()++ await service.record_count("parse.request.count", timestamp_ms=1_700_000_000_000)+ body = await service.preview_body()++ assert body["batch_id"] == "tb_preview"+ assert body["installation_id"].startswith("inst_")+ assert body["period_start"] == "2023-11-14T22:00:00.000Z"+ assert body["metrics"] == [+ {"name": "parse.request.count", "value": 1, "dimensions": {"caller": "unknown", "source": "unknown"}}+ ]++ asyncio.run(_run())+++def test_signed_headers_match_staging_api_contract() -> None:+ body = b'{"api_version":"v2"}'+ headers = signed_headers(body, timestamp=1_700_000_000_000)++ assert headers["Content-Type"] == "application/json"+ assert headers["X-Track-App-Key"] == "213a83db-44c8-4218-90c0-ded685cca86e"+ assert headers["X-Track-Ts"] == "1700000000000"+ assert headers["X-Track-Sign"] == "a64fb6b8ad0f9aa89866685f9a849e7fa316742e7ee147cc22e1789d225370ea"+++def test_flush_once_sends_enabled_period_and_deletes_on_success(monkeypatch, tmp_path) -> None:+ async def _run() -> None:+ captured: list[dict] = []++ async def _send(payload: dict) -> str:+ captured.append(payload)+ return "success"++ monkeypatch.setattr(telemetry_service_module, "send_payload", _send)+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ store = TelemetryStore(db)+ service = TelemetryService(store)+ await service.initialize()+ await store.set_consent_state("enabled")+ await service.record_count("search.request.count", timestamp_ms=1_700_000_000_000)++ result = await service.flush_once()++ assert result.status == "success"+ assert result.attempted == 1+ assert len(captured) == 1+ assert captured[0]["metrics"] == [+ {"name": "search.request.count", "value": 1, "dimensions": {"caller": "unknown", "source": "unknown"}}+ ]+ assert await store.list_periods_for_flush() == []++ asyncio.run(_run())+++def test_flush_once_keeps_period_on_retry(monkeypatch, tmp_path) -> None:+ async def _run() -> None:+ async def _send(_payload: dict) -> str:+ return "retry"++ monkeypatch.setattr(telemetry_service_module, "send_payload", _send)+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ store = TelemetryStore(db)+ service = TelemetryService(store)+ await service.initialize()+ await store.set_consent_state("enabled")+ await service.record_count("find.request.count", timestamp_ms=1_700_000_000_000)++ result = await service.flush_once()++ assert result.status == "failed"+ assert result.attempted == 1+ assert await store.list_periods_for_flush()++ asyncio.run(_run())+++def test_parse_route_records_request_finished_and_duration_metrics(tmp_path) -> None:+ class _ParseService:+ async def request_parse(self, *args, **kwargs) -> dict:+ return {+ "sha256": "abc",+ "tier": "standard",+ "page_range": "1",+ "status": "pending",+ "cache_hit": False,+ "wait_parse_ids": [1],+ "created_parse_ids": [1],+ "reused_parse_ids": [],+ }++ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ store = TelemetryStore(db)+ telemetry = TelemetryService(store)+ await telemetry.initialize()+ server = DoclibServer(SimpleNamespace(parse_svc=_ParseService(), telemetry_svc=telemetry))++ await server.ensure_parse(ParseRequest(path="/tmp/a.pdf", tier="standard"))+ body = await telemetry.preview_body()++ metric_names = {metric["name"] for metric in body["metrics"]}+ assert "parse.request.count" in metric_names+ assert "parse.finished.count" in metric_names+ assert "parse.duration_bucket.count" in metric_names+ finished = next(metric for metric in body["metrics"] if metric["name"] == "parse.finished.count")+ assert finished["dimensions"] == {+ "caller": "unknown",+ "source": "unknown",+ "status": "queued",+ "tier": "standard",+ }++ asyncio.run(_run())+++def test_search_route_records_result_bucket_metrics(tmp_path) -> None:+ class _SearchService:+ async def search(self, **kwargs) -> tuple[list[dict], int]:+ return [], 0++ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ store = TelemetryStore(db)+ telemetry = TelemetryService(store)+ await telemetry.initialize()+ server = DoclibServer(SimpleNamespace(search_svc=_SearchService(), telemetry_svc=telemetry))++ await server.search("needle")+ body = await telemetry.preview_body()++ by_name = {metric["name"]: metric for metric in body["metrics"]}+ assert by_name["search.request.count"]["value"] == 1+ assert by_name["search.finished.count"]["dimensions"]["status"] == "succeeded"+ assert by_name["search.results_bucket.count"]["dimensions"] == {+ "bucket": "0",+ "caller": "unknown",+ "source": "unknown",+ }++ asyncio.run(_run())+++def test_parse_service_process_doc_records_task_metrics(tmp_path) -> None:+ class _Fts:+ async def get_tier(self, sha256: str) -> str | None:+ return None++ async def replace(self, **kwargs) -> None:+ return None++ async def upsert_filename(self, *args, **kwargs) -> None:+ return None++ class _Result:+ def to_dict(self, *, skip_defaults: bool = True) -> dict:+ return {"pages": [{"page_idx": 0, "blocks": []}]}++ def markdown(self, *, add_markers: bool = False) -> str:+ return "content"++ class _ParseService(ParseService):+ async def _parse_via_local(self, file_row, tier, page_range):+ return _Result()++ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ store = TelemetryStore(db)+ telemetry = TelemetryService(store)+ await telemetry.initialize()+ config_svc = ConfigService(db)+ parse_svc = _ParseService(+ db,+ _Fts(),+ config_svc,+ str(tmp_path),+ parse_lock_timeout_sec=30,+ telemetry_svc=telemetry,+ )+ now = 1_700_000_000_000+ await db.execute(+ "INSERT INTO docs (sha256, short_id, size_bytes, file_type, page_count, first_seen_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?, ?)",+ ("sha", "sha", 1, "pdf", 1, now, now),+ )+ await db.execute(+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, first_seen_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",+ (str(tmp_path / "a.pdf"), "a.pdf", "pdf", 1, now, "sha", now, now),+ )+ await db.execute(+ "INSERT INTO parses (sha256, tier, page_range, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",+ ("sha", "flash", "1", "parsing", now, now),+ )+ task = await db.fetchone("SELECT * FROM parses WHERE sha256=?", ("sha",))++ assert await parse_svc.process_doc(task)+ body = await telemetry.preview_body()+ names = {metric["name"] for metric in body["metrics"]}++ assert "parse_task.execute.count" in names+ assert "parse_task.write.count" in names+ assert "parse_task.finished.count" in names+ assert "parse_task.files.count" in names+ assert "parse_task.pages.count" in names+ finished = next(metric for metric in body["metrics"] if metric["name"] == "parse_task.finished.count")+ assert finished["dimensions"] == {"status": "succeeded", "tier": "flash"}++ asyncio.run(_run())+++def test_scan_service_process_scan_records_task_metrics(tmp_path) -> None:+ class _ScanService(ScanService):+ async def _run_scan(self, task):+ counters = _ScanCounters()+ counters.files_seen = 2+ counters.files_refreshed = 1+ counters.files_new = 1+ return counters++ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ store = TelemetryStore(db)+ telemetry = TelemetryService(store)+ await telemetry.initialize()+ scan_svc = _ScanService(+ db,+ ConfigService(db),+ SimpleNamespace(),+ scan_lock_timeout_sec=30,+ telemetry_svc=telemetry,+ )+ now = 1_700_000_000_000+ await db.execute(+ "INSERT INTO scans (path, kind, source, status, started_at, created_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?, ?)",+ (str(tmp_path), "manual", "cli", "running", now, now, now),+ )+ task = await db.fetchone("SELECT * FROM scans LIMIT 1")++ assert await scan_svc.process_scan(task)+ body = await telemetry.preview_body()+ by_name = {metric["name"]: metric for metric in body["metrics"]}++ assert by_name["scan.finished.count"]["dimensions"] == {"status": "succeeded"}+ assert by_name["scan.files.count"]["value"] >= 1++ asyncio.run(_run())+++def test_parse_wait_observation_uses_parse_rows_for_tier_and_pages_bucket(tmp_path) -> None:+ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ store = TelemetryStore(db)+ telemetry = TelemetryService(store)+ await telemetry.initialize()+ server = DoclibServer(SimpleNamespace(db=db, telemetry_svc=telemetry))+ now = 1_700_000_000_000+ await db.execute(+ "INSERT INTO docs (sha256, short_id, size_bytes, file_type, page_count, first_seen_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?, ?)",+ ("sha", "sha", 1, "pdf", 10, now, now),+ )+ await db.execute(+ "INSERT INTO parses (sha256, tier, page_range, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",+ ("sha", "standard", "1~3", "done", now, now),+ )+ row = await db.fetchone("SELECT id FROM parses WHERE sha256=?", ("sha",))++ await server.record_observations(+ TelemetryObservationsRequest(+ observations=[+ TelemetryObservation(+ metric_name="parse.wait",+ parse_ids=[row["id"]],+ duration_ms=1234,+ dimensions={"status": "succeeded"},+ )+ ]+ )+ )+ body = await telemetry.preview_body()+ by_name = {metric["name"]: metric for metric in body["metrics"]}++ assert by_name["parse.wait.count"]["dimensions"] == {+ "caller": "unknown",+ "pages_bucket": "2_5",+ "source": "unknown",+ "status": "succeeded",+ "tier": "standard",+ }+ assert by_name["parse.wait_duration_bucket.count"]["dimensions"]["bucket"] == "1_5s"++ asyncio.run(_run())diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.pyindex 1990af11..81a23dac 100644--- a/tests/unittest/test_parser_api_contract.py+++ b/tests/unittest/test_parser_api_contract.py@@ -10,7 +10,7 @@ from pydantic import ValidationErrorimport mineru.parser.api_client as api_clientimport mineru.parser.api_server as api_server-from mineru.parser.api_client import MinerUApiParser, _pages_from_middle_json, _parse_result_from_job+from mineru.parser.api_client import MinerUApiParser, _pages_from_middle_json, _parse_result_from_job, should_trust_env_for_urlfrom mineru.parser import parse, parse_asyncfrom mineru.parser.base import ParseResultfrom mineru.parser.api_server import (@@ -151,6 +151,44 @@ def test_async_api_client_rejects_unsafe_image_sidecar_paths(monkeypatch: pytest)+def test_api_client_disables_env_proxy_for_local_network_urls() -> None:+ assert should_trust_env_for_url("http://localhost:8000/api") is False+ assert should_trust_env_for_url("http://127.0.0.1:8000/api") is False+ assert should_trust_env_for_url("http://192.168.1.20:8000/api") is False+ assert should_trust_env_for_url("https://staging.mineru.org.cn/api") is True+++def test_api_client_passes_trust_env_from_api_url(monkeypatch: pytest.MonkeyPatch) -> None:+ calls: list[bool] = []++ class _Response:+ status_code = 200+ text = ""++ def json(self) -> dict[str, str]:+ return {"job_id": "job_1", "status": "completed"}++ class _Client:+ def __init__(self, *, timeout: object, trust_env: bool, **_: object) -> None:+ calls.append(trust_env)++ def __enter__(self) -> "_Client":+ return self++ def __exit__(self, *args: object) -> None:+ return None++ def post(self, *args: object, **kwargs: object) -> _Response:+ return _Response()++ monkeypatch.setattr("mineru.parser.api_client.httpx.Client", _Client)++ MinerUApiParser(api_url="http://127.0.0.1:8000/api")._do_parse({"files": []})+ MinerUApiParser(api_url="https://mineru.net/api")._do_parse({"files": []})++ assert calls == [False, True]++def test_api_client_omits_tier_when_unspecified(tmp_path: Path) -> None:pdf = tmp_path / "demo.pdf"pdf.write_bytes(b"%PDF-1.7\n")