fix: persist release outcomes and guard active native backup sessions

This commit is contained in:
阿白叔 committed 2026-11-06 12:08:54 +08:00
1 parent d40192ee58
commit 5eb4b2d7ed
10 files changed
+669 -69

No files matched your search

+2
View File
@@ -4,6 +4,8 @@
当前开发版本:**[v0.2.4-beta.1](docs/releases/v0.2.4-beta.1.md)(待评审、待现场验收)**。ICDB 批量检查在后台逐项运行,普通校验、管理和恢复可排队;READY 工程在实际执行前再次排除。检查不自动 Repair、Restore 或选择历史版本,也不代表中心库 READY。
历史释放记录会触发实际占用复核,确认释放后归档继续;会话释放不等于历史数据恢复。释放结果逐项保存;记录保存失败会单独显示,不把已确认释放的会话重新标成占用。可查看后台窗口的原生提示;仅对当前可识别的原生取消按钮提供确认操作。
自动流程不强杀原生会话;释放入口默认正常关闭。另有单独确认的“强制结束客户端”操作,仅限属于当前 Windows 用户和会话、归属及进程身份已确认的 PCB、Library Manager、DxDesigner/viewdraw、iCDB Project Backup 客户端。**ICDB 数据库服务器、后台导入器和归属未知的进程不允许强制结束**,即使命令指向当前库也不例外。客户端中其他已打开工程可能一并退出、未保存更改可能丢失;必须先记录确认名单,结束后重新证明库已释放,不能宣称数据库已修复。详见 [操作规程](SOP.md) 与 [版本说明](docs/releases/v0.2.4-beta.1.md)。下方日期记录为历史行为,以本说明为准。
本目录是独立的 CBB 中心库上传后校验工具,不属于 Part Replacement,也不负责 CBB 工程复制或中心库上传。
+10 -2
View File
@@ -12,13 +12,21 @@
新增拒绝同名冲突;更新先原生移除再导入,失败可能需要人工备份恢复;移除后重新读取目录确认。版本回退由操作员在原生界面选择,核对工程内容后单独校验。
## 历史记录、操作结果与报告
校验和管理遇到历史释放记录时,先复核实际进程、地址、独占文件及导出副本。确认释放后归档记录再继续,不以历史 JSON 本身判定真实占用;同目标未完成写入仍需核对,不自动重放。释放证明在管理首次原生调用前写入检查点,并在结果中保留。
管理操作生成目标工程、库配置和共享依赖的写前/写后主要文件清单及新增、删除、修改差分;不增加自动全库备份,也不声称检查了其他 CBB 内容。报告不可用与原生操作失败分别记录;本任务已释放时可继续独立项。
## 默认释放与单独确认的强制客户端操作
1. 停止新任务,预览当前库的工程、程序、PID 和历史记录。默认“确认释放”仅正常关闭作用域及当前身份已确认的客户端。未保存更改由操作员选择保存、放弃或保留;未知提示保持现场。
2. 数据库服务器可能服务同库其他用户。本工具不允许强制结束服务器,命令行指向本库也不构成独占授权;由库管理员核对用户和服务器状态。
3. “强制结束客户端”是另行确认的异常处理,只允许属于当前 Windows 用户和会话、已确认作用域和精确进程身份的 Expedition PCB、Library Manager、viewdraw、iCDB Project Backup 客户端。后台导入器、脚本宿主和归属未知的进程同样不在强制名单。
4. 警告明确告知客户端中其他已打开工程可能一并退出、未保存更改会丢失、写入中的工程可能需要恢复。执行前持久保存库外 `consent.json`,包含目标库、名单、创建身份和排除项;写入失败不执行。派发与最终进程句柄两处重新核对,PID 复用、用户/Windows 会话或范围变化时拒绝。
5. 客户端退出仅证明进程结束,不表示修复成功或 READY。服务器仍活跃或库状态未知时保留 PARTIAL、检查点和映射。只有完整的独立释放证明才解除匹配的历史记录;空进程列表本身不是释放证明。
4. 警告明确告知客户端中其他已打开工程可能一并退出、未保存更改会丢失、写入中的工程可能需要恢复。执行前持久保存库外 `consent.json`,包含目标库、名单、创建身份和排除项;写入失败不执行。派发处核对快照身份和原预览范围,最终句柄处核对创建时间、完整映像、用户 SID、Windows 会话和原生活动;变化时拒绝。
5. 预览和执行前检查进度与本轮 Output。Backup/Restore/Repair 进行中或状态无法确认时,不强制结束。可查看后台窗口的标题、输出和所在桌面;仅当当前窗口唯一存在已识别的 Cancel/取消按钮时,提供单独确认的原生取消。核对身份、用户会话和按钮快照后发送请求,再重新检查实际结果;没有识别到按钮时不猜菜单参数,不抢占前台。
6. 每项动作前后持久记录实际结果,异常保留已完成/未执行项。若最终记录保存失败但独立库释放证明已确认,界面明确提示记录失败并接受释放事实,不伪造新的占用。
7. 客户端退出仅证明进程结束,不表示修复成功或 READY。服务器仍活跃或库状态未知时保留 PARTIAL、检查点和映射。只有完整的独立释放证明才解除匹配的历史记录;空进程列表本身不是释放证明。
## 失败、证据和回退
+4
View File
@@ -16,6 +16,10 @@ ICDB 数据库服务器即使命令行指向当前中心库,也可能服务其
强制客户端动作必须先在库外证据目录持久写入确认名单、库和进程创建身份,再核对当前进程句柄、用户 SID 和 Windows 会话;记录失败或身份变化时不执行。客户端结束后仍需独立证明库已释放,重新打开工程并核对版本,必要时从人工一致备份或原生历史版本恢复。不能把“进程已结束”解释为“ICDB 已修复”。具体步骤见 [操作规程](../SOP.md)。
原生 Backup/Restore/Repair 进行中时不强制结束。释放预览可查看后台桌面上的原生输出;只有当前窗口唯一可识别的取消按钮才提供确认请求,发送后仍需重新检查是否停止。输出或取消按钮无法确认时保留现场,不猜测原生命令。
## 原生工程数据库 Repair
1. 启动本机的 iCDB Project Backup,并打开实际报错工程对应的 `.prj`。本机可用 PowerShell 命令形式如下,工程路径需替换为自己的隔离副本:
@@ -0,0 +1,75 @@
{
"date": "2026-11-06",
"review_comments": [
275,
283,
286
],
"tests": {
"backend_full": {
"tests": 1385,
"errors": 0,
"failures": 0,
"skipped": 0,
"xml_file": "cbb-refresh-verify-795-backend-fixes-fixes.xml",
"xml_sha256": "b1af9d0025abbbbcf25fe134b02da980c9402dd22c0fa39e1f96b9f8124183ee"
},
"backend_read_guard": {
"tests": 9,
"errors": 0,
"failures": 0,
"skipped": 0,
"xml_file": "cbb-refresh-verify-795-backend-fixes-fixes-focused.xml",
"xml_sha256": "25dac539945d9ba71f2f9dafeb342e8f6110e094c62364369013e16e551b1f94"
},
"ui_integration": {
"tests": 29,
"errors": 0,
"failures": 0,
"skipped": 0,
"xml_file": "cbb-refresh-verify-795-ui-fixes-fixes.xml",
"xml_sha256": "9eeeff28c6fcd31d8f2e6d7fb38e0bdf01b0058ba7b7f9e5df2f173f71a4fca0"
},
"final_integrated": {
"tests": 1631,
"errors": 0,
"failures": 0,
"skipped": 0,
"xml_file": "cbb-refresh-verify-795-review-stack-fixes-full.xml",
"xml_sha256": "7d75049e4feecb4a6026062321d4a0fcb1c92e30f8f1ba23d11a4ea28ee19c9c"
},
"final_release_focused": {
"tests": 63,
"errors": 0,
"failures": 0,
"skipped": 0,
"xml_file": "cbb-refresh-verify-795-review-stack-fixes-focused.xml",
"xml_sha256": "469923faf0919ab2e3dffac183f2cb44a6b606aa15edacce92a88da1bde81424"
}
},
"compileall": "passed",
"git_diff_check": "passed",
"source_and_tests_sha256": "6fe6f02a3e0e731c4c9d2ff2f2c5e86e537139ef5e59f15441a9059522109526",
"post_full_suite_change": "GUI proof path comparison now uses lexical absolute paths, with no filesystem resolution; final 63 release regressions cover this one-line change. No further full-suite run was performed for this isolated UI comparison.",
"ui_preview": {
"file": "2026-11-06-release-preview.png",
"sha256": "e13645ed6b8234a2d46f6c462a262c7ef2092459c8e94f60a9fa273fd02c3613",
"mode": "offscreen simulated sessions; local Windows fonts loaded for visual inspection"
},
"red_regressions": {
"initial_backend": 6,
"initial_release": 12,
"ui_outcomes": 2,
"additional": "report storage, prelaunch evidence/probe timeout, cancel release propagation"
},
"scope": "Historical records trigger actual ownership proof; no automatic repair, server termination, native lock/address deletion or library backup.",
"native_cancel": "Only a unique enabled standard Cancel/取消 (IDCANCEL=2) on a current matching Project Backup window; identity, user/session, title, desktop and button rechecked; request does not prove cancellation.",
"not_verified": [
"actual Mentor native cancellation",
"actual Mentor force termination",
"field ICDB recovery",
"new frozen package",
"Windows 10",
"cross-machine shared-library concurrency"
]
}
+9 -1
View File
@@ -12,7 +12,7 @@
## 强制客户端操作的契约
支持 Expedition PCB、Library Manager、viewdraw 和 iCDB Project Backup。操作员须知晓客户端中其他工程可能一并退出、未保存更改可能丢失、写入中的工程可能需要恢复。确认名单先持久记录为库外 `consent.json`,失败则不执行;派发与进程句柄两处复核,PID 复用、用户或 Windows 会话变化时拒绝。
支持 Expedition PCB、Library Manager、viewdraw 和 iCDB Project Backup。操作员须知晓客户端中其他工程可能一并退出、未保存更改可能丢失、写入中的工程可能需要恢复。确认名单先持久记录为库外 `consent.json`,失败则不执行;派发处复核身份和预览范围,句柄处复核创建时间、完整映像、用户 SID、Windows 会话与原生活动;变化时拒绝。
数据库服务器可能服务同库其他用户,命令行归属不构成独占授权。本工具不会强制结束任何 ICDB 服务器;它仍活跃或库状态未知时保留 PARTIAL,不能通过结束客户端伪造释放或修复成功。
@@ -29,3 +29,11 @@ PR #3 comment 249 的修复通过服务器排除、确认记录失败、PID 复
此前 r10 的原生隔离检查与界面排队证据只证明该候选包已记录的打开/释放行为,不能当成新强制客户端功能的现场验收。现场服务器失联恢复、ICDB 自动修复、Windows 10 和共享库跨机器并发仍未验收。
规范:[SOP](../../SOP.md)、[ICDB 手动修复手册](../ICDB-MANUAL-REPAIR-AND-UPDATE.md)。依赖和拆分顺序见 PR #3 的独立审查链。
## 2026-11-06 审查修正
- 校验和管理统一复核历史占用,释放经过先留证;PASS 不再重复计入无法确认。
- 管理增加目标工程及共享依赖的写后差分,明确不覆盖其他 CBB 内容;报告失败不制造未完成原生事务。
- 释放逐项持久保存,快照异常保留已完成/未执行项;报告保存失败与独立释放证明分别展示。
- 预览与强制执行前读取原生活动,正在 Backup/Restore/Repair 或无法确认的备份客户端不可强制结束;显示后台提示、映像路径与桌面,并对唯一已识别的 Cancel/取消按钮提供确认请求。取消后的实际状态仍需复核。
- 本轮自动测试不包含真实 Mentor 的强制结束或原生取消验收;ICDB 自动修复继续暂停。
@@ -0,0 +1,11 @@
# 评论 286:释放留证与原生活动
释放前持久保存 NOT_STARTED 检查点,动作前保存 REQUESTING,动作后逐项保存实际状态,快照超时/中途异常也保留已执行和未执行项。保存失败停止继续发出动作;最终保存失败明确标为 PARTIAL/evidence_error,但独立且匹配当前库的释放证明仍被界面接受,不伪造占用。确认意图 consent_allowed 与实际 release_status 分别记录。
强制结束预览及精确句柄处重新读取原生窗口、进度和 Output;备份客户端进行中或状态无法确认时拒绝强制结束。普通客户端的保存模态窗口不直接等同于正在写库。服务器、导入器和未知身份仍排除。
窗口快照记录桌面,预览展示完整映像路径并提供原生提示/输出查看,支持原有保存选择。仅在当前用户/会话、精确进程身份匹配,且当前备份窗口唯一存在启用的 Cancel/取消(标准 IDCANCEL=2)控件时,提供单独确认的取消请求;执行前再次匹配标题、桌面、窗口和按钮并校验 PID。该请求复用串行准入和库外留证,不能当作已取消/已释放/已修复,也没有未知菜单或前台鼠标回退。没有可识别控件时入口禁用,保留状态供重新检查。
回归覆盖初次/末次快照超时、逐项记录、报告落盘失败、活动状态变化、原生取消按钮变化、确认与取消选择、已释放事实不被报告错误覆盖。测试使用临时文件和 fake 原生边界,没有终止或取消真实 Mentor 事务。原生取消在具体 Mentor 版本/现场窗口上的效果仍待隔离实机验收;ICDB 自动修复继续暂停。
回退代码不恢复已结束进程或原生事务;工程数据恢复仍需一致人工备份或明确选择的原生历史,不自动重放写操作。
+178 -55
View File
@@ -31,9 +31,33 @@ def force_block_reason(row):
if (row.get('force_user_confirmed') is not True or not row.get('owner_sid')
or not isinstance(row.get('session_id'), int)):
return '未确认属于当前用户和 Windows 会话,不允许强制结束'
activity = row.get('native_activity', {})
if activity.get('status') in ('ACTIVE', 'UNCONFIRMED'):
return activity.get('detail', '原生操作状态未确认')+';请查看进展或请求原生取消后重新检查'
if name == 'icdbprojectbackup.exe' and activity.get('status') != 'IDLE':
return '备份/恢复/修复状态未确认,请重新检查'
return ''
def native_activity(name, windows):
if any(w['class'] == 'UNCONFIRMED' for w in windows):
return {'status': 'UNCONFIRMED', 'detail': '原生窗口读取不完整'}
if any((name.casefold() == 'icdbprojectbackup.exe' and not w['enabled'])
or any(c['class'].casefold() == 'msctls_progress32' for c in w['children']) for w in windows):
return {'status': 'ACTIVE', 'detail': '原生窗口显示操作进行中'}
if name.casefold() == 'icdbprojectbackup.exe':
main = [w for w in windows if w['class'].startswith('Afx:')
and w['title'].startswith('iCDB Project Backup')]
output = main[0].get('output') if len(main) == 1 else None
if not isinstance(output, str) or not output.strip():
return {'status': 'UNCONFIRMED', 'detail': '无法确认备份/恢复/修复输出'}
active = list(re.finditer(r'(?i)repairing|restoring|backing up|creating (?:a )?backup', output))
if active and max(output.rfind('Backup information loaded correctly.'),
output.rfind('Repair project error [')) < active[-1].start():
return {'status': 'ACTIVE', 'detail': '原生备份/恢复/修复尚未确认结束', 'output': output}
return {'status': 'IDLE', 'detail': '未观察到进行中的原生操作'}
@contextmanager
def _process_handle(pid, *, terminate=False):
import win32api, win32con
@@ -94,7 +118,7 @@ def _process_windows(pids):
from .native_repair_ui import _native_output
result = {pid: [] for pid in pids}
observed = set()
def capture(hwnd, _=None):
def capture(hwnd, _=None, *, desktop_name='Default'):
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
if pid not in result or hwnd in observed or not win32gui.IsWindowVisible(hwnd):
return
@@ -111,6 +135,7 @@ def _process_windows(pids):
win32api.SetLastError(0)
win32gui.EnumChildWindows(hwnd, child, None)
window = {'hwnd': int(hwnd), 'title': win32gui.GetWindowText(hwnd),
'desktop': desktop_name,
'class': win32gui.GetClassName(hwnd), 'enabled': bool(win32gui.IsWindowEnabled(hwnd)),
'children': children, 'documents': documents, 'rect': list(win32gui.GetWindowRect(hwnd))}
if any(c['class'].casefold().startswith('richedit') for c in children):
@@ -136,7 +161,7 @@ def _process_windows(pids):
desktop = None
try:
desktop = win32service.OpenDesktop(name, 0, False, win32con.DESKTOP_READOBJECTS)
for hwnd in desktop.EnumDesktopWindows(): capture(int(hwnd))
for hwnd in desktop.EnumDesktopWindows(): capture(int(hwnd), desktop_name=name)
except Exception:
incomplete()
finally:
@@ -194,15 +219,36 @@ def _save_question(windows):
if (window['class'] == '#32770' and 'Expedition' in window['title']
and re.search(r'\bsave\b', text, re.I) and re.search(r'changes|modified', text, re.I)
and set(buttons) == {6, 7, 2}):
return {'hwnd': window['hwnd'], 'text': text, 'buttons': buttons}
return {'hwnd': window['hwnd'], 'text': text, 'buttons': buttons,
'desktop': window.get('desktop', '')}
return None
def _cancel_question(name, windows):
if name.casefold() != 'icdbprojectbackup.exe' or native_activity(name, windows)['status'] != 'ACTIVE':
return None
candidates = []
for window in windows:
if not (window['class'].startswith('Afx:') or window['class'] == '#32770'):
continue
if not window['title'].startswith('iCDB Project Backup') or not window['enabled']:
continue
for button in window['children']:
if (button['class'] == 'Button' and button.get('id') == 2 and button.get('enabled')
and button.get('text', '').replace('&', '').strip() in ('Cancel', '取消')):
candidates.append({'hwnd': window['hwnd'], 'button': button,
'title': window['title'],
'desktop': window.get('desktop', '')})
return candidates[0] if len(candidates) == 1 else None
def inspect_residual_sessions(library, *, block_names=()):
from .library_lock import _owner_matches_scope, blocker_path, checkpoint_record, has_retained_library
library = Path(library).resolve()
if library.suffix.casefold() != '.lmc' or not library.is_file():
raise ValueError('请选择有效的中心库 .lmc 文件')
if library.suffix.casefold() != '.lmc':
raise ValueError('请选择中心库 .lmc 文件')
if not library.is_file():
raise ValueError('中心库路径当前不可见,请检查文件是否存在及网络盘映射后重新检查')
blocks = tuple(dict.fromkeys(str(name) for name in block_names))
if any(not name or name in ('.', '..') or any(c in name for c in '\\/:*?"<>|') for name in blocks):
raise ValueError('残留检查的工程名称无效')
@@ -231,6 +277,14 @@ def inspect_residual_sessions(library, *, block_names=()):
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{error}')
item['project'] = _project_name(row, library) if row['scope_confirmed'] else '归属未确认'
item['prompt'] = _save_question(windows.get(row['pid'], [])) if row['scope_confirmed'] else None
observed = windows.get(row['pid'], [])
item['windows'] = observed
item['desktops'] = sorted({w.get('desktop', '') for w in observed if w.get('desktop')})
item['native_activity'] = native_activity(row['name'], observed)
item['cancel_prompt'] = (_cancel_question(row['name'], observed)
if row['scope_confirmed'] and item.get('force_user_confirmed') is True else None)
if any(name.startswith('Cbb') for name in item['desktops']) and not item['can_close']:
item['detail'] += ';窗口在后台,可查看原生提示并使用已提供的保存/取消操作'
item['force_block_reason'] = force_block_reason(item)
item['force_allowed'] = not item['force_block_reason']
if item['force_block_reason']:
@@ -308,6 +362,11 @@ def _force_close(row, *, stop=None):
if (not ownership['force_user_confirmed'] or
any(ownership[k] != row.get(k) for k in ('owner_sid', 'session_id'))):
return {'release_status': 'IDENTITY_CHANGED', 'detail': '用户或 Windows 会话已变化,未结束'}
activity = native_activity(row['name'], _process_windows({row['pid']}).get(row['pid'], []))
if reason := force_block_reason({**row, 'native_activity': activity}):
return {'release_status': 'WAITING', 'detail': reason, 'native_activity': activity}
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放,未强制结束'}
win32api.TerminateProcess(handle, 1)
exited = win32event.WaitForSingleObject(handle, 3000) == win32con.WAIT_OBJECT_0
return {'release_status': 'RELEASED' if exited else 'WAITING',
@@ -319,75 +378,139 @@ def _finish_library_release(library, evidence):
return release_retained_library(library, evidence)
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
def _request_native_cancel(row, *, stop=None):
"""Only click the exact currently visible Cancel control the user confirmed."""
import win32con, win32gui, win32process
if row.get('scope_confirmed') is not True:
raise ValueError('取消目标归属未确认,请重新检查')
fresh = next((r for r in query_process_snapshot() if r['pid'] == row['pid']), None)
if fresh is None or any(fresh.get(k) != row.get(k) for k in ('created', 'command', 'executable', 'name')):
raise ValueError('取消目标身份已变化,请重新检查')
with _process_handle(row['pid']) as handle:
if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}:
raise ValueError('取消目标身份已变化,请重新检查')
owner = _force_ownership(handle, row['pid'])
if not owner['force_user_confirmed'] or any(owner[k] != row.get(k) for k in ('owner_sid', 'session_id')):
raise ValueError('取消目标用户/会话已变化')
prompt = _cancel_question(row['name'], _process_windows({row['pid']}).get(row['pid'], []))
if not prompt or prompt != row.get('cancel_prompt'):
raise ValueError('原生取消按钮已变化,请重新检查')
button = prompt['button']
if win32process.GetWindowThreadProcessId(button['hwnd'])[1] != row['pid']:
raise ValueError('原生取消按钮归属已变化')
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止,未请求原生取消'}
win32gui.PostMessage(button['hwnd'], win32con.BM_CLICK, 0, 0)
return {'release_status': 'WAITING', 'detail': '已请求原生取消,需重新检查实际结果;未强制结束'}
def request_native_cancel(row, library, evidence_dir, *, stop=None):
# Reuse serialized admission, consent and incremental evidence for cancellation.
plan = {'library': str(library), 'sessions': [row]}
return release_residual_sessions(plan, evidence_dir, stop=stop, cancel_native=True)
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False):
library = Path(plan['library']).resolve()
root = Path(evidence_dir).resolve()/('sessions-'+uuid4().hex[:12])
if root.is_relative_to(library.parent) or library.parent.is_relative_to(root):
raise ValueError('释放记录需位于中心库之外')
root.mkdir(parents=True)
result = {'status': 'PARTIAL', 'library': str(library), 'sessions': [], 'force': force,
result = {'status': 'PARTIAL', 'library': str(library), 'sessions': [
{**row, 'release_status': 'NOT_STARTED', 'detail': '尚未执行',
'consent_allowed': not force_block_reason(row) if force else row.get('scope_confirmed') is True}
for row in plan['sessions']], 'force': force, 'cancel_native': cancel_native,
'evidence_path': str(root/'result.json'), 'previous_records': plan.get('previous_records', [])}
if force:
def save():
from .management import _write_json
try:
result['report_saved'] = True
_write_json(root/'result.json', result)
return True
except OSError as error:
result.update(status='PARTIAL', report_saved=False, evidence_error=str(error))
return False
if not save():
return result # No native actions without the initial checkpoint.
if force or cancel_native:
consent_path = root/'consent.json'
consent = {'version': 1, 'mode': 'force_document_clients', 'library': str(library),
consent = {'version': 1, 'mode': 'cancel_native' if cancel_native else 'force_document_clients', 'library': str(library),
'time_ns': time.time_ns(), 'sessions': [
{**row, 'force_allowed': not force_block_reason(row),
'cancel_allowed': bool(row.get('cancel_prompt')) and row.get('scope_confirmed') is True,
'force_block_reason': force_block_reason(row)} for row in plan['sessions']]}
with consent_path.open('x', encoding='utf-8') as stream:
json.dump(consent, stream, ensure_ascii=False, indent=2)
stream.flush(); os.fsync(stream.fileno())
result['consent_path'] = str(consent_path)
fresh = {r['pid']: r for r in query_process_snapshot()}
# Close native children first, so their supervisors can finish and drop leases.
ordered = sorted(plan['sessions'], key=lambda r: r['name'].casefold() in _WORKER_NAMES)
for original in ordered:
current = fresh.get(original['pid'])
outcome = {'release_status': 'RELEASED', 'detail': '已退出'}
if stop is not None and stop.is_set():
outcome = {'release_status': 'CANCELLED', 'detail': '已停止释放'}
elif current is not None:
from .library_lock import _owner_matches_scope
scoped = _owner_matches_scope(current, library, (library.parent,)) is True
if original.get('scope_confirmed') is not True or not scoped or original['pid'] == os.getpid():
outcome = {'release_status': 'WAITING', 'detail': '未在确认名单中证明属于当前库,未关闭;请重新检查'}
elif any(current.get(key) != original.get(key) for key in ('created', 'executable', 'command', 'name')):
outcome = {'release_status': 'IDENTITY_CHANGED', 'detail': '确认后进程身份已变化,未关闭'}
elif force and (reason := force_block_reason(original)):
outcome = {'release_status': 'WAITING', 'detail': reason, 'force_allowed': False}
else:
try: outcome = (_force_close if force else _request_close)(original, stop=stop)
except Exception as error:
outcome = {'release_status': 'WAITING', 'detail': str(error)}
result['sessions'].append({**original, **outcome})
by_pid = {r['pid']: r for r in result['sessions']}
result['sessions'] = [by_pid[r['pid']] for r in plan['sessions']]
# Launchers may exit only after the GUI child processed its close request.
after = {r['pid']: r for r in query_process_snapshot()}
remaining_windows = _process_windows({r['pid'] for r in result['sessions']
if r['release_status'] == 'WAITING' and r['pid'] in after})
for row in result['sessions']:
if row['release_status'] == 'WAITING' and row['pid'] not in after:
row.update(release_status='RELEASED', detail='已退出')
elif row['release_status'] == 'WAITING':
row['prompt'] = _save_question(remaining_windows.get(row['pid'], []))
if all(row['release_status'] == 'RELEASED' for row in result['sessions']) and not (stop and stop.is_set()):
try:
with consent_path.open('x', encoding='utf-8') as stream:
json.dump(consent, stream, ensure_ascii=False, indent=2)
stream.flush(); os.fsync(stream.fileno())
except OSError as error:
result['detail'] = f'确认记录保存失败,未执行:{error}'
save()
raise
result['consent_path'] = str(consent_path)
try:
fresh = {r['pid']: r for r in query_process_snapshot()}
blocks = plan.get('block_names', ())
roots = (tuple(library.parent/'ReusableBlocksLP'/b/'Work' for b in blocks)
+ (library.parent/'SymbolLibs',)) if blocks else (library.parent,)
# Close native children first; keep output rows in the original preview order.
ordered = sorted(result['sessions'], key=lambda r: r['name'].casefold() in _WORKER_NAMES)
for row in ordered:
current = fresh.get(row['pid'])
outcome = {'release_status': 'RELEASED', 'detail': '已退出'}
if stop is not None and stop.is_set():
outcome = {'release_status': 'CANCELLED', 'detail': '已停止释放'}
elif current is not None:
from .library_lock import _owner_matches_scope
scoped = _owner_matches_scope(current, library, roots) is True
if row.get('scope_confirmed') is not True or not scoped or row['pid'] == os.getpid():
outcome = {'release_status': 'WAITING', 'detail': '未在确认名单中证明属于当前库,未关闭;请重新检查'}
elif not row.get('created') or any(current.get(key) != row.get(key)
for key in ('created', 'executable', 'command', 'name')):
outcome = {'release_status': 'IDENTITY_CHANGED', 'detail': '确认后进程身份已变化,未关闭'}
elif force and (reason := force_block_reason(row)):
outcome = {'release_status': 'WAITING', 'detail': reason, 'force_allowed': False}
else:
row.update(release_status='REQUESTING', detail='正在请求原生操作,结果待确认')
if not save():
return result
try:
outcome = (_request_native_cancel(row, stop=stop) if cancel_native else
(_force_close if force else _request_close)(row, stop=stop))
except Exception as error:
outcome = {'release_status': 'WAITING', 'detail': str(error)}
row.update(outcome)
if not save():
return result # Preserve completed facts; stop further actions on storage failure.
after = {r['pid']: r for r in query_process_snapshot()}
remaining_windows = _process_windows({r['pid'] for r in result['sessions']
if r['release_status'] == 'WAITING' and r['pid'] in after})
for row in result['sessions']:
if row['release_status'] == 'WAITING' and row['pid'] not in after:
row.update(release_status='RELEASED', detail='已退出')
elif row['release_status'] == 'WAITING':
windows = remaining_windows.get(row['pid'], [])
row.update(prompt=_save_question(windows), windows=windows,
cancel_prompt=(_cancel_question(row['name'], windows)
if row.get('force_user_confirmed') is True else None),
native_activity=native_activity(row['name'], windows))
if all(row['release_status'] == 'RELEASED' for row in result['sessions']) and not (stop and stop.is_set()):
result['proof'] = _finish_library_release(library, root/'library-proof')
proof = result['proof']
if (proof.get('status') != 'RELEASE_CONFIRMED'
or Path(proof.get('library', '')).resolve() != library):
raise ValueError('释放证明与当前库不一致')
result['status'] = 'RELEASE_CONFIRMED'
except Exception as error:
result['detail'] = str(error)
try:
(root/'result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), 'utf-8')
except OSError as error:
result['evidence_error'] = str(error)
except BaseException as error:
result.update(status='PARTIAL', detail=f'{type(error).__name__}: {error}')
if not isinstance(error, Exception):
raise
finally:
save()
return result
def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False):
import win32con, win32event
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
@@ -401,7 +524,7 @@ def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
return {'status': 'PARTIAL', 'library': plan['library'], 'sessions': [
{**r, 'release_status': 'WAITING', 'detail': '其它批次尚在执行;请停止该批次后重试'}
for r in plan['sessions']], 'detail': '未取得执行通道,未关闭任何进程。'}
return _release_residual_sessions(plan, evidence_dir, stop=stop, force=force)
return _release_residual_sessions(plan, evidence_dir, stop=stop, force=force, cancel_native=cancel_native)
finally:
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
@@ -25,13 +25,13 @@ class ResidualReleaseDialog(QDialog):
self.pool = QThreadPool(self)
self.setWindowTitle('释放残留会话')
self.setModal(True)
self.resize(760, 350)
self.resize(1040, 400)
layout = QVBoxLayout(self)
self.message = QLabel('正在检查当前库关联的会话…')
self.message.setWordWrap(True)
layout.addWidget(self.message)
self.table = QTableWidget(0, 4)
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态'])
self.table = QTableWidget(0, 6)
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态', '窗口位置', '程序路径'])
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
self.table.setEditTriggers(QTableWidget.NoEditTriggers)
@@ -40,17 +40,22 @@ class ResidualReleaseDialog(QDialog):
self.refresh_button = QPushButton('重新检查')
self.confirm_button = QPushButton('确认释放')
self.prompt_button = QPushButton('处理保存提示…')
self.details_button = QPushButton('查看原生提示…')
self.cancel_native_button = QPushButton('请求原生取消…')
self.force_button = QPushButton('强制结束客户端…')
self.force_button.setEnabled(False)
self.prompt_button.setEnabled(False)
self.close_button = QPushButton('关闭')
for button in (self.refresh_button, self.confirm_button, self.prompt_button, self.force_button, self.close_button): buttons.addWidget(button)
for button in (self.refresh_button, self.confirm_button, self.details_button, self.prompt_button,
self.cancel_native_button, self.force_button, self.close_button): buttons.addWidget(button)
layout.addLayout(buttons)
self.refresh_button.clicked.connect(self.refresh)
self.confirm_button.clicked.connect(self.confirm_release)
self.close_button.clicked.connect(self.close)
self.prompt_button.clicked.connect(self.answer_prompt)
self.force_button.clicked.connect(self.force_release)
self.details_button.clicked.connect(self.show_native_details)
self.cancel_native_button.clicked.connect(self.cancel_native)
self.table.itemSelectionChanged.connect(self._update_prompt)
self.refresh()
@@ -60,6 +65,7 @@ class ResidualReleaseDialog(QDialog):
self.refresh_button.setEnabled(False)
self.prompt_button.setEnabled(False)
self.force_button.setEnabled(False)
self.cancel_native_button.setEnabled(False)
self.close_button.setText('停止释放')
self.worker = ServiceWorker(action)
self.worker.signals.succeeded.connect(completed)
@@ -83,7 +89,8 @@ class ResidualReleaseDialog(QDialog):
self.table.setRowCount(len(sessions))
for index, session in enumerate(sessions):
for column, value in enumerate((session.get('project', ''), session['name'],
session['pid'], session.get('detail', ''))):
session['pid'], session.get('detail', ''), ', '.join(session.get('desktops', [])),
session.get('image', session.get('executable', '')))):
self.table.setItem(index, column, QTableWidgetItem(str(value)))
if sessions: self.table.setCurrentCell(0, 0)
@@ -91,6 +98,65 @@ class ResidualReleaseDialog(QDialog):
row = self.table.currentRow()
rows = self.plan['sessions'] if self.plan else []
self.prompt_button.setEnabled(not self.busy and 0 <= row < len(rows) and bool(rows[row].get('prompt')))
self.cancel_native_button.setEnabled(not self.busy and 0 <= row < len(rows)
and bool(rows[row].get('cancel_prompt')))
self.details_button.setEnabled(0 <= row < len(rows))
def show_native_details(self):
if not self.plan: return
row = self.table.currentRow()
if row < 0: return
session = self.plan['sessions'][row]
box = QMessageBox(self); self.native_details = box
box.setWindowTitle('原生会话状态')
box.setText(f'{session["name"]} (PID {session["pid"]})\n'+session.get('detail', ''))
details = ['程序路径:'+session.get('image', session.get('executable', '')),
'窗口位置:'+', '.join(session.get('desktops', [])),
session.get('native_activity', {}).get('detail', '')]
for window in session.get('windows', []):
details.extend(['', window.get('title', ''), window.get('output', '') or ''])
details.extend(c.get('text', '') for c in window.get('children', [])
if c.get('class') == 'Static')
box.setDetailedText('\n'.join(details))
box.show()
def cancel_native(self):
if self.busy or not self.plan: return
row = self.table.currentRow()
if row < 0: return
session = self.plan['sessions'][row]
if not session.get('cancel_prompt'): return
answer = QMessageBox.question(self, '请求原生取消',
f'请求 {session["name"]} (PID {session["pid"]}) 当前显示的取消按钮?\n'
'取消后的工程状态仍需核对;不会强制结束进程。',
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if answer != QMessageBox.Yes: return
from cbb_refresh_verify.residual_sessions import request_native_cancel
self.before_release.emit(); self.stop.clear()
def execute():
action = lambda: request_native_cancel(session, self.library, self.evidence_dir, stop=self.stop)
return self.native_queue.run(action, stop=self.stop) if self.native_queue is not None else action()
def done(result):
self.message.setText(result.get('detail') or '\n'.join(r.get('detail', '') for r in result['sessions']))
confirmed = self._accept_release_proof(result)
if confirmed:
self.message.setText('已确认原生会话结束,当前库已释放。')
if result.get('evidence_error'):
self.message.setText(self.message.text()+'\n记录保存失败:'+result['evidence_error'])
elif not confirmed:
self._refresh_after = True
self._start(execute, done)
def _accept_release_proof(self, result):
proof = result.get('proof', {})
# Both paths were canonicalized by the worker; GUI comparison must not touch SMB.
if (proof.get('status') != 'RELEASE_CONFIRMED'
or Path(proof.get('library', '')).absolute() != self.library.absolute()
or any(r.get('release_status') != 'RELEASED' for r in result['sessions'])):
return False
self.plan = None
self.released.emit(proof)
return True
def answer_prompt(self):
if self.busy or not self.plan: return
@@ -153,13 +219,13 @@ class ResidualReleaseDialog(QDialog):
self.plan = {**plan, 'sessions': result['sessions']}
self._rows(result['sessions'])
count = sum(row['release_status'] == 'RELEASED' for row in result['sessions'])
if result['status'] == 'RELEASE_CONFIRMED':
self.plan = None
self.message.setText(f'已释放 {count} 个会话,旧占用记录已解除。')
self.released.emit(result['proof'])
if self._accept_release_proof(result):
self.message.setText(f'已释放 {count} 个会话,旧占用记录已解除。'
+ ('\n记录保存失败:'+result['evidence_error'] if result.get('evidence_error') else ''))
else:
self.message.setText(f'已释放 {count} 个会话,其余会话或库状态仍待确认。'
+ ('\n'+result['detail'] if result.get('detail') else '请处理原生窗口后重新检查。'))
+ ('\n'+result['detail'] if result.get('detail') else '可查看原生提示、处理保存或请求取消后重新检查。')
+ ('\n记录保存失败:'+result['evidence_error'] if result.get('evidence_error') else ''))
def execute():
action = lambda: release_residual_sessions(plan, self.evidence_dir, stop=self.stop, force=force)
return self.native_queue.run(action, stop=self.stop) if self.native_queue is not None else action()
+2 -1
View File
@@ -147,7 +147,7 @@ def test_backup_intermediate_success_does_not_allow_cooperative_close(output):
def test_force_requires_separate_explicit_argument_and_rechecks_identity(tmp_path, monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library = tmp_path/'lib.lmc'; library.touch()
process = row(10, tmp_path/'ReusableBlocksLP/A/Work/A.prj')
process = row(10, tmp_path/'ReusableBlocksLP/A/Work/A.prj', name='ExpeditionPCB.exe')
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process.copy()])
monkeypatch.setattr(sessions, '_process_identity', lambda r: {**OWNERSHIP, 'created_handle': 'old', 'image': r['executable']})
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
@@ -311,6 +311,7 @@ def test_supported_force_revalidates_exact_handle_before_termination(monkeypatch
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda handle, timeout:
win32con.WAIT_OBJECT_0 if timeout else win32con.WAIT_TIMEOUT)
monkeypatch.setattr(sessions, '_force_ownership', lambda *args: dict(OWNERSHIP))
monkeypatch.setattr(sessions, '_process_windows', lambda _: {10: []})
calls = []
monkeypatch.setattr(win32api, 'TerminateProcess', lambda handle, code: calls.append((handle, code)))
assert sessions._force_close({**process, 'created_handle': 'reused'})['release_status'] == 'IDENTITY_CHANGED'
+302
View File
@@ -0,0 +1,302 @@
import json
from contextlib import nullcontext
from pathlib import Path
import pytest
from test_residual_sessions import row, OWNERSHIP
@pytest.mark.parametrize('failure_stage', ['before_actions', 'after_actions'])
def test_snapshot_timeout_keeps_each_actual_release_result(tmp_path, monkeypatch, failure_stage):
from cbb_refresh_verify import residual_sessions as sessions
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
process = row(10, library.parent/'ReusableBlocksLP/A/Work/A.prj')
process.update(scope_confirmed=True, created_handle='creation', image=process['executable'], **OWNERSHIP)
snapshots = [0]
def snapshot():
snapshots[0] += 1
if snapshots[0] == (1 if failure_stage == 'before_actions' else 2):
raise TimeoutError('OWNER_QUERY_TIMEOUT')
return [process]
monkeypatch.setattr(sessions, 'query_process_snapshot', snapshot)
monkeypatch.setattr(sessions, '_request_close', lambda *a, **kw:
{'release_status': 'RELEASED', 'detail': 'closed'})
monkeypatch.setattr(sessions, '_finish_library_release', lambda *a: pytest.fail('snapshot failed'))
plan = {'library': str(library), 'sessions': [process]}
result = sessions._release_residual_sessions(plan, tmp_path/'evidence')
saved = json.loads(Path(result['evidence_path']).read_text('utf-8'))
assert saved['status'] == 'PARTIAL' and 'OWNER_QUERY_TIMEOUT' in saved['detail']
assert saved['sessions'][0]['release_status'] == ('NOT_STARTED' if failure_stage == 'before_actions' else 'RELEASED')
def test_first_outcome_is_durable_before_next_session_action(tmp_path, monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
processes = [dict(row(pid, library.parent/f'ReusableBlocksLP/{pid}/Work/a.prj'),
scope_confirmed=True) for pid in (10, 20)]
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: processes)
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
def close(process, **kwargs):
if process['pid'] == 20:
report = json.loads(next((tmp_path/'evidence').glob('sessions-*/result.json')).read_text('utf-8'))
assert report['sessions'][0]['release_status'] == 'RELEASED'
assert report['sessions'][1]['release_status'] == 'REQUESTING'
return {'release_status': 'RELEASED', 'detail': 'closed'}
monkeypatch.setattr(sessions, '_request_close', close)
monkeypatch.setattr(sessions, '_finish_library_release', lambda *a:
{'status': 'RELEASE_CONFIRMED', 'library': str(library)})
result = sessions._release_residual_sessions({'library': str(library), 'sessions': processes}, tmp_path/'evidence')
assert result['status'] == 'RELEASE_CONFIRMED'
def test_report_storage_failure_does_not_claim_complete_or_undo_release_proof(tmp_path, monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [])
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
monkeypatch.setattr(sessions, '_finish_library_release', lambda *a:
{'status': 'RELEASE_CONFIRMED', 'library': str(library)})
original = Path.open
writes = []
def deny(path, *args, **kwargs):
if path.name == 'result.pending':
writes.append(1)
if len(writes) > 1: raise PermissionError('disk full after release')
return original(path, *args, **kwargs)
monkeypatch.setattr(Path, 'open', deny)
result = sessions._release_residual_sessions({'library': str(library), 'sessions': []}, tmp_path/'evidence')
assert result['status'] == 'PARTIAL' and 'disk full' in result['evidence_error']
assert result['proof']['status'] == 'RELEASE_CONFIRMED'
@pytest.mark.parametrize('output', [None, 'Repairing project\nRepair backup created successfully.',
'Restoring project', 'Backing up project'])
def test_force_rechecks_native_backup_activity_before_termination(monkeypatch, output):
import win32api, win32con, win32event
from cbb_refresh_verify import residual_sessions as sessions
process = dict(row(10, 'C:/library/A.prj'), scope_confirmed=True,
created_handle='creation', image='C:/Mentor/iCDBProjectBackup.exe',
native_activity={'status': 'IDLE'}, **OWNERSHIP)
monkeypatch.setattr(sessions, '_process_handle', lambda *a, **kw: nullcontext(123))
monkeypatch.setattr(sessions, '_handle_identity', lambda _: {k:process[k] for k in ('created_handle','image')})
monkeypatch.setattr(sessions, '_force_ownership', lambda *a: dict(OWNERSHIP))
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *a: win32con.WAIT_TIMEOUT)
monkeypatch.setattr(sessions, '_process_windows', lambda _: {10: [
{'hwnd': 100, 'class': 'Afx:main', 'title': 'iCDB Project Backup - A',
'enabled': True, 'children': [], 'output': output, 'desktop': 'CbbRepair_A'}]})
monkeypatch.setattr(win32api, 'TerminateProcess', lambda *a: pytest.fail('interrupted Backup/Repair'))
result = sessions._force_close(process)
assert result['release_status'] == 'WAITING'
assert result['native_activity']['status'] in ('ACTIVE', 'UNCONFIRMED')
def test_inspection_exposes_private_desktop_and_disables_force_for_active_backup(tmp_path, monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
process = row(10, library.parent/'ReusableBlocksLP/A/Work/A.prj')
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
monkeypatch.setattr(sessions, '_process_identity', lambda r:
dict(created_handle='creation', image=r['executable'], **OWNERSHIP))
monkeypatch.setattr(sessions, '_process_windows', lambda _: {10:[
{'hwnd':100,'class':'Afx:main','title':'iCDB Project Backup - A','enabled':True,
'children':[],'output':'Repairing project','desktop':'CbbRepair_A'}]})
preview = sessions.inspect_residual_sessions(library)['sessions'][0]
assert preview['force_allowed'] is False
assert preview['desktops'] == ['CbbRepair_A']
assert preview['native_activity']['status'] == 'ACTIVE'
def test_saved_prompt_from_private_desktop_remains_actionable():
from cbb_refresh_verify.residual_sessions import _save_question
prompt = _save_question([{'hwnd':100,'class':'#32770','title':'Expedition PCB',
'desktop':'CbbVerify_A','children':[{'class':'Static','text':'Save changes to modified design?'},
*[{'class':'Button','id':code,'hwnd':code,'enabled':True} for code in (6,7,2)]]}])
assert prompt['desktop'] == 'CbbVerify_A' and set(prompt['buttons']) == {6,7,2}
def test_native_cancel_requires_same_current_control_and_exact_owned_process(monkeypatch):
import win32con, win32event, win32gui, win32process
from cbb_refresh_verify import residual_sessions as sessions
process = dict(row(10, 'C:/library/A.prj'), scope_confirmed=True,
created_handle='creation', image='C:/Mentor/iCDBProjectBackup.exe', **OWNERSHIP)
window = {'hwnd':100,'class':'Afx:main','title':'iCDB Project Backup - A','enabled':True,
'output':'Backing up project','desktop':'CbbRepair_A',
'children':[{'class':'Button','id':2,'text':'Cancel','enabled':True,'hwnd':102}]}
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
monkeypatch.setattr(sessions, '_process_handle', lambda *a,**kw: nullcontext(123))
monkeypatch.setattr(sessions, '_handle_identity', lambda _: {k:process[k] for k in ('created_handle','image')})
monkeypatch.setattr(sessions, '_force_ownership', lambda *a: dict(OWNERSHIP))
monkeypatch.setattr(sessions, '_process_windows', lambda _: {10:[window]})
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *a: win32con.WAIT_TIMEOUT)
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (1,10))
clicked=[]; monkeypatch.setattr(win32gui, 'PostMessage', lambda *a: clicked.append(a))
process['cancel_prompt']={'hwnd':100,'button':dict(window['children'][0]),
'title':window['title'],'desktop':'CbbRepair_A'}
result = sessions._request_native_cancel(process)
assert result['release_status'] == 'WAITING' and clicked == [(102, win32con.BM_CLICK, 0, 0)]
window['children'][0]['text'] = 'Restore'
with pytest.raises(ValueError, match='取消'):
sessions._request_native_cancel(process)
assert len(clicked)==1
def test_ui_reports_missing_evidence_but_propagates_valid_library_release(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
library = tmp_path/'lib.lmc'
monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda *_:
{'library':str(library),'sessions':[]})
proof = {'status':'RELEASE_CONFIRMED','library':str(library)}
monkeypatch.setattr(library_lock, 'release_residual_sessions', lambda *a,**kw:
{'status':'PARTIAL','sessions':[],'proof':proof,'evidence_error':'disk full'})
dialog = ResidualReleaseDialog(library, tmp_path/'evidence'); qtbot.addWidget(dialog)
released = []; dialog.released.connect(released.append)
qtbot.waitUntil(lambda: not dialog.busy)
dialog.confirm_button.click(); qtbot.waitUntil(lambda: not dialog.busy)
assert released == [proof]
assert '记录' in dialog.message.text() and 'disk full' in dialog.message.text()
def test_ui_native_cancel_is_explicit_and_details_are_readable(qtbot, tmp_path, monkeypatch):
from PySide6.QtWidgets import QMessageBox
from cbb_refresh_verify import library_lock, residual_sessions
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
library = tmp_path/'lib.lmc'
process = {'name':'iCDBProjectBackup.exe','pid':10,'detail':'备份进行中',
'image':'C:/Mentor/iCDBProjectBackup.exe','desktops':['CbbRepair_A'],
'native_activity':{'status':'ACTIVE','detail':'正在备份'},'cancel_prompt':{'hwnd':100},
'windows':[{'title':'iCDB Project Backup - A','output':'Backing up project','children':[]}]}
monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda *_:
{'library':str(library),'sessions':[process]})
calls=[]
monkeypatch.setattr(residual_sessions,'request_native_cancel',lambda *a,**kw:
calls.append(a[0]) or {'status':'PARTIAL','sessions':[{'detail':'已请求取消'}]})
dialog=ResidualReleaseDialog(library,tmp_path/'evidence');qtbot.addWidget(dialog)
qtbot.waitUntil(lambda:not dialog.busy)
assert dialog.cancel_native_button.isEnabled() and not dialog.force_button.isEnabled()
dialog.details_button.click()
assert 'Backing up project' in dialog.native_details.detailedText()
assert 'CbbRepair_A' in dialog.native_details.detailedText()
dialog.native_details.close()
monkeypatch.setattr(QMessageBox,'question',lambda *a:QMessageBox.No)
dialog.cancel_native_button.click();assert calls==[]
monkeypatch.setattr(QMessageBox,'question',lambda *a:QMessageBox.Yes)
dialog.cancel_native_button.click();qtbot.waitUntil(lambda:not dialog.busy)
assert calls==[process]
def test_force_can_resume_after_backup_finishes_and_preview_is_refreshed(tmp_path, monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library=tmp_path/'library/lib.lmc';library.parent.mkdir();library.touch()
process=row(10,library.parent/'ReusableBlocksLP/A/Work/A.prj')
monkeypatch.setattr(sessions,'query_process_snapshot',lambda:[process])
monkeypatch.setattr(sessions,'_process_identity',lambda r:
dict(created_handle='creation',image=r['executable'],**OWNERSHIP))
window={'hwnd':100,'class':'Afx:main','title':'iCDB Project Backup - A','enabled':True,
'children':[],'output':'Repairing project'}
monkeypatch.setattr(sessions,'_process_windows',lambda _:{10:[window]})
assert not sessions.inspect_residual_sessions(library)['sessions'][0]['force_allowed']
window['output']+='\nBackup information loaded correctly.'
assert sessions.inspect_residual_sessions(library)['sessions'][0]['force_allowed']
def test_native_cancel_records_consent_before_sending_any_message(tmp_path, monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library=tmp_path/'library/lib.lmc';library.parent.mkdir();library.touch()
process=dict(row(10,library.parent/'ReusableBlocksLP/A/Work/A.prj'),
scope_confirmed=True,cancel_prompt={'hwnd':100})
evidence=tmp_path/'evidence'
monkeypatch.setattr(sessions,'query_process_snapshot',lambda:[process])
monkeypatch.setattr(sessions,'_process_windows',lambda _:{})
def cancel(actual, **kwargs):
record=json.loads(next(evidence.glob('sessions-*/consent.json')).read_text('utf-8'))
assert record['mode']=='cancel_native' and record['sessions'][0]['pid']==actual['pid']
return {'release_status':'WAITING','detail':'cancel requested'}
monkeypatch.setattr(sessions,'_request_native_cancel',cancel)
result=sessions.request_native_cancel(process,library,evidence)
assert result['cancel_native'] and Path(result['consent_path']).is_file()
assert result['sessions'][0]['detail']=='cancel requested'
def test_missing_initial_checkpoint_prevents_all_close_actions(tmp_path, monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library=tmp_path/'library/lib.lmc';library.parent.mkdir();library.touch()
process=dict(row(10,library.parent/'A.prj'),scope_confirmed=True)
original=Path.open
def denied(path,*args,**kwargs):
if path.name=='result.pending':raise PermissionError('no storage')
return original(path,*args,**kwargs)
monkeypatch.setattr(Path,'open',denied)
monkeypatch.setattr(sessions,'_request_close',lambda *a,**kw:pytest.fail('unrecorded close'))
result=sessions._release_residual_sessions({'library':str(library),'sessions':[process]},tmp_path/'evidence')
assert result['status']=='PARTIAL' and result['sessions'][0]['release_status']=='NOT_STARTED'
def test_native_cancel_completion_propagates_actual_release_to_parent(qtbot,tmp_path,monkeypatch):
from PySide6.QtWidgets import QMessageBox
from cbb_refresh_verify import library_lock,residual_sessions
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
library=tmp_path/'lib.lmc'
process={'name':'iCDBProjectBackup.exe','pid':10,'cancel_prompt':{'hwnd':100}}
monkeypatch.setattr(library_lock,'inspect_residual_sessions',lambda *_:
{'library':str(library),'sessions':[process]})
proof={'status':'RELEASE_CONFIRMED','library':str(library)}
monkeypatch.setattr(residual_sessions,'request_native_cancel',lambda *a,**kw:
{'status':'RELEASE_CONFIRMED','sessions':[{**process,'release_status':'RELEASED'}],'proof':proof})
monkeypatch.setattr(QMessageBox,'question',lambda *a:QMessageBox.Yes)
dialog=ResidualReleaseDialog(library,tmp_path/'evidence');qtbot.addWidget(dialog)
released=[];dialog.released.connect(released.append)
qtbot.waitUntil(lambda:not dialog.busy)
dialog.cancel_native_button.click();qtbot.waitUntil(lambda:not dialog.busy)
assert released==[proof] and dialog.plan is None
def test_interruption_after_request_is_not_recorded_as_never_started(tmp_path,monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library=tmp_path/'library/lib.lmc';library.parent.mkdir();library.touch()
process=dict(row(10,library.parent/'A.prj'),scope_confirmed=True)
evidence=tmp_path/'evidence'
monkeypatch.setattr(sessions,'query_process_snapshot',lambda:[process])
observed=[]
def interrupted(*a,**kw):
record=json.loads(next(evidence.glob('sessions-*/result.json')).read_text('utf-8'))
observed.append(record['sessions'][0]['release_status'])
raise KeyboardInterrupt()
monkeypatch.setattr(sessions,'_request_close',interrupted)
with pytest.raises(KeyboardInterrupt):
sessions._release_residual_sessions({'library':str(library),'sessions':[process]},evidence)
assert observed==['REQUESTING']
saved=json.loads(next(evidence.glob('sessions-*/result.json')).read_text('utf-8'))
assert saved['sessions'][0]['release_status']=='REQUESTING' and saved['status']=='PARTIAL'
def test_stop_during_native_activity_read_prevents_force_termination(monkeypatch):
from threading import Event
import win32api,win32con,win32event
from cbb_refresh_verify import residual_sessions as sessions
process=dict(row(10,'C:/library/A.prj',name='ExpeditionPCB.exe'),scope_confirmed=True,
created_handle='creation',image='C:/Mentor/ExpeditionPCB.exe',**OWNERSHIP)
stop=Event()
monkeypatch.setattr(sessions,'_process_handle',lambda *a,**kw:nullcontext(123))
monkeypatch.setattr(sessions,'_handle_identity',lambda _:{k:process[k] for k in ('created_handle','image')})
monkeypatch.setattr(sessions,'_force_ownership',lambda *a:dict(OWNERSHIP))
monkeypatch.setattr(win32event,'WaitForSingleObject',lambda *a:win32con.WAIT_TIMEOUT)
def windows(*args):stop.set();return {10:[]}
monkeypatch.setattr(sessions,'_process_windows',windows)
monkeypatch.setattr(win32api,'TerminateProcess',lambda *a:pytest.fail('force continued after stop'))
assert sessions._force_close(process,stop=stop)['release_status']=='CANCELLED'
def test_gui_release_proof_comparison_does_not_probe_network_filesystem(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify import library_lock
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
library=tmp_path/'lib.lmc'
monkeypatch.setattr(library_lock,'inspect_residual_sessions',lambda *_:
{'library':str(library),'sessions':[]})
dialog=ResidualReleaseDialog(library,tmp_path/'evidence');qtbot.addWidget(dialog)
qtbot.waitUntil(lambda:not dialog.busy)
with monkeypatch.context() as guard:
guard.setattr(Path,'resolve',lambda *a,**kw:pytest.fail('GUI tried filesystem resolution'))
assert dialog._accept_release_proof({'sessions':[],'proof':{
'status':'RELEASE_CONFIRMED','library':str(library)}})