OpenClaw 升级 2026.11.5 后 Doctor 迁移被拒:SQLite 审批单例冲突的定位与修复

一、问题现象

系统从 OpenClaw 2026.11.4 升级到 2026.11.5(Ubuntu、SQLite、systemd 环境),执行:

/usr/bin/node /data/opt/openclaw-v2026.11.5/dist/index.js doctor --fix

迁移直接中止:

Doctor stopped because a state migration refused to continue.
Failing check state-schema (step-refused):
Failed migrating shared state database schema:
Client credential migration found a noncanonical approval singleton.
OpenClaw 11.5 升级 Doctor 迁移被拒:现象与处理对比
图 1:现象与处理路径对比(客户信息已脱敏)

Gateway 侧表现为服务起不来,但报错点不在启动参数,而在数据库迁移的前置校验。

二、排查定位

迁移程序对 exec_approvals_config 表有单例约束:只接受零条记录,或唯一一条 config_key = current 的记录。本机升级前的实际状态是两条记录:一条 current,一条历史遗留的非标准记录。

只读核对方式(不打印审批 JSON、不暴露 Token):

import sqlite3, hashlib
from pathlib import Path
from contextlib import closing
p = Path.home() / '.openclaw/state/openclaw.sqlite'
with closing(sqlite3.connect(p.resolve().as_uri() + '?mode=ro', uri=True, timeout=5)) as db:
    db.execute('PRAGMA query_only=ON')
    print('SCHEMA_VERSION=', db.execute('PRAGMA user_version').fetchone()[0])
    rows = db.execute('SELECT config_key, raw_json FROM exec_approvals_config').fetchall()
    print('TOTAL_ROWS=', len(rows))
    print('CANONICAL_ROWS=', sum(k == 'current' for k, _ in rows))
    print('NONCANONICAL_ROWS=', sum(k != 'current' for k, _ in rows))
    for key, raw in rows:
        print(key, hashlib.sha256(raw.encode()).hexdigest())

实测结果:Schema 22、总记录 2 条、current 1 条、非标准 1 条,两条 JSON 均可解析;升级前的历史备份里同样是这两条。结论是历史数据状态与新版迁移约束冲突,不能按「数据库损坏」处理。

判断要点:

  1. 表里存的是执行权限与确认策略,可能含 Socket Token,清空整表或直接改 raw_json 都会扩大风险。
  2. 非空 WAL 不能靠删除 WAL/SHM 绕开校验。
  3. 只读审计结果与本文案例不一致时(例如 Schema 已大于 22),立即停止,不要执行修复写入。

三、解决方案

处理顺序固定为:只读审计 → 历史备份核对 → 一致性备份 → 停服务 → 条件化删除一条非标准记录 → 固定版本 Doctor 迁移 → 只读验收。核心脚本在附录,执行前必须满足:

  1. Gateway 确认为 inactive 且 MainPID=0,其他 Agent、定时任务均不写库。
  2. 数据库文件未被占用,WAL 为空。
  3. 已另有完整恢复点(配置、各 Agent、插件、工作区),SQLite 快照只是额外保护。
  4. 人工输入非标准记录的完整 SHA-256 与确认短语后才提交删除事务,脚本自身不会启动 Doctor。

修复事务只做一件事:按 config_key + raw_json 精确匹配删除那一条非标准记录,commit 前复核表内容必须只剩 current 这一条。

四、验证结果

用固定版本程序路径单独执行迁移:

/usr/bin/node /data/opt/openclaw-v2026.11.5/dist/index.js doctor --fix

结果:DOCTOR_EXIT=0;共享库 Schema 22→36;两个 Agent 库 27→38;客户端凭据库建立为 Schema 1;四库 quick_check 均为 ok;审批单例校验 PASS;Gateway 恢复 active/running,健康检查通过。

迁移完成后在独立 SSH 会话做只读复核,只查四件事:四个库的 Schema 版本、quick_check、审批是否只剩 current、服务状态与软链接指向。

需要注意:readlink 只能说明软链接当前指向哪个目录,不等同于运行中的 Gateway 进程实际加载的版本;如果升级后又切换过软链接,应另行核对服务入口与进程启动时间。

五、总结

这次故障的根因不是数据库损坏,而是旧审批数据与新版本迁移约束不兼容。四条纪律值得写进任何一次状态迁移:

  1. 不清空审批表,不删 WAL/SHM 绕过检查。
  2. 不把 SQLite 快照当成完整恢复点。
  3. 修复脚本必须条件化,且只允许删除一条、可复核、可回滚。
  4. 迁移成功后的修复脚本不得重跑;Schema 已达标的库应被脚本直接拒绝。

处置路径可以复用到同类 SQLite 状态迁移:先证明「数据没坏」,再证明「约束不满足」,最后用最小写入把它变成满足约束的状态。

附录:条件化单条修复脚本(节选,执行前须按本机路径审计)

# 仅适用于:Schema 22、恰好一条 current 加一条非标准记录
# 前置:完整恢复点已就绪;Gateway 已停;WAL 为空
bash <<'OPENCLAW_REPAIR_SCRIPT'
python3 - <<'PY'
import hashlib, json, os, shutil, sqlite3, subprocess
from contextlib import closing
from datetime import datetime, timezone
from pathlib import Path

os.umask(0o077)
root = Path.home() / ".openclaw"
backup_root = Path(os.environ.get("OPENCLAW_BACKUP_ROOT", "/data/openclaw/backups")).resolve()
dbs = {
    "shared.sqlite": root / "state/openclaw.sqlite",
    "agent-main.sqlite": root / "agents/main/agent/openclaw-agent.sqlite",
    "agent-secondary.sqlite": root / "agents/openclaw/agent/openclaw-agent.sqlite",
}
main_db = dbs["shared.sqlite"]

def stop(reason):
    raise SystemExit("STOP: " + reason)

def gateway_stopped():
    r = subprocess.run(["systemctl", "--user", "show", "openclaw-gateway.service",
                        "-p", "ActiveState", "-p", "MainPID"],
                       capture_output=True, text=True, check=True)
    status = dict(l.split("=", 1) for l in r.stdout.splitlines() if "=" in l)
    if status.get("ActiveState") != "inactive" or status.get("MainPID") != "0":
        stop("Gateway not confirmed inactive with PID 0")

def all_files_idle():
    for db in dbs.values():
        for path in (db, Path(str(db) + "-wal"), Path(str(db) + "-shm")):
            if not path.exists():
                continue
            if subprocess.run(["fuser", "-s", str(path)]).returncode != 1:
                stop("database busy or occupancy unknown: " + str(path))
            if path.name.endswith("-wal") and path.stat().st_size != 0:
                stop("nonempty WAL needs a separate recovery assessment: " + str(path))

def ro(path):
    return sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True, timeout=5)

def rows_of(conn):
    return conn.execute("SELECT config_key,raw_json FROM exec_approvals_config ORDER BY config_key").fetchall()

def digest(v):
    return hashlib.sha256(v.encode("utf-8")).hexdigest()

gateway_stopped()
all_files_idle()

with closing(ro(main_db)) as conn:
    conn.execute("PRAGMA query_only=ON")
    schema = conn.execute("PRAGMA user_version").fetchone()[0]
    rows = rows_of(conn)
    quick = conn.execute("PRAGMA quick_check").fetchone()[0]
if schema != 22 or quick != "ok":
    stop("schema/integrity precondition differs from this case")
if len(rows) != 2 or sum(k == "current" for k, _ in rows) != 1:
    stop("expected exactly one current and one noncanonical row")
current = next(r for r in rows if r[0] == "current")
legacy = next(r for r in rows if r[0] != "current")
for _, raw in rows:
    obj = json.loads(raw)
    if not isinstance(obj, dict) or obj.get("version") != 1:
        stop("unexpected approval JSON structure")

source = sum(p.stat().st_size for p in dbs.values())
if shutil.disk_usage(backup_root).free < int(source * 2.2) + 2 * 1024**3:
    stop("insufficient backup space")
archive = backup_root / ("approval-repair-" + datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ"))
archive.mkdir(mode=0o700)
for name, path in dbs.items():
    dest = archive / name
    with closing(ro(path)) as src, closing(sqlite3.connect(str(dest))) as dst:
        src.backup(dst)
        if dst.execute("PRAGMA quick_check").fetchone()[0] != "ok":
            stop("snapshot failed integrity: " + name)
    dest.chmod(0o600)
with closing(ro(archive / "shared.sqlite")) as saved:
    if rows_of(saved) != rows:
        stop("backup approval records differ")
print("BACKUP_VERIFIED=PASS")

with open("/dev/tty") as tty_in, open("/dev/tty", "w") as tty_out:
    tty_out.write("Type NONCANONICAL_POLICY_SHA256 to approve: ")
    tty_out.flush()
    if tty_in.readline().strip() != digest(legacy[1]):
        stop("operator fingerprint confirmation failed")
    tty_out.write("Type DELETE ONE NONCANONICAL ROW to commit: ")
    tty_out.flush()
    if tty_in.readline().strip() != "DELETE ONE NONCANONICAL ROW":
        stop("operator approval not provided")

gateway_stopped()
all_files_idle()
with closing(sqlite3.connect(str(main_db), timeout=5, isolation_level=None)) as conn:
    conn.execute("PRAGMA foreign_keys=ON")
    try:
        conn.execute("BEGIN IMMEDIATE")
        if rows_of(conn) != rows:
            raise RuntimeError("approval table changed")
        cur = conn.execute("DELETE FROM exec_approvals_config WHERE config_key=? AND raw_json=?", legacy)
        if cur.rowcount != 1 or rows_of(conn) != [current]:
            raise RuntimeError("exact one-row change failed")
        if conn.execute("PRAGMA quick_check").fetchone()[0] != "ok":
            raise RuntimeError("integrity check failed")
        conn.execute("COMMIT")
    except BaseException:
        if conn.in_transaction:
            conn.execute("ROLLBACK")
        raise
print("SINGLETON_REPAIR=PASS")
PY
OPENCLAW_REPAIR_SCRIPT