# 错误处理

**捕获你能处理的，并为吞掉的异常留下记录。**没有日志、注释或兜底的处理器，看起来和尚未发现的 bug 完全一样。

## 规则

| 义务 | 含义 |
| --- | --- |
| 精确捕获 | 写全操作会抛出的异常：文件 IO 是 `OSError`；JSON 是 `ValueError`；`ContextVar.reset` 对外来 token 抛 `ValueError`，对已用 token 抛 `RuntimeError`。只写一部分会让被吞的失败变成逃逸的失败。 |
| 不吞程序错误 | `AttributeError`、`TypeError`、`NameError` 是缺陷。宽到能隐藏它们的处理器要收窄，或者记录日志。 |
| 说明原因 | 每处保留的吞异常都带有上下文日志，或说明为何可以忽略的注释；不明显时两者都要。 |
| 删除无意义的处理器 | 包裹本身已吞错的操作，或捕获不可能抛出的异常。 |

## 边界

当异常传播会拖垮比失败操作更大的范围时，宽泛的 `except Exception` 是合理的。它仍要记录足以定位会话或操作的日志。

- WebSocket 处理器和 HTTP 路由：否则连接会断开
- 线程和 worker 入口：否则无声死亡
- 回调调用：调用方代码运行在我们的循环内
- 可选子系统（记忆、项目 git、用量计量）：缺失只降级功能
- 下一轮会重新推导的尽力记账

## 日志级别

| 级别 | 何时 |
| --- | --- |
| `error` | 用户会察觉且必须处理：渠道消息重试后仍未送达、MCP 服务未启动、适配器永久停止 |
| `warning` | 丢失了用户可能察觉的东西：写入未落盘、状态陈旧、记录缺失 |
| `info` | 运行中预期的降级路径：网络等待、重试、模型故障转移、重连 |
| `debug` | 可选路径按设计降级：子系统缺失、尽力缓存、兜底生效；开发者追踪 |

使用 `exc_info=True`，并包含会话 id 或等价标识。

**好的处理器**

```
# A lost durable write, made visible
except OSError:
    _log.warning(
        "index.json not saved for session %s", session_id, exc_info=True)

# Narrow where a broad catch hid defects
except (ValueError, RuntimeError):
    # ContextVar.reset raises ValueError for a token minted in another
    # context and RuntimeError for one already spent. Narrowing to only
    # the first lets a cancelled turn's spent token escape and replace
    # the CancelledError.
    _log.debug("context var token already spent or foreign", exc_info=True)

# Optional subsystem, reason stated
except Exception:
    # Memory is optional: an unavailable provider degrades to no memory
    # block, never a failed turn.
    _log.debug("memory system prompt block unavailable", exc_info=True)
```

## 门禁

```
.venv/bin/ruff check .
```

| 规则 | 捕获 |
| --- | --- |
| `E722` | 裸 `except:`，它也会吞掉 `KeyboardInterrupt` 和 `SystemExit` |
| `S110` | `try` / `except` / `pass` |
| `T201` | 库代码中的 `print` |

### 范围

- 覆盖整个 `openprogram/`。`tests/` 和 `scripts/` 静默：测试故意吞异常以断言后续行为；脚本手动运行。
- `per-file-ignores` 的 `*` 跨越 `/`，所以 `openprogram/*.py` 会静默每个模块。新模式要对照嵌套文件检查。
- `BLE001` 关闭：记录日志并降级的边界处理器是正确设计，按“边界”一节评审。
- Ruff 只做这一门禁；格式和导入顺序不管。

## 用 logging，不用 print

每模块一个 logger：`_log = logging.getLogger(__name__)`。不加 `[module]` 前缀；方括号标签只在携带数据时保留，如 `[wechat:<account>]`。参数用 `%s`，不用 f-string。

`print` 只用于下列情况；静默路径之外的每处调用用 `# noqa: T201 - <reason>` 说明属于哪种。

| 用途 | 示例 |
| --- | --- |
| 命令输出 | `openprogram cron-worker --list`、沙箱模拟的 shell 命令、`assets.py` 子命令 |
| stdout 协议 | 另一进程读取的 JSON 行或哨兵 |
| 终端提示或状态 | 二维码登录、OAuth 网址、前台运行告知已上线及如何停止 |

`T201` 静默范围：`openprogram/interfaces/cli/**`、worker 命令（`operations/worker/lifecycle.py`、`runner.py`、`startup_log.py`、`services/**`）、`operations/self_update/**`、`models/providers/recording/**`、`**/probe_thinking.py`。

### 进程日志

库代码不配置 logging。每个入口调用一次 `openprogram/host/process_logging.py` 的 `configure_process_logging()`：根 logger 上一个 stderr 处理器，格式 `%(asctime)s %(levelname)s %(name)s: %(message)s`，`httpx`、`httpcore`、`websockets`、`asyncio`、`mcp` 保持 `WARNING`（`DEBUG` 时全量输出）。

| 进程 | 默认 | 原因 |
| --- | --- | --- |
| Worker（`run_foreground`） | `INFO` | stdout 和 stderr 就是 worker 日志，与 `[worker +12.3s]` 行并列 |
| 独立调度器（`run_forever`） | `INFO` | 终端就是它的日志 |
| 前台 Server（`python -m openprogram.interfaces.server`） | `INFO` | 同上 |
| CLI（`interfaces/cli/application.py` `main`） | `WARNING` | 交互式聊天共用终端 |

- 同一进程内再次调用只调整级别、不加处理器，所以经 CLI 启动的 worker 以 `INFO` 记录。CLI 内的 ACP 服务用 `OPENPROGRAM_ACP_LOG` 做同样的事。
- 他人已配置的根 logger（嵌入宿主、pytest）保留其处理器。
- `OPENPROGRAM_LOG_LEVEL`（级别名，大小写不限）覆盖所有进程；无效值被忽略。

**实现状态**

- 已实现。整个包通过 `E722`、`S110` 和 `T201`。`ruff` 在 `dev` extra 中，配置于 `[tool.ruff]`；CI 对 `openprogram`、`tests`、`scripts` 运行。
- 包裹不可能抛出或自行吞错调用（`emit_safe`、`emit_ws_frame`）的处理器已移除。
- Server 运行日志函数（`interfaces/server/runtime_management.py`、`server_runtime/broadcasts.py`）中同时写 `runtime.log` 的 `print` 保留并已标注。

[统一执行控制](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/control.zh.html)：`CancelledError` 为何是 `BaseException`。[DAG 概览](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/dag/overview.zh.html)：error 作为终态节点状态。
