diff --git a/docs/diagnostics/2026-10-27-icdb-lost-server-session.md b/docs/diagnostics/2026-10-27-icdb-lost-server-session.md index 53d7125..a9e6276 100644 --- a/docs/diagnostics/2026-10-27-icdb-lost-server-session.md +++ b/docs/diagnostics/2026-10-27-icdb-lost-server-session.md @@ -84,7 +84,7 @@ Session: [2026-10-24 08.22.29-10308] 新增回归包括原错误、共享库身份、内容检查停止队列、多行集成日志、 日志重写及历史错误隔离、编码、证据写入失败和监督器失败摘要。 -最终验证: +诊断修复阶段验证(后续生命周期修复见下方链接): - 全量 Python 测试 **417 项通过**,含 34 项新增回归;仍有基线已有的 一条 pywinauto STA COM 模式提示。 @@ -110,3 +110,7 @@ Project → Repair,并只在原生诊断、Project Repair 备份、目标数 恢复识别仅覆盖已知日志末尾的有限窗口;错误出现在窗口外、相同历史会话 在重写时被原样重报、超出基线窗口的大日志发生重写、以及现场不同日志位置/格式, 仍需结合完整原生日志确认。这些不能确认新旧的情况不会自动提升为本轮修复诊断。 + +用户后续确认事故版本为 r4 或更早。失败强杀根因、正常关闭修复、自动 Repair +范围和 448 项最终回归详见 +[失败生命周期与恢复验证](../releases/2026-10-27-icdb-failure-lifecycle-and-recovery.md)。 diff --git a/docs/releases/2026-10-27-icdb-failure-lifecycle-and-recovery.md b/docs/releases/2026-10-27-icdb-failure-lifecycle-and-recovery.md new file mode 100644 index 0000000..50647d0 --- /dev/null +++ b/docs/releases/2026-10-27-icdb-failure-lifecycle-and-recovery.md @@ -0,0 +1,84 @@ +# r4 失败后 iCDB 断库:根因修复与受控恢复 + +分支:`codex/icdb-lost-session-diagnostics`。用户确认现场事故使用 r4 或更早版本。 + +## 工具侧根因 + +在 r4(`11a2b2e`)中,单项校验失败和监督器超时都会进入强制进程树清理: + +- `DesktopWorker` 设置 `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`,`kill()` 调用 + `TerminateJobObject`,回退路径是 `taskkill /T /F`。 +- `cleanup_verify_processes()` 对目标 PCB 执行同样的强制进程树终止。 +- `prepare_icdb_address()` 会在 TCP 探测失败后移走地址文件。连通性失败 + 不能证明服务器已安全退出;移走地址也不能修复数据库中未完成的会话状态。 + +这条失败收尾路径能连带杀死 PCB 启动的 iCDB 服务器,打断数据库事务或关闭过程, +留下 dirty session。下次由其他机器打开时,iCDB 拒绝继续并要求 Repair, +与用户描述的“未校验成功后才出现失联消息”吻合。现有代码足以确认该缺陷, +但没有 200091-CBB 本次完整进程/数据库日志,不能确定具体中断的是哪次事务。 + +`a11eb3c` 已修掉主要 PCB 强杀路径;继续检查发现内容检查超时仍保留 +`taskkill /T /F`,以及失败文档只保留在隐藏桌面、没有正常关闭尝试。 +这些遗漏在本分支继续修复,不能让用户继续用 r4 的收尾逻辑测试。 + +## 本轮行为 + +- 内容检查超时保留 importer 及原生子进程,使用文件承接输出,防止父进程 + 退出造成管道阻塞/断管;记录 PID、命令和退出状态并停止后续队列。 +- 校验超时/监督器丢失改为协作取消。阻塞中的原生调用先返回,再在操作边界 + 停止后续动作;不终止正在 Save 的助手。 +- 原生调用返回且已确认身份的失败文档,由 x86 助手核对 PRJ 和 PCB 名称后 + 执行 `Close(False)`,释放引用后正常 Quit。若另一个文档仍活动则保留应用; + 慢 Close 同样保留助手,不用强杀代替完成。 +- 写入前和成功前同时核对 Work、PCB 及中心库 + `SymbolLibs/__ReusableBlocksSymb` 的地址所有权。隐藏 Library Manager + 在失败 PCB 正常关闭后也请求正常关闭;所有权未知时继续停止批次。 +- 只读状态桥先关闭标准输入并等待 EOF 清理,避免正常退出也被立即终止。 + +## 自动 Repair 的范围 + +只有本轮明确的 `ICDB_REPAIR_REQUIRED`、完整会话身份、可映射到当前 +Work/PCB PRJ 的数据库,才进入一次原生恢复尝试。TIMEOUT、未释放的 +importer/PCB/Library Manager/助手、外部目标及路径歧义都不会启动 Repair。 + +恢复前通过 Windows 独占文件访问确认目标 `icdb.dat` 没有仍打开的客户端, +完整复制工程全部文件(包括数据库、锁、原备份、日志),逐项校验副本及 +源文件集合。该副本与平日排除数据库的轻量 evidence 备份不同。 + +Repair worker 绑定监督进程和确切私有桌面。它从安装程序资源解析 +`Project → Repair`,核对原生窗口中的完整 PRJ,只接受实际验证过的 +Repair 确认文本。备份期间取消会阻止后续启动;原生 Repair 已经开始后, +超时或监督器丢失不会强制终止它。 + +恢复成功需要本次原生 PID 的诊断完成、数据库关闭、完整 `Project Repair` +ZIP、原生进程正常退出及地址释放。满足后只重试一次完整校验,仍以 +`IsVerifiedReuseBlock READY/raw=1` 为最终成功条件。原错误、原 evidence +和恢复结果保存在 `recovery_attempts`,完整修复备份保留。 + +**共享符号库边界:** 本机同版本 Project Backup 直接打开符号数据库目录时, +明确拒绝并要求 `.prj`。因此对 `SymbolLibs/__ReusableBlocksSymb` 的已损坏 +数据库,本分支会报告 `SHARED_DATABASE_REPAIR_UNSUPPORTED`,不会改修一个 +不相关的 Work 工程,也不会删地址/锁或猜测私有 ABI。正常关闭和共享所有权 +检查用于防止再制造这类问题;已有共享库损坏仍需匹配该库的原生恢复入口。 + +## 实际验证 + +以下写入均针对本轮新副本,未修复或改动现场 200091-CBB 数据: + +- 真实 Windows 无害 importer/子进程试验:超时后均存活,后续队列停止。 +- x86 cscript 测试:核对身份、失败关闭用 `Close(False)`、不保存错误结果、 + 另有活动文档时不 Quit、Save 返回后响应取消。 +- 新 IP101GR 副本主动注入空闲时的同步失败:输出 `FAILURE_CLOSE_OK`、 + `FAILURE_QUIT_OK`,随后确认 PCB 进程退出;失败结果保持 FAIL。 +- 同一隔离库随后正常校验:PASS/GREEN,Save/Close/退出和 + `READY (IsVerifiedReuseBlock, raw=1)` 均确认。 +- 原生 Repair 模块真实执行:完整备份、Repair 确认、本 PID 的 dbcheck/ + 数据库关闭日志、Project Repair ZIP 校验齐全,最终 `REPAIRED`、退出码 0。 + 这验证了原生恢复链,不代表复现并恢复了现场同一个 dirty session。 +- 原样本 21,011 个文件在上述试验前后 SHA-256 内容指纹一致。 +- 最终 Python 全量回归 **448 项通过**(含前次 417 项基线);仍有基线已有的 + 一条 pywinauto STA COM 模式提示。两组 PowerShell 测试、编译和 Git 空白检查通过。 +- 独立复查指出的未释放 importer 进入 Repair、备份期间取消、修复 worker + 父进程丢失、共享 COM 应用退出等边界均已修正,并补充对应回归。 + +本地原始证据位于 `diagnostics/icdb-auto-recovery-20261027`,不随包发布。 diff --git a/src/cbb_refresh_verify/mentor_adapter.py b/src/cbb_refresh_verify/mentor_adapter.py index 77d3418..a195cc8 100644 --- a/src/cbb_refresh_verify/mentor_adapter.py +++ b/src/cbb_refresh_verify/mentor_adapter.py @@ -850,7 +850,9 @@ def execute_job(job, emit): elif not completed and identity_verified: try: from .failed_session import close_failed_document - close_failed_document(job, emit=emit) + failed_close = close_failed_document(job, emit=emit) + if failed_close.get('status') == 'CLOSED' and lm_session is not None: + lm_session.close() except Exception as error: emit(stage='failure_close_unconfirmed', detail=str(error)) cleanup_verify_processes( diff --git a/src/cbb_refresh_verify/native_repair.py b/src/cbb_refresh_verify/native_repair.py index eadef32..69a1834 100644 --- a/src/cbb_refresh_verify/native_repair.py +++ b/src/cbb_refresh_verify/native_repair.py @@ -98,6 +98,9 @@ def backup_project(target, destination): if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns): raise OSError(f'REPAIR_BACKUP_CHANGED: 备份期间源文件变化:{path}') files[str(relative)] = {'size': before.st_size, 'sha256': digest} + if {path.relative_to(source) for path in source.rglob('*')} != { + path.relative_to(source) for path in paths}: + raise OSError('REPAIR_BACKUP_CHANGED: 备份期间工程文件集合变化') record = {'complete': True, 'source': str(source), 'files': files} (destination/'backup-manifest.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8') @@ -147,12 +150,13 @@ def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progr root.mkdir(parents=True, exist_ok=True) job_path = root/'repair-request.json' cancel = root/'cancel-repair.signal' + desktop = 'CbbRepair_'+uuid4().hex[:12] job_path.write_text(json.dumps({'project': str(target.project), 'database': str(target.database), 'root': str(root), 'mentor_bin': str(mentor_bin or ''), 'timeout': timeout_seconds, - 'cancel_signal': str(cancel), 'supervisor_pid': os.getpid()}, ensure_ascii=False), encoding='utf-8') + 'cancel_signal': str(cancel), 'supervisor_pid': os.getpid(), 'desktop': desktop}, + ensure_ascii=False), encoding='utf-8') command = ([sys.executable] if getattr(sys, 'frozen', False) else [sys.executable, '-m', 'cbb_refresh_verify']) + ['--repair-worker', str(job_path)] - desktop = 'CbbRepair_'+uuid4().hex[:12] worker = DesktopWorker(command, desktop) worker.bind_cancellation(cancel) deadline = time.monotonic()+max(1, float(timeout_seconds))+5 diff --git a/src/cbb_refresh_verify/native_repair_ui.py b/src/cbb_refresh_verify/native_repair_ui.py index ccbe1a1..7673a1a 100644 --- a/src/cbb_refresh_verify/native_repair_ui.py +++ b/src/cbb_refresh_verify/native_repair_ui.py @@ -30,6 +30,22 @@ def repair_completed(diagnostic_text, database_text, *, native_backup): and 'iCDBProjectBackupRepair' in database_text and 'IC: Closing project' in database_text) +def _current_desktop_name(): + kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) + user32 = ctypes.WinDLL('user32', use_last_error=True) + kernel32.GetCurrentThreadId.restype = wintypes.DWORD + user32.GetThreadDesktop.argtypes = [wintypes.DWORD] + user32.GetThreadDesktop.restype = wintypes.HANDLE + user32.GetUserObjectInformationW.argtypes = [wintypes.HANDLE, ctypes.c_int, + wintypes.LPVOID, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)] + desktop = user32.GetThreadDesktop(kernel32.GetCurrentThreadId()) + name = ctypes.create_unicode_buffer(512) + required = wintypes.DWORD() + if not user32.GetUserObjectInformationW(desktop, 2, name, ctypes.sizeof(name), ctypes.byref(required)): + raise ctypes.WinError(ctypes.get_last_error()) + return name.value + + def _repair_command(executable): import win32api, win32gui, win32con user32 = ctypes.WinDLL('user32') @@ -124,6 +140,13 @@ def repair_worker_main(job_path): with (root/'repair-events.jsonl').open('a', encoding='utf-8') as stream: stream.write(json.dumps(event, ensure_ascii=False)+'\n') try: + if (not str(job.get('desktop', '')).startswith('CbbRepair_') + or _current_desktop_name() != job['desktop']): + raise ValueError('REPAIR_PRIVATE_DESKTOP_REQUIRED') + if not job.get('supervisor_pid'): + raise ValueError('REPAIR_SUPERVISOR_REQUIRED') + from .desktop_worker import start_supervisor_watchdog + start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job['cancel_signal']) if project.suffix.casefold() != '.prj' or database.resolve() != (project.parent/'database').resolve(): raise ValueError('REPAIR_TARGET_UNCONFIRMED') home = discover_sdd_home(job.get('mentor_bin')) @@ -140,9 +163,6 @@ def repair_worker_main(job_path): raise ValueError('REPAIR_CANCELLED_AFTER_BACKUP') baseline = snapshot_log(project.parent/'Log Files/ProjectBackupLog.txt') started_ns = time.time_ns() - if job.get('supervisor_pid'): - from .desktop_worker import start_supervisor_watchdog - start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job['cancel_signal']) process = subprocess.Popen([str(executable), '-p', str(project)], cwd=str(project.parent)) result['native_pid'] = process.pid emit(stage='native_started', pid=process.pid, project=str(project)) @@ -157,7 +177,7 @@ def repair_worker_main(job_path): if not invoked and main and not dialogs and main['enabled']: if Path(job['cancel_signal']).exists(): raise ValueError('REPAIR_CANCELLED_BEFORE_START') - win32gui.PostMessage(main['hwnd'], 0x0111, command_id, 0) + win32gui.PostMessage(main['hwnd'], win32con.WM_COMMAND, command_id, 0) invoked = True emit(stage='native_repair_requested', command=command_id) if invoked and not confirmed and main: diff --git a/tests/test_failure_lifecycle.py b/tests/test_failure_lifecycle.py index 93696de..a798bb2 100644 --- a/tests/test_failure_lifecycle.py +++ b/tests/test_failure_lifecycle.py @@ -289,3 +289,18 @@ def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path): if handle: win32process.TerminateProcess(handle, 0) handle.Close() + + +def test_idle_failed_native_verify_closes_its_library_manager_owner(tmp_path, monkeypatch): + from types import SimpleNamespace + from test_verify_worker_stability import exercise_worker + job, events, execute = exercise_worker(tmp_path, monkeypatch, integration_error='packaging rejected') + job['native_lm_verify'] = True + closed = [] + monkeypatch.setattr('cbb_refresh_verify.library_manager_verify.launch_library_verify', + lambda *a, **kw: SimpleNamespace(process=SimpleNamespace(pid=11), close=lambda: closed.append(11))) + monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document', + lambda *a, **kw: {'status':'CLOSED'}) + with pytest.raises(RuntimeError, match='packaging rejected'): + execute() + assert closed == [11] diff --git a/tests/test_native_repair.py b/tests/test_native_repair.py index b1ddc44..376a63f 100644 --- a/tests/test_native_repair.py +++ b/tests/test_native_repair.py @@ -140,3 +140,105 @@ def test_automatic_repair_does_not_retry_busy_or_unsupported_target(tmp_path, mo assert len(calls) == 1 assert outcome.safe_to_continue is False assert outcome.recovery_attempts[0]['status'] == 'BLOCKED' + + +def test_timeout_never_enters_automatic_repair(tmp_path, monkeypatch): + from cbb_refresh_verify import verify_runner as runner, native_repair + request, record, target = target_fixture(tmp_path) + evidence = tmp_path/'first/result.json' + evidence.parent.mkdir() + (evidence.parent/'diagnostics').mkdir() + (evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(record)) + monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **kw: + runner.VerifyResult('TIMEOUT', error_category='ICDB_REPAIR_REQUIRED', + safe_to_continue=False, evidence_path=evidence)) + monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: + pytest.fail('A timed-out native owner must not be repaired')) + assert runner.run_verify(request).status == 'TIMEOUT' + + +def test_retained_importer_blocks_repair_even_without_an_open_database_handle(tmp_path, monkeypatch): + from cbb_refresh_verify import native_repair + request, record, target = target_fixture(tmp_path) + evidence = tmp_path/'original' + evidence.mkdir() + (evidence/'content-check-process.json').write_text(json.dumps({'status':'RETAINED','pid':123})) + monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **kw: + pytest.fail('Do not repair between importer transactions')) + outcome = native_repair.attempt_recovery(request, record, evidence) + assert outcome['status'] == 'BLOCKED' + assert 'IMPORTER_RELEASE_UNCONFIRMED' in outcome['detail'] + + +def test_repair_cancellation_during_backup_prevents_native_launch(tmp_path, monkeypatch): + from cbb_refresh_verify import native_repair_ui as ui, native_repair, mentor_adapter + request, record, target = target_fixture(tmp_path) + root = tmp_path/'worker' + root.mkdir() + cancel = root/'cancel.signal' + job = root/'request.json' + job.write_text(json.dumps({'project':str(target.project),'database':str(target.database), + 'root':str(root),'cancel_signal':str(cancel),'timeout':1, + 'supervisor_pid':123,'desktop':'CbbRepair_test'})) + calls = [] + monkeypatch.setattr('cbb_refresh_verify.desktop_worker.start_supervisor_watchdog', + lambda *a, **kw: calls.append('watchdog')) + monkeypatch.setattr(ui, '_current_desktop_name', lambda: 'CbbRepair_test', raising=False) + monkeypatch.setattr(ui, '_repair_command', lambda *_: 32924) + monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: []) + monkeypatch.setattr(mentor_adapter, '_process_details', lambda *_: []) + def backup(*a): + assert calls == ['watchdog'], 'Watch supervisor before the potentially long backup' + cancel.touch() + calls.append('backup') + monkeypatch.setattr(native_repair, 'backup_project', backup) + monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('Repair must not start')) + assert ui.repair_worker_main(job) == 1 + outcome = json.loads((root/'repair-result.json').read_text('utf-8')) + assert 'REPAIR_CANCELLED_AFTER_BACKUP' in outcome['detail'] + + +def test_repair_worker_refuses_the_input_desktop_before_backup(tmp_path, monkeypatch): + from cbb_refresh_verify import native_repair_ui as ui, native_repair + request, record, target = target_fixture(tmp_path) + root = tmp_path/'worker' + root.mkdir() + job = root/'request.json' + job.write_text(json.dumps({'project':str(target.project),'database':str(target.database), + 'root':str(root),'cancel_signal':str(root/'cancel.signal'),'timeout':1, + 'supervisor_pid':123,'desktop':'CbbRepair_test'})) + monkeypatch.setattr(ui, '_current_desktop_name', lambda: 'Default', raising=False) + monkeypatch.setattr(native_repair, 'backup_project', lambda *a: pytest.fail('Input desktop repair forbidden')) + assert ui.repair_worker_main(job) == 1 + assert 'REPAIR_PRIVATE_DESKTOP_REQUIRED' in json.loads((root/'repair-result.json').read_text('utf-8'))['detail'] + + +def test_repair_worker_job_binds_supervisor_and_private_desktop(tmp_path, monkeypatch): + from cbb_refresh_verify.native_repair import run_native_repair + request, record, target = target_fixture(tmp_path) + class Worker: + returncode = 0 + def __init__(self, command, desktop): + job = json.loads(Path(command[-1]).read_text('utf-8')) + assert job['supervisor_pid'] > 0 + assert job['desktop'] == desktop + assert desktop.startswith('CbbRepair_') + (Path(job['root'])/'repair-result.json').write_text('{"status":"BLOCKED"}') + def poll(self): return 0 + def bind_cancellation(self, path): pass + def close(self): pass + monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker) + assert run_native_repair(target, tmp_path/'native')['status'] == 'BLOCKED' + + +def test_backup_detects_a_file_added_during_the_copy(tmp_path, monkeypatch): + from cbb_refresh_verify import native_repair + request, record, target = target_fixture(tmp_path) + original = native_repair.shutil.copy2 + def changed(source, destination): + result = original(source, destination) + (target.project.parent/'new-file.txt').write_bytes(b'concurrent writer') + return result + monkeypatch.setattr(native_repair.shutil, 'copy2', changed) + with pytest.raises(OSError, match='REPAIR_BACKUP_CHANGED'): + native_repair.backup_project(target, tmp_path/'backup') diff --git a/tests/test_safety.py b/tests/test_safety.py index 9647c71..2aa7853 100644 --- a/tests/test_safety.py +++ b/tests/test_safety.py @@ -1,9 +1,10 @@ -"""Production safeguards: no input injection, no desktop switching, no menu driving. +"""Production safeguards: no input injection or uncontrolled menu driving. These asserts encode the operating rules for this tool: the user's mouse, keyboard and desktop are never touched. Dialogs that belong to a process this run started are answered with a posted BM_CLICK, which is a message to that -dialog and not user input. +dialog and not user input. Native Project Backup Repair is restricted to an +owned private desktop/PID, a resolved resource command and an exact PRJ. """ from pathlib import Path @@ -24,6 +25,7 @@ FORBIDDEN_APIS = ( 'AttachThreadInput', 'WM_MOUSEMOVE', 'WM_CONTEXTMENU', + 'WM_COMMAND', 'VK_APPS', 'TVM_SELECTITEM', 'EndMenu', @@ -39,6 +41,11 @@ def test_no_input_injection_or_desktop_switching_in_production_code(): for path in production_sources(): text = path.read_text(encoding='utf-8') for api in FORBIDDEN_APIS: + if path.name == 'native_repair_ui.py' and api == 'WM_COMMAND': + # Only the installed Project Backup Repair menu is allowed: + # resolve its native resource, own the private desktop/PID, + # and confirm the exact PRJ before posting the command. + continue if path.name == 'library_manager_verify.py' and api in {'WM_MOUSEMOVE', 'TVM_SELECTITEM'}: continue if path.name == 'library_manager_verify.py' and api == 'click_input':