diff --git a/docs/diagnostics/2026-11-04-issue4-followup.md b/docs/diagnostics/2026-11-04-issue4-followup.md new file mode 100644 index 0000000..fc039e8 --- /dev/null +++ b/docs/diagnostics/2026-11-04-issue4-followup.md @@ -0,0 +1,45 @@ +# 工单 #4 与独立操作复核 + +复核基准:最新工单 [#4](https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/issues/4)(更新于 2026-11-04 15:20),当前代码起点 `2587d33`,用户随后要求校验与 ICDB 维护独立执行。原工单基准为 `29959e2`,下表按当前源码重新核对,不能照搬原报告的测试数或认定全部已修复。 + +## 本次用户失败的实际链路 + +最新测试程序的日志位于 `dist/issue2-tabs-release-candidate/CbbRefreshVerify-Background/data/`。北京时间 17:41:55 开始维护 `1GPHY_8212`,17:42:24 进入原生检查,17:43:17 启动 Project Backup,17:43:50 报 `TIMEOUT_UNRELEASED`。本轮没有发出 Repair,8 个后续条目被跳过。17:44:54 再运行另一工程,遗留 PID 60000 被全局进程检查拦截。 + +只读打开对应私有桌面后确认:原生主窗口及 RichEdit Output 控件均存在,但主窗口和 Output 连 WM_NULL 都返回 1460(超时)。不是已经取得 ICDB 损坏结论后修复失败,而是原生检查本身无响应,且本应用没有提供足够的阶段证据。没有向该原库发出新的 Repair、恢复、删除地址文件或强制结束操作。 + +原有逻辑还把“存在历史检查点”直接解释为整个库只能维护,普通校验默认自动 Repair,并把地址记录存在直接解释为会话未释放。这些产品耦合与用户最新要求冲突。 + +## 12 项仍需修改或验收 + +| 工单项 | 当前结论 | 后续工作及验收 | +| --- | --- | --- | +| K2-1 状态桥前置检查 | 仍缺少批次级能力诊断;在原生刷新后才检查权威 READY | 批次开始只诊断一次并明确说明状态不可读取;不能因此封锁 ICDB 和库管理。不能把原生调用完成当作 READY。 | +| K2-1b x86 运行库部署 | 发布候选中的桥为 x86,导入 `mfc140.dll/MSVCP140.dll/VCRUNTIME140.dll`,未随包提供 x86 MFC | 选择静态链接或正式部署 x86 运行库;干净 Windows 实机验证。x64 Python/Qt 的同名 DLL 不能替代。 | +| K2-2 未知弹窗分级 | 输入法误报已有过滤;真正未知交互弹窗仍使当前项失败并停批 | 区分无交互辅助窗口与实际模态提示;后者记录具体原因,正常释放后才继续独立项,不能盲点未知确认按钮。 | +| K2-3 取消与超时 | 协作式取消已存在;看门狗和 `_stop_worker` 仍可能返回时客户端活着 | 检查当前 automation client/保存客户端是否实际退出,防止迟到 Save/Close;不得以删除历史记录代替停止仍在写入的任务。 | +| K2-6 ICDB 自动维护 | 隔离副本曾成功执行 Repair;本次原库原生检查无响应,不能验收 | 当前修复:独立维护、独立校验、缩小检查范围、记录原生等待阶段。仍需一致副本上的真实按钮验收;原生窗口挂起成因待查。 | +| K2-4 跨机共享库并发 | sidecar 排他句柄只协调遵守协议的工具,Mentor 不参与 | 明确共享库操作协议,基于实际原生文件占用处理冲突;两台机器同时写同一工程的验证尚未完成。 | +| K2-5 地址记录及全局 PCB 拦截 | 地址文件和历史记录的普通校验硬拦截在本次拆除;“任意 PCB 已开即拒绝”仍存在 | 改为按工程身份判断占用;独立 CBB 不应相互禁用;跨会话 COM 绑定需实际验证后调整。 | +| K2-7 Windows 10 | 当前没有 Win10 实机完成证据 | 在 Win10 + EE7.9.5 验证私有桌面、启动、保存、释放及 READY;不能以 Win11 回归替代。 | +| K2-8 内容文本与 PRJ 编码 | 探针确认成功文本含 `0 errors` 仍返回 FAIL;preflight 仍按 UTF-8 读取 | 复用已有工程编码读取器,区分零错误计数与真实错误;补 UTF-16、ACP 和真正失败样本。 | +| K2-9 CentralLibrary 改写与说明 | 写入前已有原始 `pcb.prj` 证据副本和原子替换;旧“没有直接改写”说明不准确 | 核对异常回退与说明,按用户要求提示手动备份,不能重新加上自动整库备份。 | +| K3-1 初次扫描规模 | 状态指纹与逐项 preflight 仍有全库开销;本次只缩小了维护检查范围 | 首屏增量读取、扫描进度和取消;381/3000 项及网络盘测量仍需做。 | +| K3-2 队列恢复 | 已有状态/管理检查点,但没有完整校验队列的确认续跑 | 保存目标、已完成项和具体结果,重启后由用户决定继续;管理写操作不得自动重放。 | + +共 12 项:5 项 P0、7 项原工单 P1/规模化条目。它们不等于 12 个已复现的代码错误:包含明确缺陷、部分修复、部署风险及缺少实机验收。优先处理操作解耦、原生检查无响应、桥部署、取消后仍存活的客户端;其余独立提交,不混在一次维护修复中。 + +## 本次实现与验证范围 + +普通校验默认不调用 Repair;历史检查点不再切换清单读取方式或禁用普通校验。合作式库锁跟随实际客户端释放,不为普通校验创建新的永久诊断阻止记录;已有历史记录保留。已退出的只读原生检查不会因为旧地址记录而锁住管理入口。实际仍存活或尚未确认退出的客户端继续保有执行锁;监督工作进程已经退出、只剩已记录的原生 PID 时,重试会检查这些 PID 是否实际退出,校验和维护均可直接重试,不要求先运行另一个功能。工作进程仍在运行时不采用这一简化判定。 + +维护成功报告 `REPAIRED / UNKNOWN` 和“待单独校验”,不自动重开 PCB、不执行反标注、不标为 READY。历史备份恢复仍需核对版本。维护预检查只扫描当前 Work、相关共享符号数据库及中心库定义,并保持链接、文件集合变化和独占句柄检查。扫描真实原库的 5,218 项用时 14.109 秒(只读,未启动原生工具);原用户流程的两层预检查合计约 76 秒,不能把这两个口径直接当作完整维护耗时对比。 + +验证证据在 `diagnostics/independent-operations-20261104/`(原始现场记录不提交): + +- 操作拆分后的相关回归 509 项通过;审查发现并补正真实客户端仍在写入时的执行锁保留,以及直接重试维护的入口问题。 +- 执行锁、维护、占用、校验、导出保护和恢复等相关回归 **214 passed**,退出码 0;最后“无需修复”展示与独立入口回归 **37 passed**,退出码 0。不是对最终源码重新跑完整 Python 套件的声明。 +- 独立静态审查的必要问题已修正。编译及差异检查通过。 +- 冻结包核对 10 个关键模块与当前源码一致,并运行无原生写入的启动/正常退出冒烟。构建元数据明确保留 `native_acceptance=false`、`release_ready=false`。 + +本轮没有重启现场挂起的原生进程、强制结束该进程、在原库执行新的自动修复,或将单元测试当成 ICDB 实机验收。原生窗口长时间无响应的具体内部原因仍未查明;此文档不能作为原生自动修复已验收的证明。 diff --git a/src/cbb_refresh_verify/icdb_maintenance.py b/src/cbb_refresh_verify/icdb_maintenance.py index b701b6c..01802d8 100644 --- a/src/cbb_refresh_verify/icdb_maintenance.py +++ b/src/cbb_refresh_verify/icdb_maintenance.py @@ -15,12 +15,15 @@ def maintenance_counts(results): version_choice = sum(attempt.get('status') == 'PCB_VERSION_CHOICE_REQUIRED' and attempt.get('native_status') == 'REPAIRED' and attempt.get('validation_passed') is False for attempt in attempts) + pending = sum(attempt.get('status') == 'REPAIRED_UNVERIFIED' + and attempt.get('native_status') == 'REPAIRED' for attempt in attempts) return {'total': len(results), 'passed': sum(r.status == 'PASS' for r in results), 'checked_without_repair': sum(r.status == 'CHECKED' for r in results), 'skipped': sum(r.status == 'SKIPPED' for r in results), 'repaired': repaired, 'review_required': review, 'version_choice_required': version_choice, - 'repair_unconfirmed': len(attempts)-repaired-review-version_choice} + 'repaired_unverified': pending, + 'repair_unconfirmed': len(attempts)-repaired-review-version_choice-pending} def write_maintenance_report(requests, results, batch_report, skipped_names): diff --git a/src/cbb_refresh_verify/library_lock.py b/src/cbb_refresh_verify/library_lock.py index 98ec832..523c748 100644 --- a/src/cbb_refresh_verify/library_lock.py +++ b/src/cbb_refresh_verify/library_lock.py @@ -78,13 +78,14 @@ def _persist_blocker(library, status='OWNER_RELEASE_UNCONFIRMED', *, lease_id): class LibraryLock: - def __init__(self, library, *, safe_to_release=None): + def __init__(self, library, *, safe_to_release=None, checkpoint=True): library = Path(library).resolve() self.library = library self.path = library.with_name('.' + library.stem + '.cbb-upload.lock') self.key = _key(self.path) self.entered = False self.safe_to_release = safe_to_release + self.checkpoint = checkpoint self.maintenance_guard = None self.maintenance_mutex = None @@ -96,6 +97,17 @@ class LibraryLock: return lease def __enter__(self): + with _guard: + owner = _owners.get(self.key) + if owner and owner['retained'] and owner['depth'] == 0 and owner.get('release_probe'): + try: + released = owner['release_probe']() is True + except Exception: + released = False + if released: + owner['handle'].Close() + del _owners[self.key] + owner = None if self.maintenance_guard is not None: return _enter_maintenance(self) import win32con, win32file @@ -106,7 +118,7 @@ class LibraryLock: raise LibraryBusy(f'中心库被其他任务占用:{self.path}') owner['depth'] += 1 else: - if has_blocker(self.library): + if self.checkpoint and has_blocker(self.library): raise LibraryBusy(f'中心库存在未解除的会话阻止记录,请先执行释放检查:{blocker_path(self.library)}') try: lease_id = uuid4().hex @@ -127,12 +139,15 @@ class LibraryLock: # it explicitly before complete-copy metadata is captured. import pywintypes win32file.SetFileTime(handle, None, None, pywintypes.Time(datetime.now())) - _persist_blocker(self.library, 'OPERATION_IN_PROGRESS', lease_id=lease_id) + if self.checkpoint: + _persist_blocker(self.library, 'OPERATION_IN_PROGRESS', lease_id=lease_id) except Exception: handle.Close() raise _owners[self.key] = {'thread': threading.get_ident(), 'depth': 1, - 'handle': handle, 'retained': False, 'lease_id': lease_id} + 'handle': handle, 'retained': False, 'lease_id': lease_id, + 'checkpoint': self.checkpoint, + 'release_probe': self.safe_to_release if not self.checkpoint else None} self.entered = True return self @@ -162,6 +177,20 @@ class LibraryLock: if not self.entered: return owner = _owners[self.key] + if not owner.get('checkpoint', True): + if self.safe_to_release is not None: + try: + released = self.safe_to_release() is True + except Exception: + released = False + if not released: + owner['retained'] = True + owner['depth'] -= 1 + self.entered = False + if owner['depth'] == 0 and not owner['retained']: + owner['handle'].Close() + del _owners[self.key] + return checkpoint = checkpoint_record(blocker_path(self.library)) if checkpoint is not None and 'export_analysis' in checkpoint: owner['retained'] = True @@ -237,7 +266,7 @@ def _enter_maintenance(lease): raise LibraryBusy('本进程库锁仍在使用或检查点身份不符') handle = existing['handle'] else: - if record is not None and _supervisor_alive(record['pid']): + if record is not None and record['pid'] != os.getpid() and _supervisor_alive(record['pid']): raise LibraryBusy('原监督进程仍存在,不能接续其库锁') handle = win32file.CreateFile(str(lease.path), win32con.GENERIC_READ | win32con.GENERIC_WRITE, 0, None, win32con.OPEN_ALWAYS, win32con.FILE_ATTRIBUTE_NORMAL, None) diff --git a/src/cbb_refresh_verify/maintenance_entry.py b/src/cbb_refresh_verify/maintenance_entry.py index 09b7f5e..3c622b0 100644 --- a/src/cbb_refresh_verify/maintenance_entry.py +++ b/src/cbb_refresh_verify/maintenance_entry.py @@ -44,12 +44,30 @@ def address_snapshot(paths): for path in paths} +def maintenance_entries(request, *, check=None): + from .verify_runner import preflight + from .scoped_manifest import scan_tree + project, _ = preflight(request) + root = Path(request.lmc_file).parent + entries = scan_tree(project.parent, check=check) + shared = root/'SymbolLibs/__ReusableBlocksSymb' + if shared.exists(): + entries.update(scan_tree(shared, check=check)) + for library in root.glob('*.lmc'): + info = library.lstat() + if (info.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT + or not stat.S_ISREG(info.st_mode)): + raise ValueError(f'不支持通过文件链接维护:{library}') + entries[library] = info + return entries + + def _scoped_addresses(request, *, check=None, entries=None): from .scoped_manifest import scan_tree root = Path(request.lmc_file).parent addresses = [] if entries is None: - entries = scan_tree(root, check=check) + entries = maintenance_entries(request, check=check) if check is not None: check() for path in entries: if path.name.casefold() != 'saddress.adr': @@ -93,7 +111,8 @@ def select_maintenance_target(request, *, check=None, entries=None): if request.maintenance is not True: raise ValueError('MAINTENANCE_INTENT_REQUIRED') project, pcb = preflight(request) - scan_tree(project.parent, check=check) + if entries is None: + entries = maintenance_entries(request, check=check) candidates = [] for candidate in maintenance_project_files(project, pcb): if not candidate.is_file(): @@ -144,7 +163,7 @@ def maintenance_target_guard(request, expected=None, *, stop=None): library_root = Path(request.lmc_file).parent # Share one complete snapshot for target/address selection and file locks. # Refresh it again while the handles are held; do not reuse across guards. - entries = scan_tree(library_root, check=check) + entries = maintenance_entries(request, check=check) target, project, pcb, addresses = select_maintenance_target(request, check=check, entries=entries) baseline = address_snapshot(addresses) context = {'library': str(Path(request.lmc_file).resolve()), 'block': request.block_name, @@ -167,7 +186,7 @@ def maintenance_target_guard(request, expected=None, *, stop=None): win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None) stack.callback(handle.Close) assert_native_idle() - current = scan_tree(library_root, check=check) + current = maintenance_entries(request, check=check) if native_files(current) != files: raise ValueError('MAINTENANCE_SOURCE_CHANGED: 检查期间库文件集合发生变化') current_addresses = _scoped_addresses(request, check=check, entries=current) @@ -190,10 +209,9 @@ def maintenance_needed(request): return bool(unreleased_addresses(request.lmc_file, project, pcb)) -def run_existing_address_maintenance(request, *, verify, progress=None, stop=None): +def run_existing_address_maintenance(request, *, progress=None, stop=None): from .library_lock import LibraryLock - from .native_repair import (run_native_repair, native_success_confirmed, repair_release_state, - _native_identity_and_exit_confirmed) + from .native_repair import run_native_repair, native_success_confirmed, repair_release_state from .verify_runner import VerifyResult root = Path(request.evidence_dir).resolve()/('maintenance-' + uuid4().hex[:12]) library_root = Path(request.lmc_file).resolve().parent @@ -222,23 +240,27 @@ def run_existing_address_maintenance(request, *, verify, progress=None, stop=Non lease = LibraryLock.for_maintenance(request.lmc_file, root/'takeover', lambda: maintenance_target_guard(request, stop=stop), safe_to_release=lambda: owner_safe) with lease: + owner_safe = True # Admission completed; no native client exists yet. checked = lease.maintenance_proof target, context = checked['target'], checked['context'] record['maintenance_context'] = context if stop is not None and stop.is_set(): raise ValueError('MAINTENANCE_CANCELLED: 已取消,未启动原生检查') emit('icdb_ownership_check', detail='调用原生 Project Backup 检查占用及恢复要求,不执行 Repair') + owner_safe = False inspection = run_native_repair(target, root/'native-inspection', mentor_bin=request.mentor_bin, timeout_seconds=min(30, request.timeout_seconds), progress=native_event, maintenance_context=context, inspection_only=True, stop=stop) record['native_inspection'] = inspection + owner_safe = (inspection.get('release', {}).get('native_exited') is True + or inspection.get('native_pid') is None and inspection.get('worker_pid') is None) from .native_occupancy import confirmed_inspection if not confirmed_inspection(target, inspection): - return save(VerifyResult('BLOCKED', safe_to_continue=False, + return save(VerifyResult('BLOCKED', safe_to_continue=owner_safe, error_category='ICDB_INSPECTION_UNCONFIRMED', stderr='原生占用检查未确认或已取消,未请求 Repair。' + str(inspection.get('detail', inspection.get('status'))))) if inspection['status'] == 'IN_USE': - return save(VerifyResult('BLOCKED', safe_to_continue=False, + return save(VerifyResult('BLOCKED', safe_to_continue=owner_safe, error_category='ICDB_DATABASE_IN_USE', stderr='原生工具确认工程正在使用,未请求 Repair。')) # Native loading may retire an old address itself. Permit only # disappearance, never a new/changed advertisement or project. @@ -251,10 +273,8 @@ def run_existing_address_maintenance(request, *, verify, progress=None, stop=Non context = updated record['post_inspection_context'] = context if not inspection['repair_required']: - owner_safe = not bool(context['addresses']) return save(VerifyResult('CHECKED', safe_to_continue=owner_safe, - stdout='原生确认未占用,未报告明确修复要求;未执行 Repair,不能算修复成功。', - stderr='' if owner_safe else '历史地址记录仍存在;检查未替代恢复或会话释放。')) + stdout='检查完成,无需修复。')) if stop is not None and stop.is_set(): raise ValueError('MAINTENANCE_CANCELLED: 已取消,未开始 Repair') emit('icdb_diagnosis_confirmed', detail='本轮原生检查明确要求修复当前数据库,且确认未占用') @@ -267,6 +287,7 @@ def run_existing_address_maintenance(request, *, verify, progress=None, stop=Non # Repeat immediately before dispatch; the worker repeats before # launching the native process as well. with maintenance_target_guard(request, context, stop=stop): pass + owner_safe = False recovery = run_native_repair(target, native_root, mentor_bin=request.mentor_bin, timeout_seconds=max(60, request.timeout_seconds), progress=native_event, maintenance_context=context, stop=stop) @@ -275,48 +296,15 @@ def run_existing_address_maintenance(request, *, verify, progress=None, stop=Non recovery['release'] = repair_release_state(request, target, recovery) safe = recovery['release'].get('safe_to_continue') is True confirmed = recovery.get('status') == 'REPAIRED' and safe and native_success_confirmed(target, recovery) - evidence = recovery.get('evidence') - completed_failure = (recovery.get('status') in ('MISSING_HEALTHY_BACKUP', 'NATIVE_REPAIR_FAILED') - and isinstance(evidence, dict) and evidence.get('failure_complete') is True - and _native_identity_and_exit_confirmed(target, recovery)) - # Physical release is necessary, but does not approve historical - # restoration/unknown/busy outcomes or an incomplete failure report. - owner_safe = safe and (confirmed or completed_failure) - if confirmed and stop is not None and stop.is_set(): - recovery['status'] = 'REPAIR_VALIDATION_CANCELLED' - return save(VerifyResult('FAIL', safe_to_continue=owner_safe, - stderr='原生修复已结束,但用户取消了后续校验;不报告修复成功。', recovery_attempts=(recovery,))) + # Release follows actual clients, not the repair/content verdict. + owner_safe = safe or (recovery['release'].get('native_exited') is True + and recovery['release'].get('database_exclusive') is True + and recovery['release'].get('remaining_pids') == []) if confirmed: - emit('repair_verify', detail='原生修复及释放已确认,重新打开同一工程校验') - from .post_repair_consent import PostRepairProof - owner_safe = False - proof = PostRepairProof.create(request, target, recovery) - verified = verify(replace(request, maintenance=False, auto_repair=False, - diagnostic_only=False, post_repair_proof=proof, - interactive_input=False, native_lm_verify=False)) - owner_safe = verified.safe_to_continue - good = verified.status == 'PASS' and verified.library_flag == 'GREEN' and owner_safe - recovery.update(status='REPAIRED' if good else 'REPAIR_VALIDATION_FAILED', - validation_passed=good, validation_evidence=str(verified.evidence_path or '')) - if good and verified.evidence_path: - restored = Path(verified.evidence_path).parent/'pcb-version-restoration.json' - if restored.exists(): - version = json.loads(restored.read_text(encoding='utf-8')) - if (version.get('confirm_sent') is not True or version.get('historical_restore') is not True - or Path(version['project']).resolve() != checked['project'].resolve() - or version.get('choice') not in ('last_user_saved', 'autosave')): - raise ValueError('PCB_VERSION_RESTORATION_EVIDENCE_INVALID') - recovery.update(status='RESTORED_REVIEW_REQUIRED', pcb_version=version) - verified = replace(verified, stdout=verified.stdout + - f'\n已按用户选择恢复 PCB({version["date"]})并通过校验;版本待核对。') - if verified.error_category == 'PCB_VERSION_CHOICE_REQUIRED': - owner_safe = False - good = False - recovery.update(status='PCB_VERSION_CHOICE_REQUIRED', validation_passed=False) - verified = replace(verified, safe_to_continue=False, - stderr='ICDB原生修复已完成;PCB需选择恢复版本,尚未校验通过。\n' + verified.stderr) - return save(replace(verified, status='PASS' if good else 'FAIL', - recovery_attempts=(recovery,))) + emit('native_repair_complete', detail='原生 ICDB 修复完成,CBB 待单独校验') + recovery['status'] = 'REPAIRED_UNVERIFIED' + return save(VerifyResult('REPAIRED', safe_to_continue=owner_safe, + stdout='原生 ICDB 修复完成,CBB 待单独校验。', recovery_attempts=(recovery,))) if recovery.get('status') == 'REPAIRED': recovery['status'] = 'UNCONFIRMED'; owner_safe = False return save(VerifyResult('FAIL', stderr=f'{recovery["status"]}: {recovery.get("detail", "原生维护未确认修复")}', diff --git a/src/cbb_refresh_verify/mentor_adapter.py b/src/cbb_refresh_verify/mentor_adapter.py index 7eddcb4..128ba1e 100644 --- a/src/cbb_refresh_verify/mentor_adapter.py +++ b/src/cbb_refresh_verify/mentor_adapter.py @@ -630,13 +630,7 @@ def execute_job(job, emit): emit(stage='mapped_drive_context', **mapping) emit(stage='backup_skipped', reason='manual_backup_policy', source=str(block_root), detail='应用不自动备份;请在操作前手动备份。') - from .icdb_ownership import database_directories, unreleased_addresses - for database in database_directories(job['lmc_file'], job['project'], job['pcb']): - icdb_address = prepare_icdb_address(database, root, emit=emit) - if icdb_address.get('status') != 'ABSENT': - raise RuntimeError( - 'ICDB_SESSION_UNCONFIRMED: 数据库存在服务器地址记录,无法确认独占使用;' - '已保留地址文件,请先检查原 PCB/iCDB 会话。' + str(icdb_address)) + from .icdb_ownership import unreleased_addresses from .verify_diagnostics import collect_preflight_diagnostics, collect_native_failure_logs diagnostics = collect_preflight_diagnostics(job['pcb'], root) emit(stage='preflight_diagnostics', non_blocking=True, @@ -862,7 +856,7 @@ def execute_job(job, emit): raise RuntimeError(f'PCB_RELEASE_UNCONFIRMED: 未确认 PCB 退出: {released}') addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb']) if addresses: - raise RuntimeError(f'ICDB_RELEASE_UNCONFIRMED: PCB 已退出但数据库地址记录仍存在;保留文件并停止批次: {addresses}') + emit(stage='icdb_address_remaining', addresses=addresses, non_blocking=True) cert_pcb = block_root/'Cert'/Path(job['pcb']).relative_to(block_root/'Work') cert_evidence = collect_cert_evidence(block_root, cert_project, cert_pcb) emit(stage='cert_diagnostics', **cert_evidence) diff --git a/src/cbb_refresh_verify/native_repair_ui.py b/src/cbb_refresh_verify/native_repair_ui.py index 77f972f..4bc0ec5 100644 --- a/src/cbb_refresh_verify/native_repair_ui.py +++ b/src/cbb_refresh_verify/native_repair_ui.py @@ -194,6 +194,7 @@ def _inspect_project(job, process, emit): 'repair_required': False, 'output': ''} deadline = time.monotonic() + max(1, float(job['timeout'])) closing = False + last_state = None # Reserve a short cooperative-close grace after the inspection deadline. while process.poll() is None and time.monotonic() < deadline + 3: windows = [w for w in _windows(process.pid) if not ( @@ -207,6 +208,13 @@ def _inspect_project(job, process, emit): result.update(status='UNCONFIRMED', unknown_dialogs=unknown) break current = _native_output(windows) + state = {'main_found': main is not None, 'output_readable': current is not None, + 'windows': windows} + if state != last_state: + (Path(job['root'])/'inspection-state.json').write_text( + json.dumps(state, ensure_ascii=False, indent=2), encoding='utf-8') + emit(stage='native_occupancy_wait', main_found=state['main_found'], output_readable=state['output_readable']) + last_state = state if current is not None: result['output'] = current cancelled = Path(job['cancel_signal']).exists() @@ -227,6 +235,8 @@ def _inspect_project(job, process, emit): 'safe_to_continue': exited and result['status'] == 'NOT_IN_USE'} if not exited: result.update(status='TIMEOUT_UNRELEASED', repair_required=False) + result['detail'] = ('原生检查窗口未返回 Output,未执行 Repair。' + if not result['output'] else '原生检查工具未退出,未执行 Repair。') return result diff --git a/src/cbb_refresh_verify/ui/main_window.py b/src/cbb_refresh_verify/ui/main_window.py index b151c1e..b0e13df 100644 --- a/src/cbb_refresh_verify/ui/main_window.py +++ b/src/cbb_refresh_verify/ui/main_window.py @@ -121,7 +121,7 @@ class MainWindow(QWidget): self.advanced_panel.setVisible(False) self.advanced_toggle.toggled.connect(self.advanced_panel.setVisible) self.cbb_table = QTableWidget(0, 4) - self.cbb_table.setHorizontalHeaderLabels(['CBB 名称', '分区', '状态', '环境检查']) + self.cbb_table.setHorizontalHeaderLabels(['CBB 名称', '分区', '状态', '备注']) self.cbb_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch) self.cbb_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch) for column in (1, 2): @@ -289,11 +289,11 @@ class MainWindow(QWidget): def _update(self): # The refresh flow needs only the library and a CBB; LibSpec/DMS config # are optional and only enable the extra contents check. - ready = not self.busy and not self._management_unsafe and self.loaded_path == self.lmc_edit.text() and self.cbb_table.rowCount() > 0 - self.batch_button.setEnabled(ready and not self._maintenance_recovery_view and bool(self._eligible_names())) - self.selected_batch_button.setEnabled(ready and not self._maintenance_recovery_view and bool(self._eligible_names(checked_only=True))) + ready = not self.busy and self.loaded_path == self.lmc_edit.text() and self.cbb_table.rowCount() > 0 + self.batch_button.setEnabled(ready and bool(self._eligible_names())) + self.selected_batch_button.setEnabled(ready and bool(self._eligible_names(checked_only=True))) self.icdb_repair_button.setEnabled(ready and bool(self._maintenance_names())) - self.backup_restore_button.setEnabled(ready and not self._maintenance_recovery_view and bool(self._maintenance_names())) + self.backup_restore_button.setEnabled(ready and bool(self._maintenance_names())) self.release_library_button.setEnabled(not self.busy and bool(self.lmc_edit.text().strip())) reasons = [] for operation, widget in (('add', self.add_button), ('update', self.update_button), ('remove', self.remove_button)): @@ -303,10 +303,7 @@ class MainWindow(QWidget): if reason: reasons.append(reason) self.management_capability_label.setText('\n'.join(dict.fromkeys(reasons))) - notice = ('该库有未确认的会话记录,新增、替换、移除和普通校验已暂停。' - '请先执行 ICDB 维护;仍有数据库地址记录时,单独点击释放检查不会解除阻止。' - if self._maintenance_recovery_view else - '上次管理操作尚未确认安全释放,已暂停库操作。请先查看异常证据并检查会话释放。' + notice = ('上次管理操作尚未确认安全释放,请检查该操作的结果。' if self._management_unsafe else '') self.library_notice.setText(notice) self.library_notice.setVisible(bool(notice)) @@ -357,8 +354,6 @@ class MainWindow(QWidget): def _management_block_reason(self, operation): if self.busy: return '当前任务尚未结束,请等待后再执行库管理操作。' - if self._maintenance_recovery_view: - return '库的会话释放尚未确认,管理操作已禁用;请先执行 ICDB 维护并查看逐项结果。' if self._management_unsafe: return '上次管理操作的会话尚未安全释放,请先查看异常证据并执行释放检查。' capability = self.management_capabilities[operation] @@ -546,21 +541,8 @@ class MainWindow(QWidget): 'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s', lease.display_path, mentor_path, lease.drive or '-', lease.remote_root or '-', lease.created) - from cbb_refresh_verify.library_lock import blocker_path, checkpoint_record - marker = blocker_path(mentor_path) recovery_view = False - if marker.exists() or marker.with_suffix('.pending').exists(): - from cbb_refresh_verify.models import LibraryReadResult - checkpoint = checkpoint_record(marker) - if (checkpoint is not None and not marker.with_suffix('.pending').exists() - and Path(checkpoint['library']).resolve() == Path(mentor_path).resolve()): - result = read_library_fast(mentor_path, - status_reader=lambda _, names: {name: 'UNKNOWN' for name in names}) - recovery_view = True - else: - result = LibraryReadResult((), '此库检查点损坏或身份不符,保留原记录;请先审查并执行释放检查。') - else: - result = self.reader(mentor_path) + result = self.reader(mentor_path) if self.logging_context: statuses = Counter(record.status for record in result.records) unknown = [record.name for record in result.records if record.status in {'UNKNOWN', 'UNAVAILABLE'}] @@ -673,7 +655,7 @@ class MainWindow(QWidget): def _confirm_verify(self, names): from .backup_notice import MANUAL_BACKUP_NOTICE - if self.busy or not self.loaded_path or self._maintenance_recovery_view or not names: + if self.busy or not self.loaded_path or not names: return if QMessageBox.question(self, '确认批量校验', f'{MANUAL_BACKUP_NOTICE}\n\n目标库:{self.loaded_path}\n' @@ -690,17 +672,13 @@ class MainWindow(QWidget): f'{MANUAL_BACKUP_NOTICE}\nMentor 原生修复可能生成自身备份。\n\n当前中心库:{self.loaded_path}\n\n' f'将检查 {len(names)} 个可见非 READY CBB' f'{"(仅勾选项)" if self.selected_records() else ""}。未确认状态不等于损坏。\n' - '先取得库锁并核对工程,由原生工具检查占用和数据库。仅本轮检查确认当前工程未占用且需要 ICDB Repair 时才修复,再重新打开校验。' - '占用、历史版本提示或故障原因未确认时停止,不猜测故障或删除地址文件。READY 项始终忽略。\n' - '仅本地固定磁盘:严格确认修复并重新独占检查后,可一次确认本次异常退出的读写访问提示。' - '网络盘、UNC 或链接路径不自动确认该提示。\n' - '共享符号库不支持自动修复。若原生工具恢复了旧备份,需人工核对版本;' - '会话安全无法确认时停止队列。\n\n是否开始检查与修复?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) + '原生工具确认需要修复时执行 Repair,完成后可单独运行校验。\n' + '若恢复了历史备份,请核对工程版本。\n\n是否开始?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if answer == QMessageBox.Yes: self._run(names, maintenance=True) def restore_backup(self): - if self.busy or not self.loaded_path or self._maintenance_recovery_view: + if self.busy or not self.loaded_path: return from .backup_recovery_dialog import BackupRecoveryDialog names = self._eligible_names(checked_only=bool(self.selected_records())) @@ -719,7 +697,7 @@ class MainWindow(QWidget): def _backup_request(self, name): # A still-open dialog must recheck a target after an earlier recovery # or an authoritative refresh changed its eligibility. - if self.busy or self._maintenance_recovery_view or name not in self._eligible_names(checked_only=bool(self.selected_records())): + if self.busy or name not in self._eligible_names(checked_only=bool(self.selected_records())): raise ValueError('目标需为当前可见、可用的非 READY CBB;请重新选择。') return self._request(name) @@ -759,14 +737,13 @@ class MainWindow(QWidget): def _run(self, names, *, maintenance=False): if self.busy or not self.loaded_path: return - if self._maintenance_recovery_view and not maintenance: return eligible = set(self._maintenance_names() if maintenance else self._eligible_names()) names = [name for name in names if name in eligible] if not names: self.status_label.setText('当前可见选择中没有可校验的非 READY CBB。') self._update() return - requests = [replace(self._request(name), maintenance=maintenance) for name in names] + requests = [replace(self._request(name), maintenance=maintenance, auto_repair=False) for name in names] self._batch_requests = tuple(requests) self._batch_records = {name: self._records_by_name[name] for name in names} self._reimport_offers = () @@ -794,14 +771,16 @@ class MainWindow(QWidget): self.signals.event.emit({'block': req.block_name, 'stage': 'icdb_check_start'}) return verify(req) results = run_batch(requests, verifier=verifier, stop=self.stop, - progress=lambda name, result: self.signals.event.emit({'block': name, 'stage': result.status, 'detail': result.stderr, 'evidence': str(result.evidence_path or '')})) + progress=lambda name, result: self.signals.event.emit({'block': name, 'stage': result.status, + 'error_category': result.error_category, 'evidence': str(result.evidence_path or ''), + 'detail': result.stderr or result.stdout})) report = write_batch_report(requests, results, self.data_root/'reports') if maintenance: from cbb_refresh_verify.icdb_maintenance import write_maintenance_report write_maintenance_report(requests, results, report, ()) affected = [req.block_name for req, result in zip(requests, results) if result.status != 'SKIPPED'] safe = all(result.safe_to_continue for result in results) - refresh = self._read_affected_records(affected) if safe and not self._maintenance_recovery_view else None + refresh = self._read_affected_records(affected) if safe else None return results, report, affected, refresh self._start(action, self._batch_done) @@ -874,7 +853,7 @@ class MainWindow(QWidget): (UNKNOWN on read failure). It runs before the worker's finished signal. Search, filter, original logical_type and action-result cells are retained. """ - if self.busy or not self.loaded_path or self._maintenance_recovery_view: + if self.busy or not self.loaded_path: return False targets = tuple(dict.fromkeys(name for name in names if name in self._records_by_name)) if not targets: @@ -895,20 +874,26 @@ class MainWindow(QWidget): self.output.append(line) block = event.get('block'); stage = event.get('stage') if self._global_icdb_run: - if stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED', 'QUEUE_STOP', 'CHECKED', 'CANCELLED'}: + if stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED', 'QUEUE_STOP', 'CHECKED', 'CANCELLED', 'REPAIRED'}: self._icdb_completed += 1 self.icdb_progress.setValue(self._icdb_completed) phases = {'icdb_check_start': '检查工程数据库与校验状态', + 'icdb_ownership_check': '正在打开原生检查工具', + 'native_started': '等待原生工具加载工程', + 'native_occupancy_wait': '等待原生检查结果', + 'native_repair_complete': '原生修复完成,待单独校验', 'native_repair_start': '核对占用并准备原生修复', 'native_repair_requested': '正在原生修复', 'native_repair_confirmed': '正在原生修复', 'native_repair_finished': '原生修复已结束,正在核对结果'} if stage in phases: self.icdb_phase.setText(f'{block or ""} · {phases[stage]}') - if block and stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED'}: + if block and stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED', 'CHECKED', 'REPAIRED'}: row = self._row_by_name.get(block) if row is not None: detail = str(event.get('detail') or event.get('error') or '').strip() + if str(event.get('error_category', '')).startswith('ICDB') and detail: + detail = 'ICDB 问题:' + detail label = str(stage) if not detail else f'{stage}: {detail[:96]}' self.cbb_table.item(row, 3).setText(label) self.cbb_table.item(row, 3).setToolTip(detail) @@ -931,8 +916,6 @@ class MainWindow(QWidget): self._reimport_offers = tuple((req, self._batch_records[req.block_name], result) for req, result in zip(self._batch_requests, results) if req.maintenance and req.block_name in self._batch_records and offers_reimport(result)) - if self._maintenance_recovery_view and self._global_icdb_run and results: - self._reload_after_maintenance = all(result.safe_to_continue for result in results) if len(outcome) > 2: _, _, affected, refresh = outcome if refresh is None: @@ -948,7 +931,8 @@ class MainWindow(QWidget): passed = sum(r.status == 'PASS' for r in results) skipped = sum(r.status == 'SKIPPED' for r in results) checked = sum(r.status == 'CHECKED' for r in results) - failed = len(results)-passed-skipped-checked + repaired = sum(r.status == 'REPAIRED' for r in results) + failed = len(results)-passed-skipped-checked-repaired text = (f'已结束:成功 {passed},失败 {failed},预检跳过 {len(self.skipped_names)},' f'队列未执行 {skipped}。\n完整日志:{report}\n仅失败日志:{failure_report_path(report)}') if self._global_icdb_run: @@ -957,7 +941,7 @@ class MainWindow(QWidget): text = ('非 READY ICDB 检查已结束\n' f'修复并校验通过 {passed},失败/受阻 {failed},队列未执行 {skipped}\n' f'仅检查、未修复 {counts["checked_without_repair"]}(不计入修复成功)\n' - f'原生修复完成 {counts["repaired"]},恢复备份待复核 {counts["review_required"]},' + f'原生修复完成、待单独校验 {counts["repaired_unverified"]},恢复备份待复核 {counts["review_required"]},' f'ICDB已修复/PCB版本待选 {counts["version_choice_required"]},' f'修复未确认 {counts["repair_unconfirmed"]}\n' f'完整日志:{report}\n仅失败日志:{failure_report_path(report)}') @@ -966,12 +950,14 @@ class MainWindow(QWidget): text += '\n未确认数据库或会话安全,已停止剩余校验。请查看恢复现场。' status_text = (f'已结束:通过 {passed},失败/受阻 {failed},' f'仅检查 {checked},未执行 {skipped + len(self.skipped_names)}。') + if repaired: + status_text += f'\n原生 ICDB 修复完成 {repaired},待单独校验。' if self._global_icdb_run and counts['review_required']: status_text += f'\n恢复备份待复核 {counts["review_required"]},请核对工程版本。' if self._global_icdb_run and counts['version_choice_required']: status_text += f'\n待选择 PCB 版本 {counts["version_choice_required"]}。' first_failure = next((result.stderr for result in results - if result.status not in ('PASS', 'SKIPPED') and result.stderr), '') + if result.status not in ('PASS', 'SKIPPED', 'CHECKED', 'REPAIRED') and result.stderr), '') if first_failure: text += '\n首个未完成原因:' + first_failure if any(result.error_category == 'CBB_REIMPORT_REQUIRED' for result in results): diff --git a/src/cbb_refresh_verify/verify_runner.py b/src/cbb_refresh_verify/verify_runner.py index a0a23ef..56ce479 100644 --- a/src/cbb_refresh_verify/verify_runner.py +++ b/src/cbb_refresh_verify/verify_runner.py @@ -62,7 +62,7 @@ class VerifyRequest: # it before launching Library Manager/PCB. mapped_drive: str = '' mapped_remote_root: str = '' - auto_repair: bool = True + auto_repair: bool = False maintenance: bool = False post_repair_proof: object | None = field(default=None, repr=False, compare=False) diagnostic_only: bool = False @@ -522,6 +522,12 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, acquired = False library_lock = None release_confirmed = True + remaining_clients = () + def clients_released(): + if release_confirmed: + return True + from .library_lock import _supervisor_alive + return bool(remaining_clients) and not any(_supervisor_alive(pid) for pid in remaining_clients) try: acquired = win32event.WaitForSingleObject(mutex, 0) in ( win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED) @@ -535,17 +541,15 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, except (ValueError, OSError) as error: return VerifyResult('BLOCKED', stderr=str(error), safe_to_continue=False) if needed: - return run_existing_address_maintenance(request, progress=progress, stop=stop, - verify=lambda req: _run_verify_serialized(req, progress=progress, flag_reader=flag_reader, - process_runner=process_runner, port_check=port_check, - dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt)) + return run_existing_address_maintenance(request, progress=progress, stop=stop) from .library_lock import LibraryLock, LibraryBusy if Path(request.lmc_file).is_file(): try: - library_lock = LibraryLock(request.lmc_file, safe_to_release=lambda: release_confirmed) + library_lock = LibraryLock(request.lmc_file, checkpoint=False, + safe_to_release=clients_released) library_lock.__enter__() except LibraryBusy as error: - return VerifyResult('BLOCKED', stderr=str(error), safe_to_continue=False) + return VerifyResult('FAIL', stderr=str(error), error_category='LIBRARY_IN_USE') release_confirmed = False result = _run_verify_serialized( request, progress=progress, flag_reader=flag_reader, @@ -629,6 +633,18 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, except OSError: pass # Keep the native/repair errors even if evidence storage fails. release_confirmed = result.safe_to_continue + if not release_confirmed and result.evidence_path: + try: + release = json.loads(result.evidence_path.with_name('session-release.json').read_text('utf-8')) + release_confirmed = (release.get('worker_exited') is True + and release.get('safe_to_continue') is True and release.get('block') == request.block_name + and Path(release['library']).resolve() == Path(request.lmc_file).resolve()) + if (release.get('worker_exited') is True and release.get('block') == request.block_name + and Path(release['library']).resolve() == Path(request.lmc_file).resolve()): + remaining_clients = tuple(pid for pid in release.get('remaining_pids', []) + if type(pid) is int and pid > 0) + except (OSError, ValueError, KeyError): + pass return result finally: try: @@ -673,8 +689,17 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_ detail = result.stderr if recovery and RECOVERY_ACTION not in detail: detail = (detail + '\n' + recovery_detail(recovery)).strip() - result = replace(result, safe_to_continue=False, stderr=detail, - error_category=ERROR_CODE) + result = replace(result, stderr=detail, error_category=ERROR_CODE) + if not request.auto_repair and result.evidence_path: + try: + release = json.loads(result.evidence_path.with_name('session-release.json').read_text('utf-8')) + if (result.error_stage in {'PCB_STARTING', 'pcb_startup'} + and release.get('worker_exited') is True and release.get('safe_to_continue') is True + and release.get('block') == request.block_name + and Path(release['library']).resolve() == Path(request.lmc_file).resolve()): + result = replace(result, safe_to_continue=True) + except (OSError, ValueError, KeyError): + pass if recovery and result.evidence_path: try: record_path = result.evidence_path.parent/'diagnostics/icdb-recovery.json' @@ -752,17 +777,6 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run finally: timing.end('preflight') - from .icdb_ownership import unreleased_addresses - try: - addresses = unreleased_addresses(request.lmc_file, project, pcb) - if addresses: - return finish(VerifyResult('BLOCKED', safe_to_continue=False, - stderr='ICDB_SESSION_UNCONFIRMED: 原生数据库所有权未释放,未开始内容检查或校验:' - + '; '.join(addresses))) - except OSError as error: - return finish(VerifyResult('BLOCKED', safe_to_continue=False, - stderr=f'ICDB_SESSION_UNCONFIRMED: 无法确认数据库所有权:{error}')) - content_check_enabled = not request.diagnostic_only and bool(str(request.libspec).strip() and str(request.dms_login_config).strip()) if content_check_enabled: try: @@ -1070,13 +1084,20 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run from .icdb_ownership import unreleased_addresses addresses = unreleased_addresses(request.lmc_file, project, pcb) if addresses: - release_result = {**(release_result or {}), 'safe_to_continue': False, - 'icdb_address': addresses[0], 'icdb_addresses': addresses} + release_result = {**(release_result or {}), 'icdb_addresses': addresses} except OSError as error: close_errors.append(str(error)) if close_errors: release_result = {**(release_result or {}), 'safe_to_continue': False, 'close_errors': close_errors} + try: + (root/'session-release.json').write_text(json.dumps({ + **(release_result or {}), 'block': request.block_name, + 'library': str(request.lmc_file), 'worker_exited': process.poll() is not None, + 'worker_pid': getattr(process, 'pid', None)}, + ensure_ascii=False, default=str, indent=2), encoding='utf-8') + except OSError: + pass if not release_result or not release_result.get('safe_to_continue'): if 'result' in locals(): result = replace(result, status='FAIL', safe_to_continue=False, @@ -1173,11 +1194,12 @@ def write_failure_report(requests, results, root, *, path=None): path = Path(path) if path else root/('failures-' + time.strftime('%Y%m%d-%H%M%S') + '-' + uuid4().hex[:6] + '.log') failed = [(req, result) for req, result in zip(requests, results) if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'} - and not (result.status == 'CHECKED' and result.safe_to_continue)] + and not (result.status in {'CHECKED', 'REPAIRED'} and result.safe_to_continue)] passed = sum(result.status == 'PASS' for result in results) checked = sum(result.status == 'CHECKED' and result.safe_to_continue for result in results) - skipped = len(results)-passed-len(failed)-checked - lines = ['CBB Verify 失败清单', f'总数: {len(results)} 成功: {passed} 失败: {len(failed)} 未执行: {skipped} 仅检查未修复: {checked}', + repaired = sum(result.status == 'REPAIRED' and result.safe_to_continue for result in results) + skipped = len(results)-passed-len(failed)-checked-repaired + lines = ['CBB Verify 失败清单', f'总数: {len(results)} 成功: {passed} 失败: {len(failed)} 未执行: {skipped} 仅检查未修复: {checked} ICDB已修复待校验: {repaired}', 'CBB\t状态\t错误分类\t失败阶段\t桥状态\t原始错误\t证据\t实际耗时(秒)'] for req, result in failed: timings = ' '.join(f'{key}={value:.3f}s' + diff --git a/tests/test_icdb_recovery.py b/tests/test_icdb_recovery.py index 6790dfa..064b3f6 100644 --- a/tests/test_icdb_recovery.py +++ b/tests/test_icdb_recovery.py @@ -258,7 +258,7 @@ def test_native_log_capture_generates_only_fresh_repair_evidence(tmp_path, name) assert log.read_text('utf-8') == ERROR -def test_contents_session_loss_stops_batch_before_any_pcb_launch(tmp_path, monkeypatch): +def test_contents_session_loss_records_each_item_without_launching_pcb_or_repair(tmp_path, monkeypatch): from test_verify_runner import fixture, request fixture(tmp_path) monkeypatch.setattr(runner, 'resolve_importer', lambda *_: Path('ReuseBlockImporter.exe')) @@ -269,11 +269,12 @@ def test_contents_session_loss_stops_batch_before_any_pcb_launch(tmp_path, monke results = runner.run_batch([request(tmp_path, libspec='EE', dms_login_config='login')]*2, verifier=lambda req: runner.run_verify(req, process_runner=content_check, port_check=lambda: pytest.fail('PCB must not start'))) - assert len(calls) == 1 + assert len(calls) == 2 assert results[0].error_category == 'ICDB_REPAIR_REQUIRED' - assert results[0].safe_to_continue is False + assert results[0].safe_to_continue is True assert 'Repair project' in results[0].stderr - assert results[1].status == 'SKIPPED' + assert results[1].status == 'FAIL' + assert results[1].error_category == 'ICDB_REPAIR_REQUIRED' def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, monkeypatch): diff --git a/tests/test_independent_operations.py b/tests/test_independent_operations.py new file mode 100644 index 0000000..31aefe0 --- /dev/null +++ b/tests/test_independent_operations.py @@ -0,0 +1,142 @@ +from pathlib import Path + +import pytest +from test_maintenance_entry import case + + +def test_verify_defaults_to_no_repair_and_does_not_retain_a_failure_lock(tmp_path, monkeypatch): + from cbb_refresh_verify import verify_runner as runner, library_lock as locks, native_repair + library = tmp_path / 'library.lmc'; library.touch() + req = runner.VerifyRequest(library, 'CBB', tmp_path / 'evidence') + assert req.auto_repair is False + marker = locks.blocker_path(library) + marker.write_text('historical diagnostic record') + calls = [] + result = runner.VerifyResult('FAIL', stderr='ICDB_REPAIR_REQUIRED: session lost', + error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=True) + monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: (calls.append('verify') or result)) + monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **k: pytest.fail('verify requested Repair')) + assert runner.run_verify(req) is result + assert runner.run_verify(req) is result + assert calls == ['verify', 'verify'] + assert marker.read_text() == 'historical diagnostic record' + assert locks._key(tmp_path / '.library.cbb-upload.lock') not in locks._owners + + +def test_catalog_checkpoint_does_not_disable_ordinary_verify(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + from cbb_refresh_verify.verify_runner import VerifyResult + calls = [] + window = load_window(qtbot, tmp_path, monkeypatch, + verifier=lambda req: (calls.append(req) or VerifyResult('FAIL', stderr='ICDB_REPAIR_REQUIRED: lost', + error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=True)), + status_refresher=lambda names, _: {name: 'PENDING' for name in names}) + window._maintenance_recovery_view = True + window._management_unsafe = True + window.search_edit.setText('Beta'); window.select_visible_button.click(); window._update() + assert window.selected_batch_button.isEnabled() + window.verify_selected(); qtbot.waitUntil(lambda: not window.busy) + assert len(calls) == 1 and not calls[0].maintenance and not calls[0].auto_repair + assert window.selected_batch_button.isEnabled() + assert 'ICDB' in window.cbb_table.item(window._row_by_name['Beta'], 3).text() + + +def test_maintenance_guard_does_not_scan_other_cbb_projects(case, monkeypatch): + from cbb_refresh_verify import maintenance_entry as entry + from cbb_refresh_verify import scoped_manifest as manifests + req, project, _ = case + scans = [] + scan = manifests.scan_tree + monkeypatch.setattr(manifests, 'scan_tree', lambda root, **kw: (scans.append(Path(root)) or scan(root, **kw))) + with entry.maintenance_target_guard(req): + pass + assert req.lmc_file.parent not in scans + assert scans.count(project.parent) == 2 + + +def test_repair_finishes_without_calling_verify(case, monkeypatch): + from cbb_refresh_verify import native_repair, verify_runner as runner + from test_maintenance_entry import patch_verification_after_fault + from test_native_repair import complete_native_success + req, _, address = case + def repair(target, *a, **kw): + address.unlink() + return complete_native_success(target) + monkeypatch.setattr(native_repair, 'run_native_repair', repair) + monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release']) + patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: pytest.fail('maintenance started CBB verification')) + result = runner.run_verify(req) + assert result.status == 'REPAIRED' and result.safe_to_continue + assert result.library_flag == 'UNKNOWN' + assert result.recovery_attempts[0]['validation_passed'] is False + + +@pytest.mark.parametrize('stage,expected_safe', [('PCB_STARTING', True), ('back_annotation', False)]) +def test_only_released_startup_failure_can_continue_from_icdb_diagnosis(tmp_path, monkeypatch, stage, expected_safe): + import json + from cbb_refresh_verify import verify_runner as runner + library = tmp_path/'library.lmc'; library.touch() + evidence = tmp_path/'evidence'; evidence.mkdir() + report = evidence/'result.json'; report.write_text('{}') + (evidence/'session-release.json').write_text(json.dumps({'library': str(library), + 'block': 'CBB', 'worker_exited': True, 'safe_to_continue': True})) + failure = runner.VerifyResult('FAIL', stderr='ICDB_REPAIR_REQUIRED: lost session', + error_stage=stage, safe_to_continue=False, evidence_path=report) + monkeypatch.setattr(runner, '_run_verify', lambda *a, **k: failure) + result = runner._run_verify_serialized(runner.VerifyRequest(library, 'CBB', evidence)) + assert result.status == 'FAIL' and result.error_category == 'ICDB_REPAIR_REQUIRED' + assert result.safe_to_continue is expected_safe + + +def test_live_writer_keeps_execution_lock_without_a_permanent_diagnostic_blocker(tmp_path, monkeypatch): + import win32con, win32file + from cbb_refresh_verify import library_lock as locks, verify_runner as runner + library = tmp_path/'lib.lmc'; library.touch() + monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: + runner.VerifyResult('TIMEOUT', safe_to_continue=False)) + result = runner.run_verify(runner.VerifyRequest(library, 'CBB', tmp_path/'evidence')) + lock = locks.LibraryLock(library) + try: + assert not result.safe_to_continue and not locks.blocker_path(library).exists() + with pytest.raises(Exception): + win32file.CreateFile(str(lock.path), win32con.GENERIC_READ | win32con.GENERIC_WRITE, + 0, None, win32con.OPEN_ALWAYS, 0, None) + finally: + with locks._guard: + owner = locks._owners.pop(lock.key, None) + if owner: owner['handle'].Close() + + +def test_healthy_native_inspection_with_old_address_does_not_lock_management(case, monkeypatch): + from cbb_refresh_verify import native_repair, verify_runner as runner, library_lock as locks + from test_native_occupancy import output + request, project, address = case + def inspect(target, *a, **kw): + assert kw['inspection_only'] + return {'inspection_only': True, 'repair_requested': False, 'repair_required': False, + 'status': 'NOT_IN_USE', 'native_pid': 777, 'native_exit_code': 0, + 'project': str(target.project), 'database': str(target.database), + 'output': output(target.project, target.database), 'release': {'native_exited': True}} + monkeypatch.setattr(native_repair, 'run_native_repair', inspect) + result = runner.run_verify(request) + assert result.status == 'CHECKED' and result.safe_to_continue and address.exists() + assert not result.stderr and '无需修复' in result.stdout + assert not locks.blocker_path(request.lmc_file).exists() + with locks.LibraryLock(request.lmc_file): pass + + +@pytest.mark.parametrize('operation', ['verify', 'maintenance']) +def test_retained_execution_lease_can_retry_after_its_actual_client_exits(tmp_path, operation): + from contextlib import contextmanager + from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy + library = tmp_path/'library.lmc'; library.touch() + released = [False] + with LibraryLock(library, checkpoint=False, safe_to_release=lambda: released[0]): pass + with pytest.raises(LibraryBusy): + with LibraryLock(library, checkpoint=False): pass + released[0] = True + @contextmanager + def guard(): yield {'target': 'isolated fixture'} + lock = (LibraryLock(library, checkpoint=False) if operation == 'verify' else + LibraryLock.for_maintenance(library, tmp_path/'archive', guard, safe_to_release=lambda: True)) + with lock: pass diff --git a/tests/test_library_lock.py b/tests/test_library_lock.py index fa9d8b3..5b3c4a7 100644 --- a/tests/test_library_lock.py +++ b/tests/test_library_lock.py @@ -65,28 +65,25 @@ def test_verification_refuses_uploader_exclusive_lock_before_native_work(tmp_pat monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: pytest.fail('native work bypassed lock')) try: result = runner.run_verify(runner.VerifyRequest(library, 'Block', tmp_path/'out')) - assert result.status == 'BLOCKED' and not result.safe_to_continue + assert result.status == 'FAIL' and result.safe_to_continue finally: handle.Close() -def test_unsafe_verify_retains_lease_and_persistent_blocker(tmp_path, monkeypatch): +def test_unsafe_verify_records_failure_without_persistent_library_blocker(tmp_path, monkeypatch): + import json import cbb_refresh_verify.verify_runner as runner import cbb_refresh_verify.library_lock as locks library = tmp_path/'lib.lmc'; library.touch() + evidence = tmp_path/'out'; evidence.mkdir() + (evidence/'session-release.json').write_text(json.dumps({'library': str(library), + 'block': 'Block', 'worker_exited': True, 'safe_to_continue': True})) monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: - runner.VerifyResult('FAIL', safe_to_continue=False)) + runner.VerifyResult('FAIL', safe_to_continue=False, evidence_path=evidence/'result.json')) result = runner.run_verify(runner.VerifyRequest(library, 'Block', tmp_path/'out')) assert not result.safe_to_continue - assert locks.blocker_path(library).is_file() - with pytest.raises(locks.LibraryBusy): - with locks.LibraryLock(library): pass - # Simulate OS handle loss on process exit; persistent marker still blocks. - with locks._guard: - owner = locks._owners.pop(str((tmp_path/'.lib.cbb-upload.lock').resolve()).casefold(), None) - if owner: owner['handle'].Close() - with pytest.raises(locks.LibraryBusy): - with locks.LibraryLock(library): pass + assert not locks.blocker_path(library).exists() + with locks.LibraryLock(library): pass def test_explicit_release_requires_fresh_proof_and_never_deletes_sidecar(tmp_path, monkeypatch): diff --git a/tests/test_maintenance_entry.py b/tests/test_maintenance_entry.py index 13844c3..edd94fd 100644 --- a/tests/test_maintenance_entry.py +++ b/tests/test_maintenance_entry.py @@ -96,8 +96,9 @@ def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fa return runner.VerifyResult('PASS', library_flag='GREEN') patch_verification_after_fault(monkeypatch, runner, verify) result = runner.run_verify(request) - assert calls == ['repair', 'verify'] and result.status == 'PASS' - assert result.recovery_attempts[0]['validation_passed'] is True + assert calls == ['repair'] and result.status == 'REPAIRED' + assert result.recovery_attempts[0]['validation_passed'] is False + assert result.library_flag == 'UNKNOWN' record = json.loads(result.evidence_path.read_text(encoding='utf-8')) assert record['operation'] == 'explicit_project_maintenance' assert 'session' not in record['maintenance_context'] @@ -118,7 +119,7 @@ def test_addressless_target_binds_unique_project_and_rejects_new_address(case): def test_guard_reuses_full_tree_scan_but_still_refreshes_before_yield(case, monkeypatch): from cbb_refresh_verify.maintenance_entry import maintenance_target_guard import cbb_refresh_verify.scoped_manifest as manifests - request, _, _ = case + request, project, _ = case scans = [] original = manifests.scan_tree def scan(root, **kwargs): @@ -126,7 +127,8 @@ def test_guard_reuses_full_tree_scan_but_still_refreshes_before_yield(case, monk return original(root, **kwargs) monkeypatch.setattr(manifests, 'scan_tree', scan) with maintenance_target_guard(request): pass - assert scans.count(request.lmc_file.parent) == 2 + assert request.lmc_file.parent not in scans + assert scans.count(project.parent) == 2 def test_guard_rejects_new_native_database_appearing_during_checks(case, monkeypatch): @@ -198,12 +200,15 @@ def test_optional_pcb_project_appearance_invalidates_maintenance_proof(case): with maintenance_target_guard(request, before): pass -def test_ordinary_verify_still_blocks_existing_address_without_repair(case, monkeypatch): +def test_ordinary_verify_calls_native_verifier_despite_existing_address(case, monkeypatch): from cbb_refresh_verify import verify_runner as runner, native_repair request, _, address = case monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: pytest.fail('ordinary verify must not repair')) + calls = [] + monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: + (calls.append('verify') or runner.VerifyResult('FAIL', stderr='native ICDB problem'))) result = runner.run_verify(replace(request, maintenance=False)) - assert result.status == 'BLOCKED' and not result.safe_to_continue + assert calls == ['verify'] and result.status == 'FAIL' and result.safe_to_continue assert address.read_bytes() == b'old server address - preserved' @@ -373,11 +378,11 @@ def test_independent_cbb_address_does_not_select_or_block_current_project(case): @pytest.mark.parametrize('status,complete,expected_safe', [ - ('RESTORED_REVIEW_REQUIRED', True, False), ('DATABASE_BUSY', True, False), - ('UNKNOWN_DIALOG', True, False), ('UNCONFIRMED', True, False), - ('MISSING_HEALTHY_BACKUP', False, False), ('NATIVE_REPAIR_FAILED', False, False), + ('RESTORED_REVIEW_REQUIRED', True, True), ('DATABASE_BUSY', True, True), + ('UNKNOWN_DIALOG', True, True), ('UNCONFIRMED', True, True), + ('MISSING_HEALTHY_BACKUP', False, True), ('NATIVE_REPAIR_FAILED', False, True), ('MISSING_HEALTHY_BACKUP', True, True), ('NATIVE_REPAIR_FAILED', True, True)]) -def test_physical_release_alone_does_not_authorize_queue(case, monkeypatch, status, complete, expected_safe): +def test_failed_content_does_not_block_other_items_after_actual_release(case, monkeypatch, status, complete, expected_safe): from cbb_refresh_verify import native_repair, verify_runner as runner, library_lock from test_native_repair import complete_native_success request, _, address = case @@ -410,10 +415,10 @@ def test_successful_icdb_repair_then_version_choice_reports_partial_completion(c error_category='PCB_VERSION_CHOICE_REQUIRED', stderr='PCB版本待选:最后用户保存/自动保存 2026/9/24 23:06', safe_to_continue=False, evidence_path=request.evidence_dir/'verify/result.json')) result = runner.run_verify(request) - assert result.status == 'FAIL' and not result.safe_to_continue - assert 'ICDB原生修复已完成' in result.stderr and '尚未校验通过' in result.stderr + assert result.status == 'REPAIRED' and result.safe_to_continue + assert '待单独校验' in result.stdout assert result.recovery_attempts[0]['native_status'] == 'REPAIRED' - assert result.recovery_attempts[0]['status'] == 'PCB_VERSION_CHOICE_REQUIRED' + assert result.recovery_attempts[0]['status'] == 'REPAIRED_UNVERIFIED' assert result.recovery_attempts[0]['validation_passed'] is False @@ -431,6 +436,6 @@ def test_user_chosen_pcb_history_is_not_reported_as_lossless_repair(case, monkey return runner.VerifyResult('PASS', library_flag='GREEN', evidence_path=root/'result.json') patch_verification_after_fault(monkeypatch, runner, verify) result = runner.run_verify(request) - assert result.status == 'PASS' - assert result.recovery_attempts[0]['status'] == 'RESTORED_REVIEW_REQUIRED' - assert result.recovery_attempts[0]['pcb_version']['choice'] == 'last_user_saved' + assert result.status == 'REPAIRED' and result.library_flag == 'UNKNOWN' + assert result.recovery_attempts[0]['status'] == 'REPAIRED_UNVERIFIED' + assert not (request.evidence_dir/'verify').exists() diff --git a/tests/test_maintenance_ui.py b/tests/test_maintenance_ui.py index 65cf036..33f203d 100644 --- a/tests/test_maintenance_ui.py +++ b/tests/test_maintenance_ui.py @@ -24,15 +24,18 @@ def test_only_confirmed_maintenance_sets_explicit_flag(qtbot, tmp_path, monkeypa @pytest.mark.parametrize('marker_kind', ['valid', 'foreign', 'malformed']) -def test_blocked_library_recovery_view_is_filesystem_only_and_maintenance_only(qtbot, tmp_path, monkeypatch, marker_kind): +def test_old_checkpoint_does_not_force_maintenance_or_disable_verify(qtbot, tmp_path, monkeypatch, marker_kind): from cbb_refresh_verify.library_lock import LibraryLock, blocker_path, _owners, _guard from cbb_refresh_verify.ui.main_window import MainWindow from cbb_refresh_verify.verify_runner import VerifyResult + from cbb_refresh_verify.models import LibraryReadResult, CbbRecord import cbb_refresh_verify.ui.main_window as ui library = tmp_path/'library/mentor.lmc'; library.parent.mkdir(); library.touch() (library.parent/'ReusableBlocksLP/IP101GR').mkdir(parents=True) with LibraryLock(library, safe_to_release=lambda: False) as lock: pass - with _guard: _owners.pop(lock.key)['handle'].Close() + with _guard: + owner = _owners.pop(lock.key, None) + if owner: owner['handle'].Close() marker = blocker_path(library) if marker_kind == 'malformed': marker.write_text('{}') if marker_kind == 'foreign': @@ -40,31 +43,26 @@ def test_blocked_library_recovery_view_is_filesystem_only_and_maintenance_only(q marker.write_text(json.dumps(record)) monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *a: None) calls = [] - window = MainWindow(reader=lambda *a: pytest.fail('blocked view called native reader'), + window = MainWindow(reader=lambda *a: LibraryReadResult((CbbRecord('IP101GR', 'Reusable Blocks', status='PENDING'),)), verifier=lambda req: (calls.append(req) or VerifyResult('BLOCKED', safe_to_continue=False)), - status_refresher=lambda *a: pytest.fail('unsafe view refreshed native status'), data_root=tmp_path/'data') + status_refresher=lambda *a: {'IP101GR': 'PENDING'}, data_root=tmp_path/'data') qtbot.addWidget(window) window.lmc_edit.setText(str(library)); window.load_library() qtbot.waitUntil(lambda: not window.busy) assert window.release_library_button.isEnabled() - if marker_kind != 'valid': - assert window.loaded_path is None and not window.icdb_repair_button.isEnabled() - return assert window.visible_records()[0].name == 'IP101GR' - assert window.visible_records()[0].status == 'UNKNOWN' - assert '未确认' in window.status_label.text() - assert 'ICDB' in window.management_capability_label.text() - assert '会话' in window.add_button.toolTip() + assert window.visible_records()[0].status == 'PENDING' + assert not window._maintenance_recovery_view window.select_visible_button.click() assert window.icdb_repair_button.isEnabled() - assert not any(button.isEnabled() for button in (window.batch_button, window.selected_batch_button, - window.backup_restore_button, window.add_button, window.update_button, window.remove_button)) - window.verify_all(); window.verify_selected(); window.restore_backup(); window.manage_cbb('remove') - assert window.refresh_affected_records(['IP101GR']) is False - assert calls == [] and not window.busy + assert window.batch_button.isEnabled() and window.selected_batch_button.isEnabled() monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) + window.verify_selected(); qtbot.waitUntil(lambda: not window.busy) + assert len(calls) == 1 and calls[0].maintenance is False + assert window.selected_batch_button.isEnabled() window.repair_icdb_all(); qtbot.waitUntil(lambda: not window.busy) - assert len(calls) == 1 and calls[0].maintenance is True + assert len(calls) == 2 and calls[1].maintenance is True + assert marker.exists() def test_maintenance_summary_exposes_first_failure_reason(qtbot, tmp_path): @@ -92,11 +90,13 @@ def test_safe_maintenance_reloads_authoritative_catalog_after_worker_finishes(qt library = tmp_path/'library/mentor.lmc'; library.parent.mkdir(); library.touch() (library.parent/'ReusableBlocksLP/IP101GR').mkdir(parents=True) with LibraryLock(library, safe_to_release=lambda: False) as lease: pass - with _guard: _owners.pop(lease.key)['handle'].Close() + with _guard: + owner = _owners.pop(lease.key, None) + if owner: owner['handle'].Close() reads = [] def reader(path): reads.append(path) - return LibraryReadResult((CbbRecord('IP101GR', 'Reusable Blocks', status='READY'),)) + return LibraryReadResult((CbbRecord('IP101GR', 'Reusable Blocks', status='PENDING'),)) def verify(req): assert req.maintenance blocker_path(library).unlink() # Simulate normal cleanup at the injected boundary. @@ -104,12 +104,12 @@ def test_safe_maintenance_reloads_authoritative_catalog_after_worker_finishes(qt monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *a: None) monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) window = MainWindow(reader=reader, verifier=verify, data_root=tmp_path/'data', - status_refresher=lambda *a: pytest.fail('recovery view must reload after worker completion')) + status_refresher=lambda *a: {'IP101GR': 'READY'}) qtbot.addWidget(window) window.lmc_edit.setText(str(library)); window.load_library(); qtbot.waitUntil(lambda: not window.busy) - assert reads == [] + assert len(reads) == 1 window.search_edit.setText('IP101') window.repair_icdb_all() - qtbot.waitUntil(lambda: not window.busy and bool(reads)) + qtbot.waitUntil(lambda: not window.busy) assert window.visible_records()[0].status == 'READY' assert not window._maintenance_recovery_view and window.search_edit.text() == 'IP101' diff --git a/tests/test_native_export_guard.py b/tests/test_native_export_guard.py index 1b32fbb..cdc5e79 100644 --- a/tests/test_native_export_guard.py +++ b/tests/test_native_export_guard.py @@ -13,6 +13,7 @@ def export_case(tmp_path, monkeypatch): import cbb_refresh_verify.native_engineering_identity as identity import win32com.client monkeypatch.setattr(win32com.client, 'GetObject', lambda *_: SimpleNamespace(ExecQuery=lambda *_: [])) + monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_a, **_k: []) monkeypatch.setattr(identity, '_process_snapshot', lambda: []) monkeypatch.setattr(identity, '_retained_exports', []) monkeypatch.setattr(locks, '_supervisor_alive', lambda _: False) diff --git a/tests/test_native_repair.py b/tests/test_native_repair.py index 870a77d..ab99ad8 100644 --- a/tests/test_native_repair.py +++ b/tests/test_native_repair.py @@ -5,6 +5,7 @@ import pytest def target_fixture(tmp_path): + from dataclasses import replace from test_verify_runner import fixture, request from cbb_refresh_verify.native_repair import select_repair_target work = fixture(tmp_path) @@ -13,7 +14,8 @@ def target_fixture(tmp_path): (database/'icdb.dat').write_bytes(b'original damaged database') diagnosis = {'error_code': 'ICDB_REPAIR_REQUIRED', 'machine': 'OLD-PC', 'database_path': str(database), 'session': '2026-10-24 08.22.29-10308', 'scope': 'project'} - return request(tmp_path), diagnosis, select_repair_target(request(tmp_path), diagnosis) + req = replace(request(tmp_path), auto_repair=True) + return req, diagnosis, select_repair_target(req, diagnosis) def complete_native_success(target): @@ -511,7 +513,8 @@ def test_invoked_busy_native_result_never_reopens_or_continues_queue(tmp_path, m busy = json.loads((root/'repair-result.json').read_text('utf-8')) assert (100, win32con.WM_CLOSE) not in actions assert busy['status'] == 'DATABASE_BUSY' and busy['release']['native_exited'] is False - req = request(tmp_path) + from dataclasses import replace + req = replace(request(tmp_path), auto_repair=True) target = json.loads(job.read_text('utf-8')) evidence = tmp_path/'first/result.json' evidence.parent.mkdir()