fix: inspect native ICDB occupancy before bounded repair

This commit is contained in:
阿白叔 committed 2026-11-04 12:26:09 +08:00
1 parent cb1326688b
commit e14a864b37
17 files changed
+617 -153

No files matched your search

@@ -0,0 +1,52 @@
# 原生占用检查候选:完整修复验收失败
本记录更新此前 `2026-11-04-icdb-review-fixes.md` 的维护入口说明。工单 #2 保持未解决;本候选不合并、不发布正式版、不关闭工单。
## 本轮改动
- 维护入口先调用原生 iCDB Project Backup 的工程加载/占用检查,不先打开 PCB。旧 `sAddress.adr` 只是待核实证据,不再单凭它阻断检查,也不删除或改写该文件。
- 仅本轮 Output 明确绑定目标工程、目标数据库,确认未占用且要求 Repair,原生检查正常退出,并再次通过工程身份和占用检查,才调用一次 Repair。其他工程、共享库、未知错误或未释放会话均阻止后续操作。
- WMI 占用查询在独立只读辅助进程执行,最多 10 秒;超时是未知,不是空闲。文件扫描在后台运行并支持取消。原生准备阶段预算 60 秒,另加原生操作超时及 5 秒监督余量;取消后再次核对,避免迟到启动。
- 停止请求传入维护流程,原生写入不强杀;释放未确认时停止后续批次。仅检查结果使用 `CHECKED`,不计入修复成功。READY 即使已勾选也不进入维护。
- 精确的 verified/once-verified Reusable Block BackAnnotate 拒绝归类为 `CBB_REIMPORT_REQUIRED`,不再被后续释放告警掩盖。该分类不会执行重导入,也不改变 `safe_to_continue`;原生错误及释放错误都保留在报告中。
- 历史版本选择继续通过应用弹窗;只有完整校验及权威 READY 通过才允许成功。历史恢复仍标记版本待核对。
## 隔离环境实测
证据根目录:`diagnostics/native-occupancy-20261104/`(含本机路径和原生日志,不纳入 Git)。测试通过实际应用维护按钮和版本选择弹窗完成,没有以手工分阶段调用替代验收。
一致副本包含 38,954 个文件、1,220,129,120 字节。复制期间源文件集合/大小/修改时间一致,253 个主要文件 SHA-256 核对通过;追加目标 PRJ/PCB 后,最终再次核对原库的 255 个已记录文件,全部未变化。原库未执行写操作。
最终尝试 `source-ui-fourth`,目标 `1GPHY_8212`:
1. 原生检查明确返回未占用,并指出当前数据库不一致、要求 Repair。
2. 原生 Repair 创建自身备份,完成数据库检查、整理和关闭,返回 `Project should now be fixed.`,并确认退出释放。
3. 应用弹窗选择用户已授权的最后手动保存版本(2026/9/24 15:15),重新打开同一工程。
4. SynchCES、LoadCES 通过;BackAnnotation 为 Required,实际调用被 Mentor 拒绝:`Back Annotation is not allowed on verified (or once verified) Reusable Blocks.`
5. 未完成保存与 READY 校验。最终 **FAIL / UNKNOWN / REPAIR_VALIDATION_FAILED**,`validation_passed=false`、`safe_to_continue=false`。原生 Repair 完成不等于整体修复成功。
6. 失败关闭助手记录 Close/Quit 成功,但最终释放检查仍看到 PID 21968,因此保留检查点并停止批次。后续只读复查该原生进程已消失;这不追溯修改原失败结果。测试应用关闭结果对话框后正常退出。
实测界面响应记录:614 次 WM_NULL 检查,200 毫秒超时 0 次,最大约 78 毫秒。这只证明本次运行的界面响应,不保证任意网络故障下所有系统调用可立即取消。
关键证据:
- `source-ui-fourth/acceptance.json`:`accepted=false`。
- `source-ui-fourth/evidence/maintenance-43479c21aa59/result.json`:完整维护结果。
- `source-ui-fourth/evidence/maintenance-43479c21aa59/native-repair/repair-result.json`:原生 Repair 证据。
- `source-ui-fourth/evidence/verify-99a675e0399c/`:重新打开、集成拒绝、正常关闭及释放未确认记录。
- `source-ui-fourth/ui-responsiveness.json`、`version-choice.png`、`finished.png`。
- `source-final-check.json`:原库 255 个哈希均保持不变。
## 代码与冻结候选验证
- `python -X utf8 -m pytest -q --tb=short`:**1,176 passed**,302.56 秒;1 条既有 pywinauto STA 警告。
- `compileall`、`git diff --check`、独立只读代码审查通过。
- PyInstaller 构建通过;冻结程序创建主窗口及正常退出通过,新 `--owner-probe` 在冻结程序中返回有效结果。
- EXE 内 11 个变更模块与当前源码编译结果一致。验证脚本及结果在证据根目录的 `check_candidate.py`、`frozen-result.json`。
- 本地候选目录:`dist/issue2-native-occupancy-candidate/`。冻结包完整故障修复链路未执行,不能称为已验收的修复包。
## 尚未解决
已验证或曾验证的 CBB 注册状态限制仍阻止 BackAnnotate。不能跳过 Required 操作、强行设置 READY 或把移除/重导入偷偷加入 ICDB Repair。此前隔离试验的独立重导入路径见 `2026-11-03-field-feedback.md`,其行为涉及库条目更新,不能据此宣称本次无损修复通过。
本轮没有完成 Windows 10/11 双系统验收;冻结包的完整现场故障链路仍需验证。程序测试和启动冒烟均不能代替上述失败的实际验收。
+4
View File
@@ -50,6 +50,7 @@ def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--repair-worker', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--owner-probe', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--management-worker', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
@@ -60,6 +61,9 @@ def main(argv: Sequence[str] | None = None) -> int:
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS)
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
args = parser.parse_args(list(argv) if argv is not None else None)
if args.owner_probe:
from .owner_probe import owner_probe_main
return owner_probe_main(args.owner_probe)
if args.management_worker:
from .native_management import management_worker_main
return management_worker_main(args.management_worker)
+1 -1
View File
@@ -16,7 +16,7 @@ def maintenance_counts(results):
and attempt.get('native_status') == 'REPAIRED'
and attempt.get('validation_passed') is False for attempt in attempts)
return {'total': len(results), 'passed': sum(r.status == 'PASS' for r in results),
'checked_without_repair': sum(r.status == 'PASS' and not r.recovery_attempts 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,
+69 -57
View File
@@ -13,7 +13,7 @@ from uuid import uuid4
def assert_native_idle():
import win32com.client
from .owner_probe import query_owners
from .native_management import _retained_workers
from .native_export_guard import assert_retained_exports_idle
from .native_engineering_identity import _OWNER_NAMES
@@ -23,19 +23,15 @@ def assert_native_idle():
names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'viewdraw.exe', 'iCDBProjectBackup.exe',
'ReuseBlockImporter.exe', 'CleanWGLib.exe', 'cscript.exe', 'wscript.exe',
'python.exe', 'pythonw.exe', 'CbbRefreshVerify.exe', *sorted(_OWNER_NAMES))
service = win32com.client.GetObject('winmgmts:')
query = 'SELECT ProcessId, Name, CommandLine FROM Win32_Process WHERE ' + ' OR '.join(
f"Name='{name}'" for name in names)
owners = []
for item in service.ExecQuery(query):
if int(item.ProcessId) == os.getpid():
for item in query_owners(names):
if item['pid'] == os.getpid():
continue
name, command = str(item.Name).casefold(), str(item.CommandLine or '').casefold()
name, command = item['name'].casefold(), item['command'].casefold()
automation = name in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe')
if not automation or not command or any(flag in command for flag in (
'--verify-worker', '--repair-worker', '--management-worker')):
owners.append({'pid': int(item.ProcessId), 'name': str(item.Name),
'command': str(item.CommandLine or '')})
owners.append(item)
if owners:
raise ValueError(f'MAINTENANCE_OWNER_ACTIVE: 请正常关闭原生程序/操作助手:{owners}')
@@ -47,11 +43,11 @@ def address_snapshot(paths):
for path in paths}
def _scoped_addresses(request):
def _scoped_addresses(request, *, check=None):
from .scoped_manifest import scan_tree
root = Path(request.lmc_file).parent
addresses = []
for path in scan_tree(root):
for path in scan_tree(root, check=check):
if path.name.casefold() != 'saddress.adr':
continue
parts = tuple(part.casefold() for part in path.relative_to(root).parts)
@@ -85,7 +81,7 @@ def maintenance_project_files(project, pcb):
return (project,)
def select_maintenance_target(request):
def select_maintenance_target(request, *, check=None):
from .verify_runner import preflight
from .backup_recovery import _project_text
from .native_repair import RepairTarget
@@ -93,7 +89,7 @@ def select_maintenance_target(request):
if request.maintenance is not True:
raise ValueError('MAINTENANCE_INTENT_REQUIRED')
project, pcb = preflight(request)
scan_tree(project.parent)
scan_tree(project.parent, check=check)
candidates = []
for candidate in maintenance_project_files(project, pcb):
if not candidate.is_file():
@@ -113,7 +109,7 @@ def select_maintenance_target(request):
if not (database/'icdb.dat').is_file():
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 缺少 icdb.dat')
candidates.append(RepairTarget(candidate, candidate.parent/'database'))
addresses = _scoped_addresses(request)
addresses = _scoped_addresses(request, check=check)
if not addresses:
# A crashed project may retain its internal open state after the server
# advertisement disappears. Explicit maintenance must still inspect it.
@@ -133,11 +129,15 @@ def select_maintenance_target(request):
@contextmanager
def maintenance_target_guard(request, expected=None):
def maintenance_target_guard(request, expected=None, *, stop=None):
"""Simultaneously hold native database files, preserving every address."""
import win32con, win32file
from .scoped_manifest import scan_tree, hash_file
target, project, pcb, addresses = select_maintenance_target(request)
def check():
if stop is not None and stop.is_set():
raise ValueError('MAINTENANCE_CANCELLED: 已取消占用检查')
check()
target, project, pcb, addresses = select_maintenance_target(request, check=check)
baseline = address_snapshot(addresses)
context = {'library': str(Path(request.lmc_file).resolve()), 'block': request.block_name,
'project': str(target.project.resolve()), 'database': str(target.database.resolve()),
@@ -147,16 +147,18 @@ def maintenance_target_guard(request, expected=None):
if expected is not None and context != expected:
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 目标或地址记录在检查后变化')
assert_native_idle()
entries = scan_tree(Path(request.lmc_file).parent)
files = [path for path in entries if path.is_file() and (
path.suffix.casefold() == '.lmc' or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt'))]
check()
entries = scan_tree(Path(request.lmc_file).parent, check=check)
files = [path for path in entries if (
path.suffix.casefold() == '.lmc' or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt')) and path.is_file()]
with ExitStack() as stack:
for path in files:
check()
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
assert_native_idle()
current_addresses = _scoped_addresses(request)
current_addresses = _scoped_addresses(request, check=check)
if address_snapshot(current_addresses) != baseline:
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 地址记录在检查期间变化')
yield {'target': target, 'context': context, 'project': project, 'pcb': pcb}
@@ -176,7 +178,7 @@ def maintenance_needed(request):
return bool(unreleased_addresses(request.lmc_file, project, pcb))
def run_existing_address_maintenance(request, *, verify, progress=None):
def run_existing_address_maintenance(request, *, verify, 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)
@@ -199,45 +201,51 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
record['result'] = asdict(result)
report.write_text(json.dumps(record, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
return result
def native_event(event):
emit(event['stage'], **{key: value for key, value in event.items() if key != 'stage'})
try:
if stop is not None and stop.is_set():
return save(VerifyResult('CANCELLED', stderr='维护已取消,未启动原生操作'))
emit('preflight', detail='正在核对工程、库文件和进程占用;可请求取消')
lease = LibraryLock.for_maintenance(request.lmc_file, root/'takeover',
lambda: maintenance_target_guard(request), safe_to_release=lambda: owner_safe)
lambda: maintenance_target_guard(request, stop=stop), safe_to_release=lambda: owner_safe)
with lease:
checked = lease.maintenance_proof
target, context = checked['target'], checked['context']
record['maintenance_context'] = context
emit('icdb_diagnosis_start', detail='已取得库锁,检查原生启动;不执行集成或保存')
diagnostic_request = replace(request, maintenance=False, auto_repair=False,
diagnostic_only=True, post_repair_proof=None, native_lm_verify=False,
interactive_input=False, libspec='', dms_login_config='', evidence_dir=root/'diagnosis')
diagnosis = verify(diagnostic_request)
record['preflight_diagnosis'] = asdict(diagnosis)
evidence = diagnosis.evidence_path
if (evidence is None or not Path(evidence).is_file()
or not Path(evidence).resolve().is_relative_to((root/'diagnosis').resolve())):
raise ValueError('ICDB_DIAGNOSIS_UNCONFIRMED: 缺少本轮诊断证据,未调用 Repair')
owner_safe = diagnosis.safe_to_continue
if diagnosis.status == 'PASS' and owner_safe:
emit('icdb_diagnosis_complete', detail='本轮启动未发现 ICDB 故障,未调用 Repair')
return save(replace(diagnosis, library_flag='UNKNOWN', library_flag_detail='',
stdout='ICDB 启动检查通过;未执行集成、保存或原生 Repair。', recovery_attempts=()))
if diagnosis.error_category != 'ICDB_REPAIR_REQUIRED' or diagnosis.status in ('BLOCKED', 'TIMEOUT'):
return save(replace(diagnosis, status='BLOCKED' if diagnosis.status == 'PASS' else diagnosis.status,
stderr=(diagnosis.stderr + '\n未确认 ICDB 故障,未调用原生 Repair。').strip(),
recovery_attempts=()))
# Only this run's structured native lost-session diagnosis may
# authorize Repair, and it must identify this exact database.
fault = json.loads((Path(evidence).parent/'diagnostics/icdb-recovery.json').read_text('utf-8'))
if (fault.get('error_code') != 'ICDB_REPAIR_REQUIRED' or fault.get('scope') != 'project'
or not fault.get('session') or not fault.get('database_path')
or Path(fault['database_path']).resolve() != target.database.resolve()):
raise ValueError('ICDB_DIAGNOSIS_UNCONFIRMED: 故障证据未绑定当前数据库')
record['confirmed_fault'] = fault
# A diagnostic worker may have failed to release its native owner.
# Recheck every owner and the exact target before dispatch.
with maintenance_target_guard(request, context): pass
owner_safe = False
emit('icdb_diagnosis_confirmed', detail='本轮原生日志已确认目标数据库失联,进入 Repair')
if stop is not None and stop.is_set():
raise ValueError('MAINTENANCE_CANCELLED: 已取消,未启动原生检查')
emit('icdb_ownership_check', detail='调用原生 Project Backup 检查占用及恢复要求,不执行 Repair')
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
from .native_occupancy import confirmed_inspection
if not confirmed_inspection(target, inspection):
return save(VerifyResult('BLOCKED', safe_to_continue=False,
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,
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.
with maintenance_target_guard(request, stop=stop) as refreshed:
updated = refreshed['context']
if ({k: v for k, v in context.items() if k != 'addresses'}
!= {k: v for k, v in updated.items() if k != 'addresses'}
or any(context['addresses'].get(k) != v for k, v in updated['addresses'].items())):
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 原生检查后工程或地址身份变化')
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 '历史地址记录仍存在;检查未替代恢复或会话释放。'))
if stop is not None and stop.is_set():
raise ValueError('MAINTENANCE_CANCELLED: 已取消,未开始 Repair')
emit('icdb_diagnosis_confirmed', detail='本轮原生检查明确要求修复当前数据库,且确认未占用')
native_root = root/'native-repair'; native_root.mkdir()
attempt = native_root/'attempt.json'
with attempt.open('x', encoding='utf-8') as stream:
@@ -246,10 +254,10 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
emit('native_repair_start', detail='核对占用后由官方工具检查/修复;应用不自动备份')
# Repeat immediately before dispatch; the worker repeats before
# launching the native process as well.
with maintenance_target_guard(request, context): pass
with maintenance_target_guard(request, context, stop=stop): pass
recovery = run_native_repair(target, native_root, mentor_bin=request.mentor_bin,
timeout_seconds=max(60, request.timeout_seconds), progress=progress,
maintenance_context=context)
timeout_seconds=max(60, request.timeout_seconds), progress=native_event,
maintenance_context=context, stop=stop)
assert_native_idle()
recovery = {**recovery, 'native_status': recovery.get('status'), 'validation_passed': False}
recovery['release'] = repair_release_state(request, target, recovery)
@@ -262,6 +270,10 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
# 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,)))
if confirmed:
emit('repair_verify', detail='原生修复及释放已确认,重新打开同一工程校验')
from .post_repair_consent import PostRepairProof
@@ -0,0 +1,61 @@
"""Interpret the current Project Backup loading session, before any Repair."""
import ntpath
import re
def _same(left, right):
return ntpath.normcase(ntpath.normpath(str(left))) == ntpath.normcase(ntpath.normpath(str(right)))
def classify_inspection(project, database, output):
result = {'status': 'UNCONFIRMED', 'repair_required': False}
if not isinstance(output, str):
return result
loaded = re.findall(r'Loading project file \[([^\]\r\n]+)\]\.', output)
if len(loaded) != 1 or not _same(loaded[0], project):
return result
checking = 'Checking if project is in use.'
if checking not in output:
return result
current = output.rsplit(checking, 1)[1]
if re.search(r'\bProject is in use\b', current, re.I):
return {**result, 'status': 'IN_USE'}
if ("Project is not in use. Full iCDB Project Backup's functionality is available." not in current
or 'Backup information loaded correctly.' not in current):
return result
# This exact native error was captured from the isolated EE7.9.5 project.
# A generic 'try Repair' or an old error before the latest check is not proof.
inconsistency_pattern = (
r"Project database \[([^\]\r\n]+)\] is inconsistent\. It has been manually copied while the iCDB Server was running\. "
r"Please use iCDB Project Backup 'Repair project' functionality to fix this issue\.")
inconsistent = re.findall(inconsistency_pattern, current)
from .icdb_recovery import _session_losses
losses = list(_session_losses(current))
if (len(inconsistent) > 1 or any(not _same(path, database) for path in inconsistent)
or len(losses) > 1 or any(not lost.get('session') or lost.get('scope') != 'project'
or not _same(lost.get('database_path', ''), database) for lost in losses)):
return result
required = bool(inconsistent or losses)
remaining = re.sub(inconsistency_pattern, '', current)
if required:
remaining = remaining.replace('Please try to repair the project!', '')
if re.search(r'\berror\b|try to repair|inconsistent|corrupt', remaining, re.I):
return result
return {'status': 'NOT_IN_USE', 'repair_required': bool(required)}
def confirmed_inspection(target, record):
"""Only an exact, exited, inspection-only native process grants a verdict."""
if (not isinstance(record, dict) or record.get('inspection_only') is not True
or record.get('repair_requested') is not False
or type(record.get('native_pid')) is not int or record['native_pid'] <= 0
or record.get('native_exit_code') != 0
or record.get('release', {}).get('native_exited') is not True
or not _same(record.get('project', ''), target.project)
or not _same(record.get('database', ''), target.database)
or record.get('unknown_dialogs')):
return False
expected = classify_inspection(target.project, target.database, record.get('output'))
return (expected['status'] in ('NOT_IN_USE', 'IN_USE')
and record.get('status') == expected['status']
and record.get('repair_required') is expected['repair_required'])
+16 -5
View File
@@ -253,8 +253,10 @@ def repair_release_state(request, target, native_result):
def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progress=None,
maintenance_context=None):
maintenance_context=None, inspection_only=False, stop=None):
"""Supervise the GUI on its own desktop; a repair timeout never kills it."""
if stop is not None and stop.is_set():
return {'status': 'CANCELLED', 'detail': '原生操作启动前已取消', 'release': {'safe_to_continue': True}}
from .desktop_worker import DesktopWorker
root = Path(root)
root.mkdir(parents=True, exist_ok=True)
@@ -264,16 +266,23 @@ def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progr
job_path.write_text(json.dumps({'project': str(target.project), 'database': str(target.database),
'root': str(root), 'mentor_bin': str(mentor_bin or ''), 'timeout': timeout_seconds,
'cancel_signal': str(cancel), 'supervisor_pid': os.getpid(), 'desktop': desktop,
'maintenance_context': maintenance_context},
'maintenance_context': maintenance_context, 'inspection_only': inspection_only},
ensure_ascii=False), encoding='utf-8')
command = ([sys.executable] if getattr(sys, 'frozen', False) else
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--repair-worker', str(job_path)]
worker = DesktopWorker(command, desktop)
worker.bind_cancellation(cancel)
deadline = time.monotonic()+max(1, float(timeout_seconds))+5
# Worker admission includes filesystem/ownership checks before the native
# timeout begins. Bound that preparation separately; never extend on polls.
deadline = time.monotonic()+60+max(1, float(timeout_seconds))+5
event_count = 0
cancelled = False
try:
while worker.poll() is None and time.monotonic()<deadline:
if not cancelled and stop is not None and stop.is_set():
worker.request_stop()
cancelled = True
deadline = min(deadline, time.monotonic()+5)
event_file = root/'repair-events.jsonl'
if progress and event_file.is_file():
lines = event_file.read_text('utf-8').splitlines()
@@ -287,11 +296,13 @@ def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progr
outcome = root/'repair-result.json'
if worker.poll() is None or not outcome.is_file():
worker.request_stop()
return {'status': 'TIMEOUT_UNRELEASED', 'worker_pid': worker.pid, 'desktop': desktop,
return {'status': 'CANCELLED_UNRELEASED' if cancelled else 'TIMEOUT_UNRELEASED', 'worker_pid': worker.pid, 'desktop': desktop,
'release': {'safe_to_continue': False},
'detail': '原生修复尚未确认结束,保留操作并停止批次', 'evidence_path': str(root)}
result = json.loads(outcome.read_text('utf-8'))
if worker.returncode != 0 and result.get('status') == 'REPAIRED':
if cancelled:
result.update(status='CANCELLED', repair_required=False)
if worker.returncode != 0 and result.get('status') in ('REPAIRED', 'NOT_IN_USE', 'IN_USE'):
result['status'] = 'UNCONFIRMED'
return {**result, 'evidence_path': str(root)}
finally:
+56 -1
View File
@@ -180,6 +180,52 @@ def _native_evidence(project, database, pid, started_ns, baseline, *, output_tex
'restore_tail': restore_log[-8192:]}
def _inspect_project(job, process, emit):
"""Observe this process's native query; never send a Repair/menu command."""
import win32con, win32gui
from .native_occupancy import classify_inspection
project, database = Path(job['project']), Path(job['database'])
result = {'status': 'UNCONFIRMED', 'project': str(project), 'database': str(database),
'native_pid': process.pid, 'inspection_only': True, 'repair_requested': False,
'repair_required': False, 'output': ''}
deadline = time.monotonic() + max(1, float(job['timeout']))
closing = False
# 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 (
w['title'] == '' and w['class'] in ('UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator'))]
mains = [w for w in windows if w['class'].startswith('Afx:')
and w['title'].casefold() == ('iCDB Project Backup - '+str(project)).casefold()]
main = mains[0] if len(mains) == 1 else None
shells = [w for w in windows if w['class'].startswith('Afx:') and w['title'] == 'iCDB Project Backup']
unknown = [w for w in windows if w is not main and w not in shells]
if unknown:
result.update(status='UNCONFIRMED', unknown_dialogs=unknown)
break
current = _native_output(windows)
if current is not None:
result['output'] = current
cancelled = Path(job['cancel_signal']).exists()
expired = time.monotonic() >= deadline
verdict = classify_inspection(project, database, current)
if cancelled:
result.update(status='CANCELLED', repair_required=False)
if not closing and main and main['enabled'] and (cancelled or expired or verdict['status'] != 'UNCONFIRMED'):
if not cancelled and not expired: result.update(verdict)
emit(stage='native_occupancy', **result)
win32gui.PostMessage(main['hwnd'], win32con.WM_CLOSE, 0, 0)
closing = True
time.sleep(.2)
exited = process.poll() is not None
result['native_exit_code'] = process.poll()
result['release'] = {'native_exited': exited,
'addresses': [str(database/'cdbsvr/sAddress.adr')] if (database/'cdbsvr/sAddress.adr').exists() else [],
'safe_to_continue': exited and result['status'] == 'NOT_IN_USE'}
if not exited:
result.update(status='TIMEOUT_UNRELEASED', repair_required=False)
return result
def repair_worker_main(job_path):
import win32con, win32gui
from .native_repair import RepairTarget, check_repair_access
@@ -208,7 +254,7 @@ def repair_worker_main(job_path):
if home is None:
raise ValueError('NATIVE_REPAIR_UNAVAILABLE: 未找到 Mentor 安装目录')
executable = home/'iCDB/win32/bin/iCDBProjectBackup.exe'
command_id = _repair_command(executable)
command_id = None if job.get('inspection_only') else _repair_command(executable)
from .mentor_adapter import pcb_processes, _process_details
if pcb_processes() or _process_details('LibraryManager.exe'):
raise ValueError('REPAIR_DATABASE_IN_USE')
@@ -218,6 +264,7 @@ def repair_worker_main(job_path):
from .verify_runner import VerifyRequest
maintenance_request = VerifyRequest(Path(maintenance_context['library']),
maintenance_context['block'], root, maintenance=True)
emit(stage='native_preflight', detail='正在核对本次原生工具的目标及占用')
with maintenance_target_guard(maintenance_request, maintenance_context) as checked:
if (checked['target'].project.resolve() != project.resolve()
or checked['target'].database.resolve() != database.resolve()):
@@ -229,11 +276,19 @@ def repair_worker_main(job_path):
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
if maintenance_context is not None:
with maintenance_target_guard(maintenance_request, maintenance_context): pass
if Path(job['cancel_signal']).exists():
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
baseline = snapshot_log(project.parent/'Log Files/ProjectBackupLog.txt')
started_ns = time.time_ns()
if Path(job['cancel_signal']).exists():
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
process = subprocess.Popen([str(executable), '-p', str(project)], cwd=str(project.parent))
result['native_pid'] = process.pid
emit(stage='native_started', pid=process.pid, project=str(project))
if job.get('inspection_only'):
result = _inspect_project(job, process, emit)
(root/'repair-result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
return 0 if result['status'] in ('NOT_IN_USE', 'IN_USE') else 1
deadline = time.monotonic()+max(1, float(job['timeout']))
invoked = confirmed = closing = False
evidence = None
+59
View File
@@ -0,0 +1,59 @@
"""Bound WMI enumeration in a read-only helper, never in the Qt thread."""
from pathlib import Path
import json
import re
import subprocess
import sys
import tempfile
def query_owners(names, *, timeout_seconds=10):
names = tuple(names)
if not names or any(not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names):
raise ValueError('OWNER_QUERY_INVALID')
with tempfile.TemporaryDirectory(prefix='cbb-owner-probe-') as directory:
job = Path(directory)/'request.json'
job.write_text(json.dumps({'names': names}), encoding='utf-8')
command = ([sys.executable] if getattr(sys, 'frozen', False) else
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--owner-probe', str(job)]
try:
result = subprocess.run(command, timeout=max(.1, min(10, timeout_seconds)),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
except subprocess.TimeoutExpired as error:
# This helper only enumerates processes; it never launches Mentor
# or acquires a native database session.
raise RuntimeError('OWNER_QUERY_TIMEOUT: 进程查询超时,占用状态无法确认') from error
try:
record = json.loads(job.with_name('result.json').read_text('utf-8'))
rows = record['owners']
if result.returncode != 0 or record['names'] != list(names) or not isinstance(rows, list):
raise ValueError('invalid result')
for row in rows:
if (type(row['pid']) is not int or row['pid'] <= 0 or row['name'].casefold() not in {n.casefold() for n in names}
or not isinstance(row['command'], str)):
raise ValueError('invalid owner')
return rows
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
raise RuntimeError('OWNER_QUERY_UNCONFIRMED: 进程查询未返回有效证据') from error
def owner_probe_main(job):
import pythoncom
import win32com.client
job = Path(job)
names = json.loads(job.read_text('utf-8'))['names']
if not names or any(not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names):
return 1
pythoncom.CoInitialize()
try:
service = win32com.client.GetObject('winmgmts:')
query = 'SELECT ProcessId,Name,CommandLine FROM Win32_Process WHERE ' + ' OR '.join(
f"Name='{name}'" for name in names)
rows = [{'pid': int(item.ProcessId), 'name': str(item.Name),
'command': str(item.CommandLine or '')} for item in service.ExecQuery(query)]
service = None
job.with_name('result.json').write_text(json.dumps({'names': names, 'owners': rows}), encoding='utf-8')
return 0
finally:
pythoncom.CoUninitialize()
@@ -199,7 +199,13 @@ def _validate_current_processes(job, prelaunch, target_pid, launcher_pid, worker
or not is_reusable_circuit_pcb(launcher[2], launcher[3], job['pcb'])):
raise ValueError('POST_REPAIR_PROCESS_IDENTITY_MISMATCH')
allowed = {target_pid, launcher_pid, worker_pid, int(job['supervisor_pid']), *companion_pids}
if any(r[0] not in allowed for r in rows): raise ValueError('POST_REPAIR_FOREIGN_OWNER')
foreign = [r for r in rows if r[0] not in allowed]
if foreign:
from .management import _write_json
_write_json(Path(job['root'])/'foreign-owners.json', {'allowed_pids': sorted(allowed),
'observed': [{'pid': r[0], 'name': r[1], 'executable': r[2], 'command': r[3], 'parent_pid': r[4]}
for r in foreign]})
raise ValueError(f'POST_REPAIR_FOREIGN_OWNER: {[(r[0], r[1]) for r in foreign]}')
class ConsentController:
+3 -1
View File
@@ -136,7 +136,7 @@ def _coordination_checkpoint(path):
return checkpoint_record(path) is not None
def scan_tree(root, *, scope=None, exclude=None):
def scan_tree(root, *, scope=None, exclude=None, check=None):
"""Refuse links/special files; optionally prune trees outside semantic scope.
Copies always call this without a scope, validating complete membership.
@@ -148,8 +148,10 @@ def scan_tree(root, *, scope=None, exclude=None):
entries = {}
folders = [root]
while folders:
if check is not None: check()
with os.scandir(folders.pop()) as scanned:
for entry in scanned:
if check is not None: check()
path = Path(entry.path)
if exclude is not None and path.is_relative_to(exclude):
continue
+11 -9
View File
@@ -142,7 +142,7 @@ class MainWindow(QWidget):
self.selected_batch_button = QPushButton('批量校验已选'); self.selected_batch_button.clicked.connect(self.verify_selected)
self.batch_button = QPushButton('校验可见非 READY'); self.batch_button.clicked.connect(self.verify_all)
self.icdb_repair_button = QPushButton('非 READY ICDB 检查与修复'); self.icdb_repair_button.clicked.connect(self.repair_icdb_all)
self.icdb_repair_button.setToolTip('忽略 READY 项(包括已勾选项);先检查启动,仅本轮日志确认 ICDB 失联时才修复。')
self.icdb_repair_button.setToolTip('忽略 READY 项(包括已勾选项);先由原生工具检查占用和数据库,仅确认当前工程需要 ICDB Repair 时才修复。')
self.backup_restore_button = QPushButton('从备份恢复 CBB…')
self.backup_restore_button.clicked.connect(self.restore_backup)
self.stop_button = QPushButton('当前项完成后停止'); self.stop_button.clicked.connect(self.request_stop)
@@ -286,6 +286,7 @@ class MainWindow(QWidget):
self.counts_label.setText(f'可见 {counts["visible"]} / {len(self._records_by_name)} · '
f'READY {counts["ready"]} · 异常/待确认 {counts["error"]}')
self.stop_button.setEnabled(self.busy and self.loaded_path is not None and not self.stop.is_set())
self.stop_button.setText('取消当前检查并停止队列' if self._global_icdb_run else '当前项完成后停止')
def _show_unfinished_management(self):
from cbb_refresh_verify.management import unfinished_operations
@@ -616,7 +617,7 @@ 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 失联才修复,再重新打开校验。'
'先取得库锁并核对工程,由原生工具检查占用和数据库。仅本轮检查确认当前工程未占用且需要 ICDB Repair 时才修复,再重新打开校验。'
'占用、历史版本提示或故障原因未确认时停止,不猜测故障或删除地址文件。READY 项始终忽略。\n'
'仅本地固定磁盘:严格确认修复并重新独占检查后,可一次确认本次异常退出的读写访问提示。'
'网络盘、UNC 或链接路径不自动确认该提示。\n'
@@ -711,7 +712,7 @@ class MainWindow(QWidget):
verify = self.verifier or (lambda req: run_verify(
req, progress=lambda e: self.signals.event.emit(e),
flag_reader=read_library_flag_if_available,
version_prompt=self.signals.version_choice.emit))
version_prompt=self.signals.version_choice.emit, stop=self.stop))
def verifier(req):
if maintenance:
self.signals.event.emit({'block': req.block_name, 'stage': 'icdb_check_start'})
@@ -818,7 +819,7 @@ 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'}:
if stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED', 'QUEUE_STOP', 'CHECKED', 'CANCELLED'}:
self._icdb_completed += 1
self.icdb_progress.setValue(self._icdb_completed)
phases = {'icdb_check_start': '检查工程数据库与校验状态',
@@ -866,15 +867,16 @@ class MainWindow(QWidget):
self.recovery_button.setEnabled(self.recovery_path.is_dir())
passed = sum(r.status == 'PASS' for r in results)
skipped = sum(r.status == 'SKIPPED' for r in results)
failed = len(results)-passed-skipped
checked = sum(r.status == 'CHECKED' for r in results)
failed = len(results)-passed-skipped-checked
text = (f'已结束:成功 {passed},失败 {failed},预检跳过 {len(self.skipped_names)},'
f'队列未执行 {skipped}。\n完整日志:{report}\n仅失败日志:{failure_report_path(report)}')
if self._global_icdb_run:
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
counts = maintenance_counts(results)
text = ('非 READY ICDB 检查已结束\n'
f'检查/校验通过 {passed},失败/受阻 {failed},队列未执行 {skipped}\n'
f'启动检查通过、未修复 {counts["checked_without_repair"]}(不等同于 READY)\n'
f'修复并校验通过 {passed},失败/受阻 {failed},队列未执行 {skipped}\n'
f'仅检查、未修复 {counts["checked_without_repair"]}(不计入修复成功)\n'
f'原生修复完成 {counts["repaired"]},恢复备份待复核 {counts["review_required"]},'
f'ICDB已修复/PCB版本待选 {counts["version_choice_required"]},'
f'修复未确认 {counts["repair_unconfirmed"]}\n'
@@ -885,7 +887,7 @@ class MainWindow(QWidget):
status_text = text
if self._global_icdb_run:
status_text = (f'非 READY 检查结束:通过 {passed},失败/受阻 {failed},未执行 {skipped}。\n'
f'启动检查通过、未修复 {counts["checked_without_repair"]};'
f'仅检查、未修复 {counts["checked_without_repair"]};'
f'原生修复 {counts["repaired"]},恢复备份待复核 {counts["review_required"]},'
f'ICDB已修复/PCB版本待选 {counts["version_choice_required"]},'
f'修复未确认 {counts["repair_unconfirmed"]}。')
@@ -917,7 +919,7 @@ class MainWindow(QWidget):
def request_stop(self):
if self.version_dialog is not None:
self.version_dialog.reject()
self.stop.set(); self.status_label.setText('已请求停止;当前 CBB 完成或超时后停止队列。'); self._update()
self.stop.set(); self.status_label.setText('已请求取消;检查将停止,原生写入只等待安全结束,不强制终止。'); self._update()
def _failed(self, error):
if self.library_lease is not None:
+12 -5
View File
@@ -270,6 +270,11 @@ def classify_failure_category(detail):
from .icdb_recovery import ERROR_CODE, parse_session_loss
if ERROR_CODE.casefold() in lower or parse_session_loss(text):
return ERROR_CODE
if 'back annotation is not allowed on verified (or once verified) reusable blocks.' in lower:
# Preserve the native integration failure even when shutdown adds a
# secondary release warning. This category does not grant permission
# to reimport or change safe_to_continue.
return 'CBB_REIMPORT_REQUIRED'
if any(code in lower for code in (
'pcb_release_unconfirmed', 'icdb_release_unconfirmed',
'icdb_session_unconfirmed', 'pcb_session_active', 'database_recovery_required')):
@@ -507,7 +512,7 @@ def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline,
def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None,
dialog_supervisor_factory=None, version_prompt=None):
dialog_supervisor_factory=None, version_prompt=None, stop=None):
# Cover contents checking, native work and final state reads with one
# session-wide mutex. The worker-stage lock below is reentrant on Windows.
import win32event, win32con
@@ -530,7 +535,7 @@ 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,
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))
@@ -1167,10 +1172,12 @@ def write_failure_report(requests, results, root, *, path=None):
root = Path(root); root.mkdir(parents=True, exist_ok=True)
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'}]
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'}
and not (result.status == 'CHECKED' and result.safe_to_continue)]
passed = sum(result.status == 'PASS' for result in results)
skipped = len(results)-passed-len(failed)
lines = ['CBB Verify 失败清单', f'总数: {len(results)} 成功: {passed} 失败: {len(failed)} 未执行: {skipped}',
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}',
'CBB\t状态\t错误分类\t失败阶段\t桥状态\t原始错误\t证据\t实际耗时(秒)']
for req, result in failed:
timings = ' '.join(f'{key}={value:.3f}s' +
+48 -54
View File
@@ -1,81 +1,75 @@
"""Exercise the production diagnosis gate; do not spoof callback names."""
import json
from pathlib import Path
"""Native occupancy must precede repair even when old addresses remain."""
import pytest
from test_maintenance_entry import case, no_native_launch
from test_native_occupancy import output
def diagnostic_result(req, *, error='', database=None):
from cbb_refresh_verify.verify_runner import VerifyResult
root = req.evidence_dir/'probe'; root.mkdir(parents=True, exist_ok=True)
result = VerifyResult('FAIL' if error else 'PASS', error_category=error,
evidence_path=root/'result.json', safe_to_continue=not error)
result.evidence_path.write_text('{}', encoding='utf-8')
if error == 'ICDB_REPAIR_REQUIRED':
record = {'error_code': error, 'scope': 'project', 'session': 'test-session',
'database_path': str(database)}
(root/'diagnostics').mkdir(exist_ok=True)
(root/'diagnostics/icdb-recovery.json').write_text(json.dumps(record), encoding='utf-8')
return result
def inspection(target, *, fault=False):
return {'inspection_only': True, 'repair_requested': False, 'native_pid': 777,
'native_exit_code': 0, 'project': str(target.project), 'database': str(target.database),
'output': output(target.project, target.database, fault=fault),
'status': 'NOT_IN_USE', 'repair_required': fault, 'release': {'native_exited': True}}
def test_diagnosis_holds_library_lock_and_healthy_never_repair(case, monkeypatch):
@pytest.mark.parametrize('old_address', [False, True])
def test_native_inspection_holds_lock_without_opening_pcb(case, monkeypatch, old_address):
from cbb_refresh_verify import verify_runner as runner, native_repair, library_lock
request, project, address = case
address.unlink()
def worker(req, **kw):
key = library_lock.LibraryLock(req.lmc_file).key
assert key in library_lock._owners
if not old_address: address.unlink()
def native(target, root, **kw):
key = library_lock.LibraryLock(request.lmc_file).key
assert library_lock._owners[key]['depth'] > 0
assert req.diagnostic_only and not req.auto_repair and not req.maintenance
assert not req.native_lm_verify and not req.libspec
return diagnostic_result(req)
monkeypatch.setattr(runner, '_run_verify_serialized', worker)
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: pytest.fail('healthy repair'))
assert kw['inspection_only'] is True
assert kw['timeout_seconds'] <= 30
return inspection(target)
monkeypatch.setattr(native_repair, 'run_native_repair', native)
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: pytest.fail('inspection opened PCB'))
result = runner.run_verify(request)
assert result.status == 'PASS' and result.recovery_attempts == ()
assert result.status == 'CHECKED' and result.recovery_attempts == ()
assert result.library_flag == 'UNKNOWN'
assert not library_lock.has_blocker(request.lmc_file)
assert result.safe_to_continue is (not old_address)
@pytest.mark.parametrize('fault', ['missing', 'generic', 'assertion', 'wrong_database', 'outside_evidence'])
def test_unconfirmed_diagnosis_never_repairs(case, monkeypatch, fault):
@pytest.mark.parametrize('fault', ['missing', 'generic', 'assertion', 'wrong_database', 'stale_verdict', 'not_exited'])
def test_unconfirmed_native_inspection_never_repairs(case, monkeypatch, fault):
from cbb_refresh_verify import verify_runner as runner, native_repair
request, project, address = case
address.unlink()
def worker(req, **kw):
if fault == 'assertion': raise AssertionError('diagnostic failure')
if fault == 'missing': return runner.VerifyResult('PASS')
if fault == 'generic': return diagnostic_result(req, error='DATABASE_SAFETY_STOP')
if fault == 'outside_evidence':
from dataclasses import replace
req = replace(req, evidence_dir=request.evidence_dir/'old-run')
return diagnostic_result(req, error='ICDB_REPAIR_REQUIRED',
database=project.parent/('wrong' if fault == 'wrong_database' else 'database'))
monkeypatch.setattr(runner, '_run_verify_serialized', worker)
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: pytest.fail('unconfirmed repair'))
def native(target, root, **kw):
assert kw['inspection_only'] is True
if fault == 'assertion': raise AssertionError('probe failed')
if fault == 'missing': return {}
record = inspection(target, fault=True)
if fault == 'generic': record['output'] = 'DATABASE_SAFETY_STOP'
if fault == 'wrong_database': record['database'] = str(project.parent/'other')
if fault == 'stale_verdict': record['output'] += 'Checking if project is in use.'
if fault == 'not_exited': record['release']['native_exited'] = False
return record
monkeypatch.setattr(native_repair, 'run_native_repair', native)
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: pytest.fail('unconfirmed reopened PCB'))
result = runner.run_verify(request)
assert result.status != 'PASS' and result.recovery_attempts == ()
assert result.status == 'BLOCKED' and not result.recovery_attempts
def test_diagnostic_fault_repairs_once_then_full_verification(case, monkeypatch):
def test_native_fault_repairs_once_then_full_verification_with_old_address(case, monkeypatch):
from cbb_refresh_verify import verify_runner as runner, native_repair
from test_native_repair import complete_native_success
request, project, address = case
address.unlink()
calls = []
def worker(req, **kw):
calls.append('diagnose' if req.diagnostic_only else 'verify')
if req.diagnostic_only:
return diagnostic_result(req, error='ICDB_REPAIR_REQUIRED', database=project.parent/'database')
assert req.post_repair_proof is not None and not req.auto_repair
return runner.VerifyResult('PASS', library_flag='GREEN')
def repair(target, *a, **kw):
def native(target, root, **kw):
if kw.get('inspection_only'):
assert address.exists()
calls.append('inspect')
return inspection(target, fault=True)
calls.append('repair')
address.unlink() # Simulated native repair release only.
return complete_native_success(target)
monkeypatch.setattr(runner, '_run_verify_serialized', worker)
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
def verify(req, **kw):
assert req.post_repair_proof is not None and not req.diagnostic_only and not req.auto_repair
calls.append('verify')
return runner.VerifyResult('PASS', library_flag='GREEN')
monkeypatch.setattr(native_repair, 'run_native_repair', native)
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
result = runner.run_verify(request)
assert calls == ['diagnose', 'repair', 'verify']
assert calls == ['inspect', 'repair', 'verify']
assert result.status == 'PASS' and len(result.recovery_attempts) == 1
+13 -14
View File
@@ -48,20 +48,19 @@ def case(tmp_path, monkeypatch):
def patch_verification_after_fault(monkeypatch, runner, verify):
"""Inject native startup evidence, then exercise the production repair gate."""
def worker(req, **kwargs):
if not req.diagnostic_only:
return verify(req, **kwargs)
project, pcb = runner.preflight(req)
root = req.evidence_dir/'native-startup'; root.mkdir(parents=True, exist_ok=True)
(root/'diagnostics').mkdir(exist_ok=True)
(root/'diagnostics/icdb-recovery.json').write_text(json.dumps({
'error_code': 'ICDB_REPAIR_REQUIRED', 'scope': 'project', 'session': 'fixture',
'database_path': str(project.parent/'database')}), encoding='utf-8')
evidence = root/'result.json'; evidence.write_text('{}', encoding='utf-8')
return runner.VerifyResult('FAIL', error_category='ICDB_REPAIR_REQUIRED',
safe_to_continue=False, evidence_path=evidence)
monkeypatch.setattr(runner, '_run_verify_serialized', worker)
"""Inject only native process boundaries; production interprets the Output."""
from cbb_refresh_verify import native_repair
from test_native_occupancy import output
repair = native_repair.run_native_repair
def native(target, root, **kw):
if not kw.get('inspection_only'):
return repair(target, root, **kw)
return {'inspection_only': True, 'repair_requested': False, 'native_pid': 777,
'native_exit_code': 0, 'project': str(target.project), 'database': str(target.database),
'output': output(target.project, target.database, fault=True),
'status': 'NOT_IN_USE', 'repair_required': True, 'release': {'native_exited': True}}
monkeypatch.setattr(native_repair, 'run_native_repair', native)
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
@pytest.mark.parametrize('pcb_config', ['standard', 'legacy_template'])
+4 -5
View File
@@ -88,12 +88,11 @@ def test_restarted_export_copy_can_release_only_after_fresh_proof(export_case, t
def test_maintenance_idle_guard_recognizes_new_exporter_names(monkeypatch):
import win32com.client
from cbb_refresh_verify.maintenance_entry import assert_native_idle
def query(sql):
assert 'icdb2ascii.exe' in sql.casefold() and 'icdbnetserver.exe' in sql.casefold()
return [SimpleNamespace(ProcessId=123456, Name='icdb2ascii.exe', CommandLine='export')]
monkeypatch.setattr(win32com.client, 'GetObject', lambda *_: SimpleNamespace(ExecQuery=query))
def query(names):
assert 'icdb2ascii.exe' in [n.casefold() for n in names] and 'icdbnetserver.exe' in [n.casefold() for n in names]
return [{'pid': 123456, 'name': 'icdb2ascii.exe', 'command': 'export'}]
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', query)
with pytest.raises(ValueError, match='MAINTENANCE_OWNER_ACTIVE'): assert_native_idle()
+178
View File
@@ -0,0 +1,178 @@
import json
from pathlib import Path
import pytest
def output(project, database, *, fault=False, busy=False):
text = f'Loading project file [{project}].\nChecking if project is in use.\n'
if fault:
text += (f'Project database [{database}] is inconsistent. It has been manually copied while the iCDB Server was running. '
"Please use iCDB Project Backup 'Repair project' functionality to fix this issue.\n")
return text + ('Project is in use.\n' if busy else
"Project is not in use. Full iCDB Project Backup's functionality is available.\nBackup information loaded correctly.\n")
@pytest.mark.parametrize('fault,busy,status,repair', [
(False, False, 'NOT_IN_USE', False), (True, False, 'NOT_IN_USE', True),
(True, True, 'IN_USE', False), (False, True, 'IN_USE', False)])
def test_native_ownership_and_repair_need_are_separate(tmp_path, fault, busy, status, repair):
from cbb_refresh_verify.native_occupancy import classify_inspection
project, database = tmp_path/'A.prj', tmp_path/'database'
result = classify_inspection(project, database, output(project, database, fault=fault, busy=busy))
assert result['status'] == status
assert result['repair_required'] is repair
@pytest.mark.parametrize('case', ['progress', 'wrong_project', 'wrong_database', 'stale_verdict', 'generic_repair'])
def test_incomplete_or_foreign_output_cannot_authorize_repair(tmp_path, case):
from cbb_refresh_verify.native_occupancy import classify_inspection
project, database = tmp_path/'A.prj', tmp_path/'database'
text = output(project, database, fault=True)
if case == 'progress': text = f'Loading project file [{project}].\nChecking if project is in use.'
if case == 'wrong_project': text = output(tmp_path/'Other.prj', database, fault=True)
if case == 'wrong_database': text = output(project, tmp_path/'other', fault=True)
if case == 'stale_verdict': text += 'Checking if project is in use.\n'
if case == 'generic_repair': text = output(project, database) + 'Please try to repair the project!'
assert classify_inspection(project, database, text)['repair_required'] is False
@pytest.mark.parametrize('fault,busy', [(False, False), (True, False), (False, True)])
def test_inspection_mode_only_observes_and_closes_its_tool(tmp_path, monkeypatch, fault, busy):
import win32con
from test_native_repair import repair_worker_fixture
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
job.write_text(json.dumps(data), encoding='utf-8')
monkeypatch.setattr(ui, '_repair_command', lambda *a: pytest.fail('inspection resolved Repair command'))
monkeypatch.setattr(ui, '_native_output', lambda *_: output(data['project'], data['database'], fault=fault, busy=busy))
assert ui.repair_worker_main(job) == 0
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert result['status'] == ('IN_USE' if busy else 'NOT_IN_USE')
assert result['release']['native_exited'] is True
assert result['repair_required'] is (fault and not busy)
assert actions == [(100, win32con.WM_CLOSE)]
def test_only_check_never_counts_as_repair_success():
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
from cbb_refresh_verify.verify_runner import VerifyResult
counts = maintenance_counts([VerifyResult('CHECKED', safe_to_continue=True)])
assert counts['passed'] == counts['repaired'] == 0
assert counts['checked_without_repair'] == 1
def test_cancelled_probe_returns_within_grace_without_killing_native(tmp_path, monkeypatch):
from threading import Event
from types import SimpleNamespace
from cbb_refresh_verify import native_repair as native
from cbb_refresh_verify.native_repair import RepairTarget
stop = Event(); ticks = [0.0]; actions = []
def sleep(seconds):
ticks[0] += seconds
stop.set()
monkeypatch.setattr(native, 'time', SimpleNamespace(monotonic=lambda: ticks[0], sleep=sleep))
class Worker:
pid = 123
def __init__(self, *a): pass
def bind_cancellation(self, p): pass
def poll(self): return None
def request_stop(self): actions.append('cancel')
def close(self): actions.append('close_handles')
def kill(self): pytest.fail('native owner must not be killed')
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
result = native.run_native_repair(RepairTarget(tmp_path/'A.prj', tmp_path/'database'),
tmp_path/'evidence', timeout_seconds=600, inspection_only=True, stop=stop)
assert ticks[0] < 6
assert result['status'] == 'CANCELLED_UNRELEASED'
assert result['release']['safe_to_continue'] is False
assert actions[-1] == 'close_handles'
def test_ui_keeps_processing_events_and_passes_cancel_to_native_task(qtbot, tmp_path, monkeypatch):
from threading import Event
from PySide6.QtCore import QTimer
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
entered = Event(); cancelled = Event(); ticks = []
def verify(req, *, stop, **kw):
entered.set()
if stop.wait(3): cancelled.set()
return VerifyResult('CANCELLED')
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_verify', verify)
window = load_window(qtbot, tmp_path, monkeypatch,
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
window.search_edit.setText('Beta')
timer = QTimer(window); timer.setInterval(10); timer.timeout.connect(lambda: ticks.append(True)); timer.start()
window.repair_icdb_all()
qtbot.waitUntil(entered.is_set)
qtbot.waitUntil(lambda: len(ticks) >= 3)
assert window.busy and window.stop_button.isEnabled()
window.stop_button.click()
qtbot.waitUntil(lambda: not window.busy)
assert cancelled.is_set()
@pytest.mark.parametrize('extra', ['foreign_session', 'extra_error'])
def test_foreign_or_additional_fault_is_never_a_clean_inspection(tmp_path, extra):
from cbb_refresh_verify.native_occupancy import classify_inspection
project, database = tmp_path/'A.prj', tmp_path/'database'
text = output(project, database, fault=extra == 'extra_error')
if extra == 'foreign_session':
text += ('The last server session on different server machine lost the connection to the database. '
'Machine:[SERVER] Path:[C:/Other/Work/database] session:[old]')
else:
text += 'ERROR: shared symbol database unavailable'
assert classify_inspection(project, database, text)['status'] == 'UNCONFIRMED'
def test_unconfirmed_inspection_closes_known_main_at_timeout(tmp_path, monkeypatch):
import win32con
from test_native_repair import repair_worker_fixture
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
job.write_text(json.dumps(data), encoding='utf-8')
monkeypatch.setattr(ui, '_native_output', lambda *_: 'Unrecognized response')
assert ui.repair_worker_main(job) == 1
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert result['status'] == 'UNCONFIRMED'
assert result['release']['native_exited'] is True
assert actions == [(100, win32con.WM_CLOSE)]
def test_directory_scan_honors_cancel_between_entries(tmp_path):
from cbb_refresh_verify.scoped_manifest import scan_tree
for i in range(10): (tmp_path/f'{i}.dat').touch()
calls = []
def cancel():
calls.append(True)
if len(calls) == 3: raise RuntimeError('CANCELLED')
with pytest.raises(RuntimeError, match='CANCELLED'):
scan_tree(tmp_path, check=cancel)
assert len(calls) == 3
def test_cancel_during_final_guard_cannot_launch_native_tool(tmp_path, monkeypatch):
from contextlib import contextmanager
from test_native_repair import repair_worker_fixture
from cbb_refresh_verify.native_repair import RepairTarget
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
data = json.loads(job.read_text('utf-8'))
data['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
job.write_text(json.dumps(data), encoding='utf-8')
calls = []
@contextmanager
def guard(*a, **kw):
calls.append(True)
yield {'target': RepairTarget(Path(data['project']), Path(data['database']))}
if len(calls) == 2: Path(data['cancel_signal']).touch()
monkeypatch.setattr('cbb_refresh_verify.maintenance_entry.maintenance_target_guard', guard)
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('late native launch'))
assert ui.repair_worker_main(job) == 1
assert len(calls) == 2 and not actions
def test_verified_cbb_refusal_is_not_hidden_by_secondary_release_failure():
from cbb_refresh_verify.verify_runner import classify_failure_category
detail = ('BackAnnotate: Back Annotation is not allowed on verified (or once verified) Reusable Blocks.'
'\nPCB_RELEASE_UNCONFIRMED: not released')
assert classify_failure_category(detail) == 'CBB_REIMPORT_REQUIRED'
+23
View File
@@ -0,0 +1,23 @@
import subprocess
import pytest
def test_wmi_timeout_is_unknown_not_idle(monkeypatch):
from cbb_refresh_verify.owner_probe import query_owners
def hang(command, **kw):
assert 0 < kw['timeout'] <= 10
raise subprocess.TimeoutExpired(command, kw['timeout'])
monkeypatch.setattr(subprocess, 'run', hang)
with pytest.raises(RuntimeError, match='OWNER_QUERY_TIMEOUT'):
query_owners(['ExpeditionPCB.exe'])
def test_malformed_wmi_response_is_not_empty_owner_list(monkeypatch):
from cbb_refresh_verify.owner_probe import query_owners
from pathlib import Path
def run(command, **kw):
Path(command[-1]).with_name('result.json').write_text('{}')
return subprocess.CompletedProcess(command, 0)
monkeypatch.setattr(subprocess, 'run', run)
with pytest.raises(RuntimeError, match='OWNER_QUERY_UNCONFIRMED'):
query_owners(['ExpeditionPCB.exe'])