fix: preserve native calls on stop and keep status reads observational
This commit is contained in:
1 parent
97a3de20c9
commit
8d3eab1164
19 files changed
+631
-290
No files matched your search
@@ -3,3 +3,4 @@
|
||||
DEFAULT_TIMEOUT_SECONDS = 600
|
||||
DIALOG_AGENT_STARTUP_TIMEOUT_SECONDS = 30
|
||||
WORKER_START_GATE_TIMEOUT_SECONDS = DIALOG_AGENT_STARTUP_TIMEOUT_SECONDS + 15
|
||||
NATIVE_WRITE_STOP_WAIT_SECONDS = 120
|
||||
@@ -12,46 +12,61 @@ import win32service
|
||||
|
||||
_automation_clients = []
|
||||
_automation_clients_lock = threading.Lock()
|
||||
_supervisor_lost = threading.Event()
|
||||
|
||||
|
||||
def launch_save_helper(command, **kwargs):
|
||||
def launch_save_helper(command, *, start_gate=None, identity_path=None, operation_id=None, **kwargs):
|
||||
"""Register the save client atomically with respect to supervisor loss."""
|
||||
with _automation_clients_lock:
|
||||
if _supervisor_lost.is_set():
|
||||
raise RuntimeError('VERIFY_CANCELLED: 监督器已退出,未启动新的保存客户端')
|
||||
helper = subprocess.Popen(command, **kwargs)
|
||||
_automation_clients.append(helper)
|
||||
if start_gate is not None:
|
||||
from .session_record import process_identity, read_session_record, write_session_record
|
||||
if identity_path is None or not operation_id:
|
||||
raise ValueError('保存启动门缺少会话记录')
|
||||
state = {'operation_id': operation_id, 'processes': []}
|
||||
identity_path = Path(identity_path)
|
||||
if identity_path.exists():
|
||||
state = read_session_record(identity_path, evidence_root=identity_path.parent)
|
||||
if state['operation_id'] != operation_id:
|
||||
raise ValueError('保存记录不属于当前操作')
|
||||
if helper.poll() is None:
|
||||
state['processes'].append({'role': 'helper', **process_identity(helper.pid)})
|
||||
state['phase'] = 'NATIVE_CALL'
|
||||
write_session_record(identity_path, state)
|
||||
Path(start_gate).touch()
|
||||
return helper
|
||||
|
||||
|
||||
def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None, stop_clients=False):
|
||||
"""A crashed supervisor must not leave unsupervised automation writing.
|
||||
def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None, stop_clients=False,
|
||||
session_record_path=None, operation_id=None, supervisor_identity=None):
|
||||
"""Record stop intent; a watchdog cannot interrupt an in-flight COM call.
|
||||
|
||||
Stop only this Python worker and its registered automation clients. Native
|
||||
database owners remain alive, including a COM call already in progress.
|
||||
stop_clients is retained for old callers, never permission to kill Save.
|
||||
"""
|
||||
import win32api
|
||||
parent = win32api.OpenProcess(win32con.SYNCHRONIZE, False, int(supervisor_pid))
|
||||
if supervisor_identity is not None:
|
||||
from .session_record import process_identity, IDENTITY_KEYS
|
||||
actual = process_identity(int(supervisor_pid))
|
||||
if any(actual[k] != supervisor_identity.get(k) for k in IDENTITY_KEYS):
|
||||
parent.Close()
|
||||
raise RuntimeError('监督器进程身份已变化,未启动原生操作')
|
||||
|
||||
def watch():
|
||||
try:
|
||||
win32event.WaitForSingleObject(parent, win32event.INFINITE)
|
||||
_supervisor_lost.set()
|
||||
if cancel_path is not None:
|
||||
# Let native calls finish before the worker closes its exact
|
||||
# document. Killing a pending automation client can abandon it.
|
||||
Path(cancel_path).touch()
|
||||
if not stop_clients:
|
||||
return
|
||||
threading.Event().wait(5)
|
||||
with _automation_clients_lock:
|
||||
for helper in _automation_clients:
|
||||
try:
|
||||
if helper.poll() is None:
|
||||
helper.terminate()
|
||||
except OSError:
|
||||
pass
|
||||
if session_record_path is not None:
|
||||
from .session_record import write_session_record
|
||||
write_session_record(Path(session_record_path).with_name('supervisor-lost.json'),
|
||||
{'operation_id': operation_id, 'phase': 'SUPERVISOR_LOST'})
|
||||
finally:
|
||||
parent.Close()
|
||||
if cancel_path is None or stop_clients:
|
||||
os._exit(75)
|
||||
|
||||
thread = threading.Thread(target=watch, name='supervisor-watchdog', daemon=True)
|
||||
thread.start()
|
||||
@@ -80,6 +95,8 @@ class DesktopWorker:
|
||||
self.companions = []
|
||||
self.companion_pids = []
|
||||
self.job_bound = False
|
||||
self.native_worker = any(flag in command for flag in (
|
||||
'--verify-worker', '--management-worker', '--repair-worker', '--native-backup-worker'))
|
||||
# Track the session, but never use kill-on-close: PCB descendants can
|
||||
# still own a database transaction when the Python supervisor exits.
|
||||
try:
|
||||
@@ -180,24 +197,25 @@ class DesktopWorker:
|
||||
return {'safe_to_continue': False, 'remaining_pids': [], 'error': str(error)}
|
||||
|
||||
def stop_automation_clients(self):
|
||||
from .mentor_adapter import _terminate_pid
|
||||
for pid in self._save_clients():
|
||||
_terminate_pid(pid)
|
||||
# An absent return marker is not permission to interrupt Save/Close.
|
||||
return self._save_clients()
|
||||
|
||||
@property
|
||||
def returncode(self):
|
||||
return self.poll()
|
||||
|
||||
def kill(self):
|
||||
"""Stop automation clients only; preserve native PCB/iCDB sessions."""
|
||||
"""Native workers use cooperative stop, including compatibility callers."""
|
||||
if getattr(self, 'native_worker', False) or hasattr(self, 'cancel_path'):
|
||||
if hasattr(self, 'cancel_path'):
|
||||
self.cancel_path.touch()
|
||||
return False
|
||||
try:
|
||||
win32process.TerminateProcess(self.handle, 1)
|
||||
except Exception:
|
||||
pass
|
||||
# The worker is now stopped and cannot spawn another save helper.
|
||||
try:
|
||||
self.wait(timeout=5)
|
||||
self.stop_automation_clients()
|
||||
except Exception:
|
||||
pass
|
||||
for companion in self.companions:
|
||||
@@ -209,6 +227,28 @@ class DesktopWorker:
|
||||
def bind_cancellation(self, path):
|
||||
self.cancel_path = Path(path)
|
||||
|
||||
def bind_session(self, job):
|
||||
from .session_record import register_worker_session
|
||||
register_worker_session(self, job)
|
||||
|
||||
def native_write_pending(self):
|
||||
if not getattr(self, 'session_record_path', None):
|
||||
return None
|
||||
from .session_record import read_session_record
|
||||
path = self.session_record_path.with_name('worker-state.json')
|
||||
try:
|
||||
state = read_session_record(path, evidence_root=path.parent)
|
||||
from .operation_lifecycle import stop_disposition
|
||||
phase = state.get('phase')
|
||||
started = (False if phase == 'PRECALL' else True if phase in
|
||||
('NATIVE_CALL', 'CLOSING', 'POSTCALL', 'RELEASE_CHECK', 'FINISHED') else None)
|
||||
returned = (False if phase in ('PRECALL', 'NATIVE_CALL', 'CLOSING') else True if phase in
|
||||
('POSTCALL', 'RELEASE_CHECK', 'FINISHED') else None)
|
||||
return stop_disposition(call_started=started, call_returned=returned,
|
||||
identity_confirmed=True) in ('WAIT_FOR_RETURN', 'OBSERVE_UNCONFIRMED')
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
def request_stop(self):
|
||||
if not hasattr(self, 'cancel_path'):
|
||||
# Compatibility for diagnostic workers without the Verify protocol.
|
||||
@@ -228,6 +268,8 @@ class DesktopWorker:
|
||||
try:
|
||||
if self.poll() is None:
|
||||
self.request_stop()
|
||||
if getattr(self, 'native_worker', False) or hasattr(self, 'cancel_path'):
|
||||
return False # The observer keeps this exact process/desktop handle.
|
||||
except Exception:
|
||||
pass
|
||||
for companion in self.companions:
|
||||
|
||||
@@ -284,9 +284,8 @@ def scan_open_library_status(library: Path, names, *, tree_image_reader=None,
|
||||
image_status_map=image_status_map)
|
||||
status = reconcile_statuses(tree_statuses, fallback, names)
|
||||
uncalibrated = [name for name in names if status.get(name, 'UNKNOWN') == 'UNKNOWN']
|
||||
# The UI must never use UNKNOWN as a skip signal. Queue it as Pending
|
||||
# so it receives the real Verify flow instead of being silently omitted.
|
||||
effective = {name: ('PENDING' if value == 'UNKNOWN' else value)
|
||||
# Missing observations remain unknown; eligibility is decided by the caller.
|
||||
effective = {name: (value if tree_images.get(name) is not None else 'UNKNOWN')
|
||||
for name, value in status.items()}
|
||||
logger.info(
|
||||
'library_status_sources names=%s image_histogram=%s current_image_map=%s cached_image_map=%s image_status_map=%s cache_actions=%s filesystem=%s calibrated_tree=%s final=%s uncalibrated_sample=%s conflicts=%s ready_anchor_ids=%s unseen_tree_ids=%s',
|
||||
@@ -328,46 +327,14 @@ def scan_open_library_status(library: Path, names, *, tree_image_reader=None,
|
||||
return effective
|
||||
|
||||
try:
|
||||
from pywinauto import Desktop
|
||||
from pywinauto.controls.common_controls import TreeViewWrapper
|
||||
from cbb_refresh_verify.mentor_adapter import _tree_image, same_path
|
||||
target = None
|
||||
for window in Desktop(backend='win32').windows():
|
||||
title = window.window_text()
|
||||
if title.startswith('Library Manager:') and same_path(title.split(':', 1)[1].strip(), library):
|
||||
target = window
|
||||
break
|
||||
if target is None:
|
||||
if tree_image_reader is None:
|
||||
from cbb_refresh_verify.mentor_adapter import read_library_tree_image_map
|
||||
tree_image_reader = read_library_tree_image_map
|
||||
return finish(tree_image_reader(library, names))
|
||||
trees = [w for w in target.descendants() if 'TreeView' in w.class_name()]
|
||||
if len(trees) != 1:
|
||||
return finish({})
|
||||
tree = TreeViewWrapper(trees[0].handle)
|
||||
root_name = Path(library).name
|
||||
images = {}
|
||||
missing = []
|
||||
for name in names:
|
||||
try:
|
||||
item = tree.get_item(['Central Libraries', root_name, 'Reusable Blocks', 'Logical-Physical', name], exact=True)
|
||||
from cbb_refresh_verify.mentor_adapter import _tree_image_details
|
||||
details = _tree_image_details(item, tree)
|
||||
images[name] = details['image_id']
|
||||
logger.info('library_tree_image_item name=%s image_id=%s selected_image_id=%s state_image_id=%s image_color=%s selected_image_color=%s state_image_color=%s',
|
||||
name, details['image_id'], details['selected_image_id'],
|
||||
details['state_image_id'], details['image_color'],
|
||||
details['selected_image_color'], details['state_image_color'])
|
||||
except Exception:
|
||||
images[name] = None
|
||||
missing.append(name)
|
||||
logger.info('library_tree_image_probe requested=%s read=%s missing=%s',
|
||||
len(names), len(names) - len(missing), missing[:20])
|
||||
return finish(images)
|
||||
if tree_image_reader is None:
|
||||
from .mentor_adapter import read_library_tree_image_map
|
||||
tree_image_reader = read_library_tree_image_map
|
||||
return finish(tree_image_reader(library, names))
|
||||
except Exception as error:
|
||||
logger.warning('library_status_probe_failed path=%s error=%s', library, error)
|
||||
return finish({})
|
||||
return {name: 'UNKNOWN' for name in names}
|
||||
|
||||
|
||||
|
||||
def read_library(path: Path, *, dispatch=None):
|
||||
|
||||
@@ -821,15 +821,16 @@ def execute_job(job, emit):
|
||||
script = Path(__file__).with_name('save_verified_block.vbs')
|
||||
cscript = Path(os.environ.get('WINDIR', r'C:\Windows'))/'SysWOW64'/'cscript.exe'
|
||||
from .desktop_worker import launch_save_helper
|
||||
helper_gate = root/'start-save.signal'
|
||||
with (root/'save.log').open('w', encoding='utf-8') as log:
|
||||
helper = launch_save_helper([str(cscript), '//nologo', str(script), job['project'],
|
||||
Path(job['pcb']).name, str(job.get('cancel_signal') or '')],
|
||||
Path(job['pcb']).name, str(job.get('cancel_signal') or ''), str(helper_gate)],
|
||||
start_gate=helper_gate, identity_path=root/'worker-state.json',
|
||||
operation_id=job.get('operation_id', root.name),
|
||||
stdout=log, stderr=log, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
emit(stage='save_helper', helper_pid=helper.pid)
|
||||
last_markers = ()
|
||||
while helper.poll() is None:
|
||||
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||
raise RuntimeError('VERIFY_CANCELLED: 已停止等待保存客户端')
|
||||
try:
|
||||
current = tuple(line.strip() for line in (root/'save.log').read_text(encoding='utf-8', errors='replace').splitlines() if line.strip())
|
||||
except OSError:
|
||||
@@ -837,14 +838,18 @@ def execute_job(job, emit):
|
||||
if current != last_markers:
|
||||
last_markers = current
|
||||
from .runtime_timing import parse_save_progress
|
||||
emit(stage='save_progress', **parse_save_progress('\n'.join(current)))
|
||||
emit(stage='save_progress', helper_exited=False, **parse_save_progress('\n'.join(current)))
|
||||
time.sleep(.2)
|
||||
code = helper.returncode
|
||||
save_log = (root/'save.log').read_bytes().decode('utf-8', errors='replace')
|
||||
from .runtime_timing import parse_save_progress
|
||||
emit(stage='save_progress', **parse_save_progress(save_log))
|
||||
emit(stage='save_progress', helper_exited=True, **parse_save_progress(save_log))
|
||||
markers = set(save_log.splitlines())
|
||||
if (code not in (None, 0)) or not save_log_has_core_markers(save_log):
|
||||
from .operation_lifecycle import classify_save_state
|
||||
write_facts = classify_save_state(save_log.splitlines(), helper_exited=True, native_released=None)
|
||||
if ((code not in (None, 0)) or not save_log_has_core_markers(save_log)
|
||||
or write_facts['save_state'] != 'COMMITTED' or write_facts['close_state'] != 'CLOSED'
|
||||
or write_facts['interrupted']):
|
||||
raise RuntimeError(f'保存/关闭未完成 ({code}): {save_log}')
|
||||
if 'QUIT_OK' not in markers:
|
||||
emit(stage='save_quit_recovered', detail='Save/Close 已确认,忽略卡住的 app.Quit。')
|
||||
@@ -887,6 +892,9 @@ def execute_job(job, emit):
|
||||
pass
|
||||
if helper is not None and helper.poll() is None:
|
||||
emit(stage='save_helper_retained', helper_pid=helper.pid)
|
||||
elif helper is not None:
|
||||
# A failed/truncated Save result never authorizes discard-close.
|
||||
emit(stage='save_result_retained', detail='保存或关闭结果不完整,保留原生会话供核对')
|
||||
elif diagnostic_close_attempted:
|
||||
# The process-bound checker already sent its sole WM_CLOSE.
|
||||
# Preserve an unknown prompt; never fall back to global COM Close.
|
||||
@@ -994,6 +1002,22 @@ def worker_main(request_path):
|
||||
root = Path(job['root'])
|
||||
|
||||
def emit(**event):
|
||||
from .session_record import update_worker_state
|
||||
phase = {'save_start': 'NATIVE_CALL', 'integration_action': 'NATIVE_CALL',
|
||||
'integration_action_complete': 'POSTCALL', 'saved_and_closed': 'RELEASE_CHECK',
|
||||
'complete': 'FINISHED', 'failed': 'UNCONFIRMED'}.get(event.get('stage'))
|
||||
identities = [(role, event.get(key)) for role, key in
|
||||
(('native', 'pcb_pid'), ('native', 'lm_pid'), ('helper', 'helper_pid'))
|
||||
if event.get(key)]
|
||||
facts = None
|
||||
if event.get('stage') == 'save_progress':
|
||||
from .operation_lifecycle import classify_save_state
|
||||
facts = classify_save_state(event.get('markers', ()),
|
||||
helper_exited=event.get('helper_exited'), native_released=None)
|
||||
phase = ('POSTCALL' if event.get('helper_exited') is True else
|
||||
'CLOSING' if 'CLOSE_START' in event.get('markers', ()) else 'NATIVE_CALL')
|
||||
if phase or identities:
|
||||
update_worker_state(job, phase or 'UNCONFIRMED', identities=identities, write_outcome=facts)
|
||||
event.update(time=time.strftime('%Y-%m-%d %H:%M:%S'), block=job['block_name'],
|
||||
monotonic_seconds=time.monotonic())
|
||||
with (root/'events.jsonl').open('a', encoding='utf-8') as stream:
|
||||
@@ -1002,7 +1026,9 @@ def worker_main(request_path):
|
||||
try:
|
||||
if job.get('supervisor_pid'):
|
||||
from .desktop_worker import start_supervisor_watchdog
|
||||
start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job.get('cancel_signal'), stop_clients=True)
|
||||
start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job.get('cancel_signal'), stop_clients=True,
|
||||
supervisor_identity=job.get('supervisor_identity'),
|
||||
session_record_path=job.get('session_record_path'), operation_id=job.get('operation_id'))
|
||||
start_gate = Path(job.get('start_gate', '')) if job.get('start_gate') else None
|
||||
if start_gate is not None:
|
||||
from .defaults import WORKER_START_GATE_TIMEOUT_SECONDS
|
||||
@@ -1450,173 +1476,58 @@ def close_library_reader(pid, desktop, *, timeout_seconds=5):
|
||||
return False
|
||||
|
||||
|
||||
def read_library_flag(library, name, *, timeout_seconds=90, log_path=None):
|
||||
"""Return (flag, detail) for one CBB by reading its tree icon.
|
||||
|
||||
Read-only: Library Manager is started on a private desktop, the tree is
|
||||
walked with messages, the icon index is read, and the process is killed.
|
||||
The cursor is never moved and no menu is opened.
|
||||
"""
|
||||
import win32con
|
||||
import win32process
|
||||
import win32service
|
||||
def _existing_library_tree_images(library, names, *, timeout_seconds):
|
||||
"""Observe a matching, enabled LM; never launch, select, answer or close it."""
|
||||
from pywinauto import Desktop
|
||||
from pywinauto.controls.common_controls import TreeViewWrapper
|
||||
|
||||
executable = library_manager_path()
|
||||
if not executable.is_file():
|
||||
return FLAG_UNKNOWN, f'找不到 Library Manager: {executable}'
|
||||
|
||||
deadline = time.monotonic() + timeout_seconds
|
||||
desktop_name = 'CbbFlagRead_' + os.urandom(5).hex()
|
||||
desktop = None
|
||||
|
||||
handle = None
|
||||
pid = None
|
||||
handled = set()
|
||||
log = log_path or Path(library).parent/'LogFiles'/'cbb_flag_read_dialogs.jsonl'
|
||||
library = Path(library)
|
||||
result = {name: None for name in names}
|
||||
try:
|
||||
desktop = win32service.CreateDesktop(desktop_name, 0, win32con.GENERIC_ALL, None)
|
||||
startup = win32process.STARTUPINFO()
|
||||
startup.lpDesktop = 'winsta0\\' + desktop_name
|
||||
handle, thread, pid, _ = win32process.CreateProcess(
|
||||
str(executable), subprocess.list2cmdline([str(executable), str(library)]),
|
||||
None, None, False, win32con.CREATE_NO_WINDOW, None, None, startup)
|
||||
thread.Close()
|
||||
target = None
|
||||
while time.monotonic() < deadline:
|
||||
target = _private_library_window(desktop, library)
|
||||
if target is not None:
|
||||
break
|
||||
handle_known_dialogs(pid, handled, log, desktop=desktop)
|
||||
time.sleep(.3)
|
||||
if target is None:
|
||||
return FLAG_UNKNOWN, 'Library Manager 窗口未就绪(状态未读取)'
|
||||
|
||||
trees = [w for w in target.descendants() if 'TreeView' in w.class_name()]
|
||||
matches = [window for window in Desktop(backend='win32').windows()
|
||||
if window.window_text().startswith('Library Manager:')
|
||||
and same_path(window.window_text().split(':', 1)[1].strip(), library)]
|
||||
if len(matches) != 1:
|
||||
return result, '未找到唯一匹配库的已打开 Library Manager,状态无法确认'
|
||||
target = matches[0]
|
||||
if not target.is_enabled():
|
||||
return result, 'Library Manager 有原生提示或正在操作,状态无法确认'
|
||||
trees = [window for window in target.descendants() if 'TreeView' in window.class_name()]
|
||||
if len(trees) != 1:
|
||||
return FLAG_UNKNOWN, '导航树不唯一(状态未读取)'
|
||||
return result, '导航树不唯一,状态无法确认'
|
||||
tree = TreeViewWrapper(trees[0].handle)
|
||||
item = tree.get_item(['Central Libraries', Path(library).name, 'Reusable Blocks', 'Logical-Physical', name], exact=True)
|
||||
item.ensure_visible()
|
||||
index = _tree_image(item, tree)
|
||||
from .library_reader import filesystem_evidence_map, infer_tree_statuses, reconcile_statuses
|
||||
evidence = filesystem_evidence_map(library, (name,))
|
||||
filesystem = {name: evidence[name]['status']}
|
||||
calibrated = infer_tree_statuses({name: index}, filesystem, (name,))
|
||||
status = reconcile_statuses(calibrated, filesystem, (name,))[name]
|
||||
flag = FLAG_GREEN if status == 'READY' else FLAG_NOT_GREEN if status == 'PENDING' else FLAG_UNKNOWN
|
||||
detail = f'图标索引 {index};持久化证据={evidence.get(name, {})};校准状态={status}'
|
||||
if flag == FLAG_UNKNOWN:
|
||||
detail += ';未取得足够的持久化证据与图标 ID 对应关系,未强行判定'
|
||||
return flag, detail
|
||||
except Exception as error:
|
||||
return FLAG_UNKNOWN, f'状态读取失败: {error}'
|
||||
finally:
|
||||
released = pid is None or close_library_reader(pid, desktop)
|
||||
if handle is not None:
|
||||
deadline = time.monotonic() + timeout_seconds
|
||||
for name in names:
|
||||
if time.monotonic() >= deadline or not target.is_enabled():
|
||||
break
|
||||
try:
|
||||
handle.Close()
|
||||
item = tree.get_item(['Central Libraries', library.name, 'Reusable Blocks',
|
||||
'Logical-Physical', name], exact=True)
|
||||
result[name] = _tree_image(item, tree)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if desktop is not None:
|
||||
desktop.CloseDesktop()
|
||||
except Exception:
|
||||
pass
|
||||
return result, '已观察匹配库的导航树图标;图标本身不是权威状态码'
|
||||
except Exception as error:
|
||||
return result, f'状态读取失败: {error}'
|
||||
|
||||
if not released:
|
||||
raise RuntimeError(f'LIBRARY_RELEASE_UNCONFIRMED: pid={pid}; desktop={desktop_name}')
|
||||
|
||||
def read_library_flag(library, name, *, timeout_seconds=90, log_path=None):
|
||||
library = Path(library)
|
||||
images, detail = _existing_library_tree_images(library, (name,), timeout_seconds=timeout_seconds)
|
||||
if images[name] is None:
|
||||
return FLAG_UNKNOWN, detail
|
||||
from .library_reader import filesystem_evidence_map, infer_tree_statuses, reconcile_statuses
|
||||
evidence = filesystem_evidence_map(library, (name,))
|
||||
filesystem = {name: evidence[name]['status']}
|
||||
calibrated = infer_tree_statuses(images, filesystem, (name,))
|
||||
status = reconcile_statuses(calibrated, filesystem, (name,))[name]
|
||||
flag = FLAG_GREEN if status == 'READY' else FLAG_NOT_GREEN if status == 'PENDING' else FLAG_UNKNOWN
|
||||
return flag, f'{detail};图标索引 {images[name]};校准状态={status}'
|
||||
|
||||
|
||||
def read_library_tree_image_map(library, names, *, timeout_seconds=45, log_path=None):
|
||||
"""Read all CBB tree icon resource IDs in one private LM session.
|
||||
|
||||
This is deliberately read-only. It avoids the previous one-process-per-
|
||||
CBB implementation, while keeping the LM window off the user's desktop.
|
||||
The returned integer is only an observation. It is logged with each CBB
|
||||
and calibrated against independent persisted Cert evidence because Mentor
|
||||
resource IDs vary by installation. Context-menu labels are not used.
|
||||
"""
|
||||
import win32con
|
||||
import win32process
|
||||
import win32service
|
||||
from pywinauto import Desktop
|
||||
from pywinauto.controls.common_controls import TreeViewWrapper
|
||||
|
||||
names = tuple(names)
|
||||
result = {name: None for name in names}
|
||||
executable = library_manager_path()
|
||||
if not executable.is_file():
|
||||
return result
|
||||
desktop_name = 'CbbStatusRead_' + os.urandom(5).hex()
|
||||
desktop = None
|
||||
handle = None
|
||||
pid = None
|
||||
handled = set()
|
||||
log = log_path or Path(library).parent/'LogFiles'/'cbb_status_read_dialogs.jsonl'
|
||||
try:
|
||||
desktop = win32service.CreateDesktop(desktop_name, 0, win32con.GENERIC_ALL, None)
|
||||
startup = win32process.STARTUPINFO()
|
||||
startup.lpDesktop = 'winsta0\\' + desktop_name
|
||||
handle, thread, pid, _ = win32process.CreateProcess(
|
||||
str(executable), subprocess.list2cmdline([str(executable), str(library)]),
|
||||
None, None, False, win32con.CREATE_NO_WINDOW, None, None, startup)
|
||||
handle.Close(); handle = None
|
||||
thread.Close()
|
||||
deadline = time.monotonic() + timeout_seconds
|
||||
target = None
|
||||
while time.monotonic() < deadline:
|
||||
target = _private_library_window(desktop, library)
|
||||
if target is not None:
|
||||
break
|
||||
handle_known_dialogs(pid, handled, log, desktop=desktop)
|
||||
time.sleep(.25)
|
||||
if target is None:
|
||||
return result
|
||||
trees = [w for w in target.descendants() if 'TreeView' in w.class_name()]
|
||||
if len(trees) != 1:
|
||||
return result
|
||||
tree = TreeViewWrapper(trees[0].handle)
|
||||
root_name = Path(library).name
|
||||
details = {}
|
||||
for name in names:
|
||||
if time.monotonic() >= deadline:
|
||||
logger.warning('library_tree_image_probe_timeout path=%s processed=%s total=%s',
|
||||
library, len(details), len(names))
|
||||
break
|
||||
try:
|
||||
item = tree.get_item(['Central Libraries', root_name, 'Reusable Blocks', 'Logical-Physical', name], exact=True)
|
||||
details[name] = _tree_image_details(item, tree)
|
||||
result[name] = details[name]['image_id']
|
||||
except Exception:
|
||||
result[name] = None
|
||||
logger.info('library_tree_images path=%s names=%s histogram=%s', library, len(names),
|
||||
dict(Counter(str(value) for value in result.values() if value is not None)))
|
||||
for name in names:
|
||||
if name in details:
|
||||
logger.info('library_tree_image_item name=%s image_id=%s selected_image_id=%s state_image_id=%s image_color=%s selected_image_color=%s state_image_color=%s',
|
||||
name, details[name]['image_id'], details[name]['selected_image_id'],
|
||||
details[name]['state_image_id'], details[name]['image_color'],
|
||||
details[name]['selected_image_color'], details[name]['state_image_color'])
|
||||
else:
|
||||
logger.warning('library_tree_image_item_missing name=%s reason=tree_path_lookup_failed', name)
|
||||
return result
|
||||
finally:
|
||||
released = pid is None or close_library_reader(pid, desktop)
|
||||
if handle is not None:
|
||||
try:
|
||||
handle.Close()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if desktop is not None:
|
||||
desktop.CloseDesktop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not released:
|
||||
raise RuntimeError(f'LIBRARY_RELEASE_UNCONFIRMED: pid={pid}; desktop={desktop_name}')
|
||||
library = Path(library)
|
||||
images, _ = _existing_library_tree_images(library, tuple(names), timeout_seconds=timeout_seconds)
|
||||
return images
|
||||
|
||||
|
||||
def read_library_status_map(library, names, *, timeout_seconds=45, log_path=None,
|
||||
|
||||
@@ -124,7 +124,7 @@ def backup_project(target, destination):
|
||||
handle.Close()
|
||||
|
||||
|
||||
def attempt_recovery(request, diagnosis, evidence_root, *, progress=None):
|
||||
def attempt_recovery(request, diagnosis, evidence_root, *, progress=None, stop=None):
|
||||
root = Path(evidence_root)/'native-repair'
|
||||
root.mkdir(exist_ok=True)
|
||||
marker = root/'attempt.json'
|
||||
@@ -152,7 +152,7 @@ def attempt_recovery(request, diagnosis, evidence_root, *, progress=None):
|
||||
raise ValueError('REPAIR_DATABASE_IN_USE: 目标的保存/关闭助手尚未退出')
|
||||
callback = (lambda event: progress({'block': request.block_name, **event})) if progress else None
|
||||
record = run_native_repair(target, root, mentor_bin=request.mentor_bin,
|
||||
timeout_seconds=max(60, request.timeout_seconds), progress=callback)
|
||||
timeout_seconds=max(60, request.timeout_seconds), progress=callback, stop=stop)
|
||||
native_status = record.get('status')
|
||||
record['release'] = repair_release_state(request, target, record)
|
||||
if native_status == 'REPAIRED' and record['release']['safe_to_continue'] is not True:
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
Option Explicit
|
||||
Dim app, doc, pi, licensing, token, expected, attempt, stable, measuredStart, operationOK, remaining
|
||||
Dim nativeError, nativeDescription
|
||||
WaitForStartGate
|
||||
CheckCancellation
|
||||
expected = WScript.Arguments(0)
|
||||
Set app = GetObject(, "MGCPCB.Application")
|
||||
Set doc = app.ActiveDocument
|
||||
@@ -17,40 +20,89 @@ token = licensing.GetToken(doc.Validate(0))
|
||||
doc.Validate token
|
||||
LogElapsed "validate", measuredStart
|
||||
WScript.Echo "LICENSE_OK"
|
||||
CheckCancellation
|
||||
WScript.Echo "SAVE_START"
|
||||
CheckCancellation
|
||||
measuredStart = Timer
|
||||
On Error Resume Next
|
||||
operationOK = doc.Save()
|
||||
nativeError = Err.Number
|
||||
nativeDescription = Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
LogElapsed "save", measuredStart
|
||||
If Not operationOK Then WScript.Quit 4
|
||||
If nativeError <> 0 Then
|
||||
WScript.Echo "SAVE_RESULT_UNKNOWN|" & CStr(nativeError) & "|" & nativeDescription
|
||||
WScript.Quit 11
|
||||
End If
|
||||
If Not operationOK Then
|
||||
WScript.Echo "SAVE_REJECTED"
|
||||
WScript.Quit 4
|
||||
End If
|
||||
WScript.Echo "SAVE_OK"
|
||||
CheckCancellation
|
||||
measuredStart = Timer
|
||||
On Error Resume Next
|
||||
operationOK = doc.IsSaved()
|
||||
nativeError = Err.Number
|
||||
nativeDescription = Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
LogElapsed "is_saved", measuredStart
|
||||
If Not operationOK Then WScript.Quit 5
|
||||
If nativeError <> 0 Or Not operationOK Then
|
||||
WScript.Echo "POST_SAVE_FAILED|" & CStr(nativeError) & "|" & nativeDescription
|
||||
WScript.Quit 5
|
||||
End If
|
||||
WScript.Echo "IS_SAVED"
|
||||
stable = False
|
||||
WScript.Echo "POST_SAVE_CHECK"
|
||||
measuredStart = Timer
|
||||
For attempt = 1 To 50
|
||||
On Error Resume Next
|
||||
Set pi = doc.ProjectIntegration
|
||||
If pi.ForwardAnnotationStatus = 2 And pi.SynchCESStatus = 2 And pi.LoadCESStatus = 2 And pi.BackAnnotationStatus = 2 Then
|
||||
stable = (pi.ForwardAnnotationStatus = 2 And pi.SynchCESStatus = 2 And pi.LoadCESStatus = 2 And pi.BackAnnotationStatus = 2)
|
||||
nativeError = Err.Number
|
||||
nativeDescription = Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
If nativeError <> 0 Then
|
||||
WScript.Echo "POST_SAVE_FAILED|" & CStr(nativeError) & "|" & nativeDescription
|
||||
WScript.Quit 7
|
||||
End If
|
||||
If stable Then
|
||||
stable = True
|
||||
Exit For
|
||||
End If
|
||||
WScript.Sleep 200
|
||||
Next
|
||||
LogElapsed "post_save_check", measuredStart
|
||||
If Not stable Then WScript.Quit 7
|
||||
If Not stable Then
|
||||
WScript.Echo "POST_SAVE_FAILED|integration_not_synchronized"
|
||||
WScript.Quit 7
|
||||
End If
|
||||
WScript.Echo "POST_SAVE_SYNCHRONIZED"
|
||||
If Not doc.IsSaved() Then WScript.Quit 8
|
||||
On Error Resume Next
|
||||
operationOK = doc.IsSaved() And LCase(pi.ProjectFile) = LCase(expected)
|
||||
If WScript.Arguments.Count > 1 Then operationOK = operationOK And LCase(doc.Name) = LCase(WScript.Arguments(1))
|
||||
nativeError = Err.Number
|
||||
nativeDescription = Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
If nativeError <> 0 Or Not operationOK Then
|
||||
WScript.Echo "POST_SAVE_FAILED|" & CStr(nativeError) & "|identity_or_saved_state_unconfirmed|" & nativeDescription
|
||||
WScript.Quit 8
|
||||
End If
|
||||
WScript.Echo "CLOSE_START"
|
||||
CheckCancellation
|
||||
measuredStart = Timer
|
||||
On Error Resume Next
|
||||
operationOK = doc.Close(True)
|
||||
nativeError = Err.Number
|
||||
nativeDescription = Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
LogElapsed "close", measuredStart
|
||||
If Not operationOK Then WScript.Quit 6
|
||||
If nativeError <> 0 Or Not operationOK Then
|
||||
WScript.Echo "CLOSE_FAILED|" & CStr(nativeError) & "|" & nativeDescription
|
||||
WScript.Quit 6
|
||||
End If
|
||||
WScript.Echo "CLOSE_OK"
|
||||
Set pi = Nothing
|
||||
Set doc = Nothing
|
||||
@@ -75,11 +127,30 @@ Sub CheckCancellation()
|
||||
If Len(cancelPath) = 0 Then Exit Sub
|
||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||
If fso.FileExists(cancelPath) Then
|
||||
WScript.Echo "CANCELLED_BEFORE_SAVE"
|
||||
WScript.Echo "VERIFY_CANCELLED"
|
||||
WScript.Quit 9
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub WaitForStartGate()
|
||||
Dim fso, started, elapsed
|
||||
If WScript.Arguments.Count < 4 Then Exit Sub
|
||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||
started = Timer
|
||||
Do
|
||||
CheckCancellation
|
||||
If fso.FileExists(WScript.Arguments(3)) Then Exit Sub
|
||||
elapsed = Timer - started
|
||||
If elapsed < 0 Then elapsed = elapsed + 86400
|
||||
If elapsed >= 30 Then
|
||||
WScript.Echo "CANCELLED_BEFORE_SAVE|start_gate_timeout"
|
||||
WScript.Quit 9
|
||||
End If
|
||||
WScript.Sleep 50
|
||||
Loop
|
||||
End Sub
|
||||
|
||||
Sub LogElapsed(phaseName, started)
|
||||
Dim elapsed
|
||||
elapsed = Timer - started
|
||||
|
||||
@@ -103,6 +103,8 @@ class VerifyResult:
|
||||
incomplete_timing_phases: tuple[str, ...] = ()
|
||||
recovery_attempts: tuple[dict, ...] = ()
|
||||
release_proof: dict | None = None
|
||||
write_outcome: dict | None = None
|
||||
session_record_path: Path | None = None
|
||||
|
||||
|
||||
def resolve_importer(mentor_bin: str | None = None) -> Path:
|
||||
@@ -229,25 +231,26 @@ def _run_process(command, timeout_seconds, cwd, *, evidence_root=None):
|
||||
|
||||
|
||||
def _stop_worker(process, *, timeout=5):
|
||||
"""Stop automation clients; native database owners are preserved."""
|
||||
"""Request stop without interrupting a possibly unreturned native call."""
|
||||
try:
|
||||
if hasattr(process, 'request_stop'):
|
||||
process.request_stop()
|
||||
else:
|
||||
process.kill()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if getattr(process, '_stop_wait_complete', False):
|
||||
return process.poll() is not None
|
||||
process.wait(timeout=timeout)
|
||||
except Exception:
|
||||
try:
|
||||
process.kill() # Automation clients only; never the native tree.
|
||||
process.wait(timeout=5)
|
||||
except Exception:
|
||||
pass
|
||||
pending = getattr(process, 'native_write_pending', lambda: False)()
|
||||
if pending is not False and not getattr(process, '_stop_wait_complete', False):
|
||||
from .defaults import NATIVE_WRITE_STOP_WAIT_SECONDS
|
||||
try:
|
||||
process.wait(timeout=max(0, NATIVE_WRITE_STOP_WAIT_SECONDS - timeout))
|
||||
except Exception:
|
||||
pass
|
||||
process._stop_wait_complete = True
|
||||
try:
|
||||
if hasattr(process, 'stop_automation_clients'):
|
||||
process.stop_automation_clients()
|
||||
return process.poll() is not None
|
||||
except Exception:
|
||||
return False
|
||||
@@ -596,7 +599,7 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
snapshot = original.evidence_path.with_name('pre-repair-result.json')
|
||||
snapshot.write_text(json.dumps(asdict(original), ensure_ascii=False, default=str, indent=2),
|
||||
encoding='utf-8')
|
||||
recovery = attempt_recovery(request, diagnosis, result.evidence_path.parent, progress=progress)
|
||||
recovery = attempt_recovery(request, diagnosis, result.evidence_path.parent, progress=progress, stop=stop)
|
||||
recovery = {**recovery, 'original_error': original.stderr,
|
||||
'original_evidence': str(original.evidence_path),
|
||||
'original_result_snapshot': str(snapshot),
|
||||
@@ -621,7 +624,7 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
result = _run_verify_serialized(
|
||||
replace(request, auto_repair=False, maintenance=False), progress=progress, flag_reader=flag_reader,
|
||||
process_runner=process_runner, port_check=port_check,
|
||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt)
|
||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
|
||||
recovery['validation_evidence'] = str(result.evidence_path or '')
|
||||
recovery['validation_passed'] = (result.status == 'PASS'
|
||||
and result.library_flag == 'GREEN' and result.safe_to_continue)
|
||||
@@ -700,6 +703,14 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
|
||||
result = _run_verify(request, timing=timing, progress=progress, flag_reader=flag_reader,
|
||||
process_runner=process_runner, port_check=port_check,
|
||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
|
||||
if result.evidence_path:
|
||||
try:
|
||||
facts = json.loads(result.evidence_path.with_name('write-outcome.json').read_text('utf-8'))
|
||||
session = result.evidence_path.with_name('session.json')
|
||||
result = replace(result, write_outcome=facts,
|
||||
session_record_path=session if session.is_file() else None)
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
if not request.auto_repair and result.evidence_path:
|
||||
try:
|
||||
release = json.loads(result.evidence_path.with_name('session-release.json').read_text('utf-8'))
|
||||
@@ -874,6 +885,10 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
'desktop': 'CbbVerify_' + uuid4().hex[:12],
|
||||
'cancel_signal': str(root/'cancel-worker.signal'),
|
||||
'start_gate': str(root/'start-worker.signal')}
|
||||
job.update(operation_id=root.name, operation='verify', library=str(request.lmc_file),
|
||||
block=request.block_name, session_record_path=str(root/'session.json'))
|
||||
from .session_record import process_identity
|
||||
job['supervisor_identity'] = process_identity(os.getpid())
|
||||
consent = None
|
||||
job_path = root/'request.json'
|
||||
try:
|
||||
@@ -919,6 +934,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
process = DesktopWorker(worker_command(job_path), job['desktop'])
|
||||
if hasattr(process, 'bind_cancellation'):
|
||||
process.bind_cancellation(job['cancel_signal'])
|
||||
if hasattr(process, 'bind_session'):
|
||||
process.bind_session(job)
|
||||
deadline = ActivityDeadline(request.timeout_seconds)
|
||||
last_activity_key = None
|
||||
phase = DialogPhase.PCB_STARTING
|
||||
@@ -950,6 +967,12 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
Path(job['start_gate']).touch()
|
||||
while process.poll() is None:
|
||||
if stop is not None and stop.is_set():
|
||||
save_markers = timing._save_markers
|
||||
detail = ('保存已返回,关闭待确认' if 'SAVE_OK' in save_markers and 'CLOSE_OK' not in save_markers else
|
||||
'已请求停止,等待当前保存返回' if phase == DialogPhase.SAVE else
|
||||
'已请求停止,等待当前原生操作返回')
|
||||
_notify_progress(progress, {'stage': 'save_stop_requested', 'block': request.block_name,
|
||||
'detail': detail})
|
||||
_stop_worker(process)
|
||||
return finish(VerifyResult('CANCELLED', stderr='已取消当前校验。',
|
||||
safe_to_continue=False, error_stage=phase.value))
|
||||
@@ -1143,7 +1166,15 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
automation_release = process.automation_release_state()
|
||||
else:
|
||||
automation_release = {'safe_to_continue': worker_exited, 'remaining_pids': []}
|
||||
process.close()
|
||||
if worker_exited:
|
||||
process.close()
|
||||
elif getattr(process, 'session_record_path', None):
|
||||
from .session_record import handoff_session
|
||||
handoff_session(process.session_record_path, evidence_root=root,
|
||||
process=process, progress=lambda state: _notify_progress(progress,
|
||||
{'stage': 'session_observation', 'block': request.block_name, **state}))
|
||||
_notify_progress(progress, {'stage': 'session_handoff', 'block': request.block_name,
|
||||
'detail': '已转后台观察,可查看状态'})
|
||||
except Exception as error:
|
||||
close_errors.append(str(error))
|
||||
if 'process' in locals():
|
||||
@@ -1189,11 +1220,23 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
release_result['remaining_pids'] = sorted(set(release_result.get('remaining_pids', []))
|
||||
| set(automation_release.get('remaining_pids', [])))
|
||||
try:
|
||||
from .operation_lifecycle import classify_save_state
|
||||
save_lines = ((root/'save.log').read_text('utf-8', errors='replace').splitlines()
|
||||
if (root/'save.log').is_file() else [])
|
||||
_write_optional_evidence(root/'write-outcome.json', classify_save_state(save_lines,
|
||||
helper_exited=(False if automation_release.get('remaining_pids') else
|
||||
True if worker_exited and automation_release.get('safe_to_continue') else None),
|
||||
native_released=release_result.get('safe_to_continue') is True))
|
||||
(root/'session-release.json').write_text(json.dumps({
|
||||
**(release_result or {}), 'block': request.block_name,
|
||||
'library': str(request.lmc_file), 'worker_exited': worker_exited,
|
||||
'worker_pid': getattr(process, 'pid', None)},
|
||||
ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
if worker_exited and release_result.get('safe_to_continue') is True and (root/'session.json').is_file():
|
||||
from .session_record import write_session_record
|
||||
write_session_record(root/'observation-supervisor.json', {
|
||||
'operation_id': job['operation_id'], 'status': 'FINISHED',
|
||||
'native_release_confirmed': True, 'worker_exited': True})
|
||||
except OSError:
|
||||
pass
|
||||
if not release_result or not release_result.get('safe_to_continue'):
|
||||
@@ -1253,12 +1296,16 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
|
||||
if max_workers != 1:
|
||||
raise ValueError('Only serial Verify is supported for the shared Library Manager session')
|
||||
if verifier is None:
|
||||
verifier = lambda request: run_verify(request, flag_reader=read_library_flag_if_available) # noqa: E731
|
||||
verifier = lambda request: run_verify(request, flag_reader=read_library_flag_if_available, stop=stop) # noqa: E731
|
||||
results = []
|
||||
queue_stop = False
|
||||
retained_libraries = set()
|
||||
for request in requests:
|
||||
library_key = str(getattr(request, 'lmc_file', '__injected_verifier_scope__')).casefold()
|
||||
if queue_stop or (stop is not None and stop.is_set()):
|
||||
result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
|
||||
elif library_key in retained_libraries:
|
||||
result = VerifyResult('SKIPPED', stderr='同库原生会话尚未释放,未启动新的写入')
|
||||
else:
|
||||
try:
|
||||
result = verifier(request)
|
||||
@@ -1267,7 +1314,9 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
|
||||
result = VerifyResult('FAIL', stderr=str(error), safe_to_continue=False)
|
||||
results.append(result)
|
||||
# Never start another writer after an unconfirmed native shutdown.
|
||||
queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'} or not result.safe_to_continue
|
||||
if not result.safe_to_continue:
|
||||
retained_libraries.add(library_key)
|
||||
queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'}
|
||||
if queue_stop and stop is not None:
|
||||
stop.set()
|
||||
if progress: _notify_progress(progress, request.block_name, result)
|
||||
|
||||
@@ -72,7 +72,7 @@ def test_crashed_worker_cannot_pass_even_with_pass_file(tmp_path, monkeypatch, o
|
||||
assert result.safe_to_continue is True # Proven release permits another item; crash stays FAIL.
|
||||
|
||||
|
||||
def test_supervisor_crash_stops_registered_save_helper_but_not_native(tmp_path):
|
||||
def test_supervisor_crash_preserves_registered_save_caller_and_native(tmp_path):
|
||||
import subprocess, sys, time
|
||||
import win32api, win32con, win32process, win32event
|
||||
supervisor = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])
|
||||
@@ -98,8 +98,9 @@ def test_supervisor_crash_stops_registered_save_helper_but_not_native(tmp_path):
|
||||
win32con.PROCESS_TERMINATE | win32con.SYNCHRONIZE, False, pid))
|
||||
supervisor.terminate()
|
||||
supervisor.wait(5)
|
||||
assert worker.wait(8) == 75
|
||||
assert win32event.WaitForSingleObject(handles[1], 3000) == win32con.WAIT_OBJECT_0
|
||||
time.sleep(.5)
|
||||
assert worker.poll() is None
|
||||
assert win32event.WaitForSingleObject(handles[1], 0) == win32con.WAIT_TIMEOUT
|
||||
assert win32process.GetExitCodeProcess(handles[0]) == 259
|
||||
finally:
|
||||
for process in (supervisor, worker):
|
||||
|
||||
@@ -66,8 +66,8 @@ def test_stop_worker_escalates_only_after_cooperative_deadline():
|
||||
if not self.stopped: raise TimeoutError()
|
||||
def kill(self): calls.append('client_stop'); self.stopped = True
|
||||
def poll(self): return 1 if self.stopped else None
|
||||
assert runner._stop_worker(Worker(), timeout=.1) is True
|
||||
assert calls == ['cancel', 'wait', 'client_stop', 'wait']
|
||||
assert runner._stop_worker(Worker(), timeout=.1) is False
|
||||
assert calls == ['cancel', 'wait']
|
||||
|
||||
|
||||
def test_cancel_reaches_current_supervised_worker(tmp_path, monkeypatch):
|
||||
@@ -223,7 +223,7 @@ def test_save_and_failure_close_clients_are_both_tracked(script, monkeypatch):
|
||||
assert proof['safe_to_continue'] is False and proof['remaining_pids'] == [22]
|
||||
|
||||
|
||||
def test_watchdog_with_cancel_signal_stops_clients_after_supervisor_exit(tmp_path):
|
||||
def test_watchdog_with_cancel_signal_retains_callers_after_supervisor_exit(tmp_path):
|
||||
import subprocess, sys, time
|
||||
import win32api, win32con, win32process
|
||||
supervisor = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])
|
||||
@@ -246,9 +246,12 @@ def test_watchdog_with_cancel_signal_stops_clients_after_supervisor_exit(tmp_pat
|
||||
for pid in json.loads(ready.read_text()):
|
||||
handles.append(win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_TERMINATE, False, pid))
|
||||
supervisor.terminate(); supervisor.wait(5)
|
||||
assert worker.wait(10) == 75 and cancel.is_file()
|
||||
deadline = time.monotonic()+3
|
||||
while not cancel.is_file() and time.monotonic()<deadline:
|
||||
time.sleep(.02)
|
||||
assert worker.poll() is None and cancel.is_file()
|
||||
assert win32process.GetExitCodeProcess(handles[0]) == 259
|
||||
assert win32process.GetExitCodeProcess(handles[1]) != 259
|
||||
assert win32process.GetExitCodeProcess(handles[1]) == 259
|
||||
finally:
|
||||
for p in (supervisor, worker):
|
||||
if p.poll() is None: p.terminate()
|
||||
|
||||
@@ -111,10 +111,12 @@ def test_reader_does_not_create_desktop_before_preparation_finishes(monkeypatch,
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reader', ['read_library_flag', 'read_library_tree_image_map'])
|
||||
def test_reader_closes_desktop_when_process_launch_fails(monkeypatch, tmp_path, reader):
|
||||
def test_reader_never_creates_a_desktop_or_process(monkeypatch, tmp_path, reader):
|
||||
import win32service
|
||||
import win32process
|
||||
import cbb_refresh_verify.mentor_adapter as module
|
||||
from pywinauto import Desktop
|
||||
monkeypatch.setattr(Desktop, 'windows', lambda *_: [])
|
||||
|
||||
closed = []
|
||||
|
||||
@@ -133,11 +135,10 @@ def test_reader_closes_desktop_when_process_launch_fails(monkeypatch, tmp_path,
|
||||
if reader == 'read_library_flag':
|
||||
flag, detail = module.read_library_flag(tmp_path / 'library.lmc', 'Block')
|
||||
assert flag == module.FLAG_UNKNOWN
|
||||
assert 'launch failed' in detail
|
||||
assert 'Library Manager' in detail
|
||||
else:
|
||||
with pytest.raises(RuntimeError, match='launch failed'):
|
||||
module.read_library_tree_image_map(tmp_path / 'library.lmc', ['Block'])
|
||||
assert closed == ['desktop']
|
||||
assert module.read_library_tree_image_map(tmp_path / 'library.lmc', ['Block']) == {'Block': None}
|
||||
assert closed == []
|
||||
|
||||
|
||||
def test_constructor_releases_private_desktop_when_process_launch_fails(monkeypatch):
|
||||
|
||||
@@ -133,7 +133,8 @@ def test_supervisor_loss_stops_automation_but_preserves_native_like_process(tmp_
|
||||
False, int(ready.read_text()))
|
||||
supervisor.terminate()
|
||||
supervisor.wait(5)
|
||||
assert worker.wait(8) == 75
|
||||
time.sleep(.5)
|
||||
assert worker.poll() is None
|
||||
assert win32process.GetExitCodeProcess(native_handle) == 259
|
||||
finally:
|
||||
if supervisor.poll() is None: supervisor.terminate()
|
||||
@@ -167,7 +168,7 @@ def test_cli_unsafe_batch_preserves_created_drive(tmp_path, monkeypatch):
|
||||
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
|
||||
monkeypatch.setattr(LibraryPathLease, 'acquire', lambda path: lease)
|
||||
monkeypatch.setattr('cbb_refresh_verify.network_path.select_library_file', lambda path: tmp_path/'lib.lmc')
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_batch', lambda requests: [VerifyResult('FAIL', safe_to_continue=False)])
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_batch', lambda requests, **kw: [VerifyResult('FAIL', safe_to_continue=False)])
|
||||
code = application.main(['--batch-lmc', r'\\server\share\lib.lmc', '--block', 'CBB', '--data-root', str(tmp_path/'run')])
|
||||
assert code == 2
|
||||
assert not backend.cancelled
|
||||
|
||||
@@ -120,7 +120,7 @@ End Class
|
||||
assert ('NATIVE_QUIT' in outcome.stdout) is (identity and close_ok and not other_document)
|
||||
|
||||
|
||||
def test_cancel_after_native_save_returns_stops_later_native_operations(tmp_path):
|
||||
def test_cancel_after_native_save_returns_keeps_save_fact_and_normal_close(tmp_path):
|
||||
source = Path('src/cbb_refresh_verify/save_verified_block.vbs').read_text('utf-8')
|
||||
classes = r'''
|
||||
Class FakePi
|
||||
@@ -182,9 +182,10 @@ End Class
|
||||
'//nologo', str(harness), 'expected.prj', 'CBB.pcb', str(tmp_path/'cancel.signal')],
|
||||
capture_output=True, text=True, timeout=10)
|
||||
assert 'NATIVE_SAVE_RETURNED' in outcome.stdout
|
||||
assert outcome.returncode == 9, outcome.stderr
|
||||
assert 'VERIFY_CANCELLED' in outcome.stdout
|
||||
assert 'CLOSE_OK' not in outcome.stdout
|
||||
assert 'SAVE_OK' in outcome.stdout
|
||||
assert 'CLOSE_OK' in outcome.stdout
|
||||
assert 'SAVE_REJECTED' not in outcome.stdout
|
||||
assert outcome.returncode == 10, outcome.stderr # FakeApp retains another document.
|
||||
|
||||
|
||||
def test_worker_attempts_normal_close_after_idle_integration_failure(tmp_path, monkeypatch):
|
||||
@@ -200,14 +201,16 @@ def test_worker_attempts_normal_close_after_idle_integration_failure(tmp_path, m
|
||||
assert not any(event['stage'] == 'save_start' for event in events)
|
||||
|
||||
|
||||
def test_stop_cancels_then_stops_automation_client_after_deadline(tmp_path):
|
||||
def test_stop_cancels_without_killing_pending_native_call(tmp_path):
|
||||
calls = []
|
||||
class BusyWorker:
|
||||
def request_stop(self): calls.append('cancel')
|
||||
def wait(self, timeout): raise TimeoutError('native Save still running')
|
||||
def kill(self): calls.append('kill')
|
||||
runner._stop_worker(BusyWorker(), timeout=0)
|
||||
assert calls == ['cancel', 'kill']
|
||||
def stop_automation_clients(self): calls.append('stop-helper')
|
||||
def poll(self): return None
|
||||
assert runner._stop_worker(BusyWorker(), timeout=0) is False
|
||||
assert calls == ['cancel']
|
||||
|
||||
|
||||
def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path):
|
||||
@@ -255,13 +258,14 @@ def test_shared_address_is_diagnostic_after_successful_native_execution(tmp_path
|
||||
assert any(event['stage'] == 'icdb_address_remaining' for event in events)
|
||||
|
||||
|
||||
def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path):
|
||||
@pytest.mark.parametrize('stop_clients', [False, True])
|
||||
def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path, stop_clients):
|
||||
import win32api, win32con, win32process
|
||||
supervisor = subprocess.Popen([sys.executable, '-c', 'import time;time.sleep(30)'])
|
||||
script, ready, cancel = tmp_path/'worker.py', tmp_path/'ready.json', tmp_path/'cancel.signal'
|
||||
script.write_text('import subprocess,sys,time,json\nfrom pathlib import Path\n'
|
||||
'from cbb_refresh_verify.desktop_worker import start_supervisor_watchdog,launch_save_helper\n'
|
||||
f'start_supervisor_watchdog({supervisor.pid},cancel_path={str(cancel)!r})\n'
|
||||
f'start_supervisor_watchdog({supervisor.pid},cancel_path={str(cancel)!r},stop_clients={stop_clients!r})\n'
|
||||
'helper=launch_save_helper([sys.executable,"-c","import time;time.sleep(30)"])\n'
|
||||
f'Path({str(ready)!r}).write_text(json.dumps(helper.pid))\n'
|
||||
'time.sleep(30)\n', encoding='utf-8')
|
||||
@@ -280,6 +284,7 @@ def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path):
|
||||
while not cancel.exists() and time.monotonic()<deadline:
|
||||
time.sleep(.05)
|
||||
assert cancel.exists()
|
||||
time.sleep(5.2 if stop_clients else .1)
|
||||
assert worker.poll() is None
|
||||
assert win32process.GetExitCodeProcess(handle) == 259
|
||||
finally:
|
||||
|
||||
@@ -323,7 +323,7 @@ def test_status_scan_logs_each_cbb_image_id(caplog, tmp_path):
|
||||
assert 'name=B image_id=28' in caplog.text
|
||||
|
||||
|
||||
def test_status_scan_keeps_only_missing_cert_or_project_items_pending(tmp_path):
|
||||
def test_status_scan_without_native_observation_does_not_guess_status(tmp_path):
|
||||
lmc = tmp_path / 'center.lmc'
|
||||
lmc.touch()
|
||||
root = lmc.parent / 'ReusableBlocksLP'
|
||||
@@ -348,7 +348,7 @@ def test_status_scan_keeps_only_missing_cert_or_project_items_pending(tmp_path):
|
||||
('READY_CBB', 'IP101GR', 'MISSING_CBB'),
|
||||
tree_image_reader=lambda _library, _names: {},
|
||||
)
|
||||
assert result == {'READY_CBB': 'READY', 'IP101GR': 'PENDING', 'MISSING_CBB': 'PENDING'}
|
||||
assert result == {'READY_CBB': 'UNKNOWN', 'IP101GR': 'UNKNOWN', 'MISSING_CBB': 'UNKNOWN'}
|
||||
|
||||
|
||||
def test_filesystem_evidence_exposes_multiple_persistent_dimensions(tmp_path):
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
from dataclasses import replace
|
||||
import json
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
from test_verify_runner import fixture, request
|
||||
|
||||
|
||||
def test_default_batch_verifier_receives_current_stop(monkeypatch, tmp_path):
|
||||
stop = threading.Event()
|
||||
received = []
|
||||
def verify(req, **kw):
|
||||
received.append(kw.get('stop'))
|
||||
return runner.VerifyResult('FAIL')
|
||||
monkeypatch.setattr(runner, 'run_verify', verify)
|
||||
runner.run_batch([request(tmp_path)], stop=stop)
|
||||
assert received == [stop]
|
||||
|
||||
|
||||
def test_stopped_helper_save_fact_survives_supervisor_finally(tmp_path, monkeypatch):
|
||||
fixture(tmp_path)
|
||||
stop = threading.Event()
|
||||
class SavingWorker:
|
||||
desktop = None
|
||||
pid = None
|
||||
returncode = None
|
||||
def __init__(self, command, *_a, **_kw):
|
||||
self.root = __import__('pathlib').Path(command[-1]).parent
|
||||
(self.root/'save.log').write_text('SAVE_START\nSAVE_OK\nCLOSE_START\n')
|
||||
stop.set()
|
||||
def poll(self): return None
|
||||
def request_stop(self): pass
|
||||
def wait(self, timeout): raise TimeoutError('Close pending')
|
||||
def kill(self): pytest.fail('Stop/finally interrupted native Close')
|
||||
def stop_automation_clients(self): pytest.fail('Save caller was killed')
|
||||
def close(self): pass
|
||||
def automation_release_state(self):
|
||||
return {'safe_to_continue': False, 'remaining_pids': [42]}
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', SavingWorker)
|
||||
monkeypatch.setattr(runner, '_cleanup_session_processes',
|
||||
lambda *a, **kw: {'safe_to_continue': False, 'remaining_pids': []})
|
||||
result = runner.run_verify(request(tmp_path), stop=stop, port_check=lambda: (True, ''))
|
||||
assert result.status == 'CANCELLED'
|
||||
assert result.safe_to_continue is False
|
||||
assert result.write_outcome['save_state'] == 'COMMITTED'
|
||||
assert result.write_outcome['close_state'] == 'UNKNOWN'
|
||||
assert result.write_outcome['helper_state'] == 'RUNNING'
|
||||
|
||||
|
||||
def test_unreleased_library_does_not_cancel_an_independent_library(tmp_path):
|
||||
first = request(tmp_path)
|
||||
second = replace(first, lmc_file=tmp_path/'other.lmc')
|
||||
calls = []
|
||||
def verify(req):
|
||||
calls.append(req.lmc_file)
|
||||
return runner.VerifyResult('TIMEOUT', safe_to_continue=req == second)
|
||||
stop = threading.Event()
|
||||
results = runner.run_batch([first, second, first], stop=stop, verifier=verify)
|
||||
assert calls == [first.lmc_file, second.lmc_file]
|
||||
assert [r.status for r in results] == ['TIMEOUT', 'TIMEOUT', 'SKIPPED']
|
||||
assert not stop.is_set()
|
||||
|
||||
|
||||
def test_contradictory_helper_result_cannot_be_promoted_by_core_success_markers(tmp_path, monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
from test_verify_worker_stability import exercise_worker
|
||||
from cbb_refresh_verify import mentor_adapter
|
||||
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
def helper(command, **kw):
|
||||
kw['stdout'].write('LICENSE_OK\nSAVE_OK\nSAVE_REJECTED\nIS_SAVED\nPOST_SAVE_SYNCHRONIZED\nCLOSE_OK\nQUIT_OK\n')
|
||||
kw['stdout'].flush()
|
||||
return SimpleNamespace(pid=3, poll=lambda: 0, returncode=0)
|
||||
monkeypatch.setattr(mentor_adapter.subprocess, 'Popen', helper)
|
||||
with pytest.raises(RuntimeError, match='保存/关闭未完成'):
|
||||
execute()
|
||||
assert not any(event['stage'] == 'complete' for event in events)
|
||||
@@ -0,0 +1,41 @@
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
from cbb_refresh_verify.library_reader import scan_open_library_status
|
||||
|
||||
|
||||
@pytest.mark.parametrize('prompt', ['', 'Repair database', 'Overwrite existing library',
|
||||
'Save changes?', 'Unknown license warning'])
|
||||
def test_compat_readers_neither_launch_nor_answer_native_prompts(monkeypatch, tmp_path, prompt):
|
||||
import win32process, win32service, win32gui
|
||||
from pywinauto import Desktop
|
||||
def forbidden(*a, **kw):
|
||||
pytest.fail('status observation attempted a native action')
|
||||
monkeypatch.setattr(win32process, 'CreateProcess', forbidden)
|
||||
monkeypatch.setattr(win32service, 'CreateDesktop', forbidden)
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', forbidden)
|
||||
monkeypatch.setattr(adapter, 'handle_known_dialogs', forbidden)
|
||||
monkeypatch.setattr(adapter, 'close_library_reader', forbidden)
|
||||
library = tmp_path/'lib.lmc'
|
||||
target = SimpleNamespace(window_text=lambda: f'Library Manager: {library}',
|
||||
is_enabled=lambda: not bool(prompt), descendants=lambda: [], handle=0)
|
||||
monkeypatch.setattr(Desktop, 'windows', lambda *_: [target] if prompt else [])
|
||||
assert adapter.read_library_flag(library, 'A')[0] == adapter.FLAG_UNKNOWN
|
||||
assert adapter.read_library_tree_image_map(library, ['A']) == {'A': None}
|
||||
assert scan_open_library_status(library, ['A']) == {'A': 'UNKNOWN'}
|
||||
|
||||
|
||||
def test_wrong_library_window_is_not_a_status_source(monkeypatch, tmp_path):
|
||||
from pywinauto import Desktop
|
||||
import win32process, win32service
|
||||
monkeypatch.setattr(win32process, 'CreateProcess', lambda *a, **kw: pytest.fail('implicit launch'))
|
||||
monkeypatch.setattr(win32service, 'CreateDesktop', lambda *a, **kw: pytest.fail('implicit desktop'))
|
||||
def forbidden():
|
||||
pytest.fail('read another library tree')
|
||||
window = SimpleNamespace(window_text=lambda: 'Library Manager: C:/Other/lib.lmc',
|
||||
descendants=forbidden)
|
||||
monkeypatch.setattr(Desktop, 'windows', lambda *_: [window])
|
||||
assert adapter.read_library_tree_image_map(tmp_path/'lib.lmc', ['A']) == {'A': None}
|
||||
@@ -113,7 +113,7 @@ def _without_authorized_checkpoint_cleanup(text):
|
||||
tree = ast.parse(text)
|
||||
parents = {child: parent for parent in ast.walk(tree) for child in ast.iter_child_nodes(parent)}
|
||||
allowed = {('LibraryLock', '_exit_owned'): 'marker', ('LibraryLock', '__enter__'): 'marker',
|
||||
('release_retained_library',): 'checkpoint'}
|
||||
('release_retained_library',): 'checkpoint', ('write_session_record',): 'pending'}
|
||||
used, spans = set(), []
|
||||
for call in ast.walk(tree):
|
||||
if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute)
|
||||
@@ -127,7 +127,7 @@ def _without_authorized_checkpoint_cleanup(text):
|
||||
scope = tuple(scope)
|
||||
if scope in used or allowed.get(scope) != call.func.value.id:
|
||||
continue
|
||||
expected = ([('missing_ok', True)] if scope == ('LibraryLock', '_exit_owned') else [])
|
||||
expected = ([('missing_ok', True)] if scope in (('LibraryLock', '_exit_owned'), ('write_session_record',)) else [])
|
||||
keywords = [(k.arg, k.value.value if isinstance(k.value, ast.Constant) else None) for k in call.keywords]
|
||||
if keywords == expected and call.lineno == call.end_lineno:
|
||||
spans.append((call.lineno - 1, call.col_offset, call.end_col_offset))
|
||||
@@ -143,7 +143,7 @@ def _without_authorized_checkpoint_cleanup(text):
|
||||
def test_verification_never_deletes_or_moves_library_files():
|
||||
for path in production_sources():
|
||||
text = path.read_text(encoding='utf-8')
|
||||
if path == SOURCE_ROOT/'library_lock.py':
|
||||
if path.name in ('library_lock.py', 'session_record.py'):
|
||||
# Approved runtime JSON lifecycle only. Actual sidecar/engineering
|
||||
# protection is also exercised against real files below.
|
||||
text = _without_authorized_checkpoint_cleanup(text)
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify.desktop_worker import launch_save_helper
|
||||
|
||||
|
||||
def test_helper_gate_only_opens_after_exact_identity_is_durable(tmp_path):
|
||||
gate, journal, called = tmp_path/'gate', tmp_path/'worker-state.json', tmp_path/'called.json'
|
||||
script = tmp_path/'helper.py'
|
||||
script.write_text('import json,time\nfrom pathlib import Path\n'
|
||||
f'gate=Path({str(gate)!r})\n'
|
||||
'while not gate.exists(): time.sleep(.02)\n'
|
||||
f'Path({str(called)!r}).write_text(Path({str(journal)!r}).read_text())\n')
|
||||
helper = None
|
||||
try:
|
||||
helper = launch_save_helper([sys.executable, str(script)], start_gate=gate,
|
||||
identity_path=journal, operation_id='test-gate')
|
||||
helper.wait(5)
|
||||
record = json.loads(called.read_text())
|
||||
assert record['operation_id'] == 'test-gate'
|
||||
identity = record['processes'][0]
|
||||
assert identity['pid'] == helper.pid
|
||||
assert identity['created_handle'] and identity['owner_sid']
|
||||
assert identity['image'].casefold() == sys.executable.casefold()
|
||||
finally:
|
||||
if helper is not None and helper.poll() is None:
|
||||
helper.terminate()
|
||||
helper.wait(5)
|
||||
|
||||
|
||||
def test_identity_storage_failure_does_not_allow_native_call(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import desktop_worker
|
||||
gate = tmp_path/'gate'
|
||||
script = tmp_path/'helper.py'
|
||||
script.write_text('import time;time.sleep(.5)')
|
||||
created = []
|
||||
real_popen = subprocess.Popen
|
||||
def popen(*a, **kw):
|
||||
process = real_popen(*a, **kw)
|
||||
created.append(process)
|
||||
return process
|
||||
monkeypatch.setattr(desktop_worker.subprocess, 'Popen', popen)
|
||||
def fail(*a, **kw):
|
||||
raise OSError('journal unavailable')
|
||||
monkeypatch.setattr('cbb_refresh_verify.session_record.write_session_record', fail)
|
||||
with pytest.raises(OSError, match='journal unavailable'):
|
||||
launch_save_helper([sys.executable, str(script)], start_gate=gate,
|
||||
identity_path=tmp_path/'worker-state.json', operation_id='test')
|
||||
assert not gate.exists()
|
||||
for process in created:
|
||||
process.wait(5)
|
||||
@@ -85,3 +85,119 @@ End Class
|
||||
assert completed.returncode == 4, completed.stderr
|
||||
assert 'SAVE_OK' not in parsed['markers']
|
||||
assert 'CLOSE_OK' not in parsed['markers']
|
||||
|
||||
|
||||
def run_helper(tmp_path, *, save_body='Save = True', close_body='Close = True',
|
||||
is_saved='True', gated=False, cancelled=False):
|
||||
source = Path('src/cbb_refresh_verify/save_verified_block.vbs').read_text('utf-8')
|
||||
classes = '''
|
||||
Class FakePi
|
||||
Public ProjectFile, ForwardAnnotationStatus, SynchCESStatus, LoadCESStatus, BackAnnotationStatus
|
||||
Private Sub Class_Initialize
|
||||
ProjectFile = WScript.Arguments(0)
|
||||
ForwardAnnotationStatus = 2
|
||||
SynchCESStatus = 2
|
||||
LoadCESStatus = 2
|
||||
BackAnnotationStatus = 2
|
||||
End Sub
|
||||
End Class
|
||||
Class FakeDoc
|
||||
Public Name
|
||||
Private Sub Class_Initialize
|
||||
Name = "CBB.pcb"
|
||||
End Sub
|
||||
Public Property Get ProjectIntegration
|
||||
Set ProjectIntegration = New FakePi
|
||||
End Property
|
||||
Public Function Validate(token)
|
||||
Validate = 17
|
||||
End Function
|
||||
Public Function Save()
|
||||
WScript.Echo "TEST_SAVE_CALLED"
|
||||
SAVE_BODY
|
||||
End Function
|
||||
Public Function IsSaved()
|
||||
IsSaved = IS_SAVED_VALUE
|
||||
End Function
|
||||
Public Function Close(saveChanges)
|
||||
CLOSE_BODY
|
||||
closedDoc = True
|
||||
End Function
|
||||
End Class
|
||||
Class FakeApp
|
||||
Public Property Get ActiveDocument
|
||||
If closedDoc Then
|
||||
Set ActiveDocument = Nothing
|
||||
Else
|
||||
Set ActiveDocument = New FakeDoc
|
||||
End If
|
||||
End Property
|
||||
Public Sub Quit()
|
||||
WScript.Echo "TEST_QUIT"
|
||||
End Sub
|
||||
End Class
|
||||
Class FakeLic
|
||||
Public Function GetToken(value)
|
||||
GetToken = value
|
||||
End Function
|
||||
End Class
|
||||
'''.replace('SAVE_BODY', save_body).replace('CLOSE_BODY', close_body).replace('IS_SAVED_VALUE', is_saved)
|
||||
source = source.replace('Option Explicit', 'Option Explicit\nDim closedDoc\n' + classes)
|
||||
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
|
||||
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
|
||||
harness = tmp_path/'facts.vbs'
|
||||
harness.write_text(source, encoding='ascii')
|
||||
cancel = tmp_path/'cancel.signal'
|
||||
if cancelled:
|
||||
cancel.touch()
|
||||
args = [str(Path(os.environ['WINDIR'])/'SysWOW64/cscript.exe'), '//nologo',
|
||||
str(harness), 'expected.prj', 'CBB.pcb', str(cancel)]
|
||||
if gated:
|
||||
args.append(str(tmp_path/'start.signal'))
|
||||
return subprocess.run(args, capture_output=True, text=True, timeout=35)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('body,marker', [('Close = False', 'CLOSE_FAILED'),
|
||||
('Err.Raise 5, "FakeDoc", "close failed"', 'CLOSE_FAILED')])
|
||||
def test_close_failure_keeps_successful_save_fact(tmp_path, body, marker):
|
||||
result = run_helper(tmp_path, close_body=body)
|
||||
assert 'SAVE_OK' in result.stdout
|
||||
assert marker in result.stdout
|
||||
assert 'CLOSE_OK' not in result.stdout
|
||||
assert result.returncode != 0
|
||||
|
||||
|
||||
def test_save_exception_has_unknown_result_marker(tmp_path):
|
||||
result = run_helper(tmp_path, save_body='Err.Raise 5, "FakeDoc", "save failed"')
|
||||
assert 'SAVE_RESULT_UNKNOWN|5|' in result.stdout
|
||||
assert 'CLOSE_START' not in result.stdout
|
||||
assert result.returncode != 0
|
||||
|
||||
|
||||
def test_saved_document_postcheck_failure_does_not_discard_save_fact(tmp_path):
|
||||
result = run_helper(tmp_path, is_saved='False')
|
||||
assert 'SAVE_OK' in result.stdout
|
||||
assert 'POST_SAVE_FAILED' in result.stdout
|
||||
assert 'CLOSE_START' not in result.stdout
|
||||
|
||||
|
||||
def test_cancellation_in_save_allows_identity_checked_saved_close(tmp_path):
|
||||
result = run_helper(tmp_path, save_body='''
|
||||
Dim fso, flag
|
||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||
Set flag = fso.CreateTextFile(WScript.Arguments(2), True)
|
||||
flag.Close
|
||||
Save = True
|
||||
''')
|
||||
assert 'SAVE_OK' in result.stdout
|
||||
assert 'CLOSE_OK' in result.stdout
|
||||
assert 'QUIT_OK' in result.stdout
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
def test_unopened_gate_cancellation_exits_before_com(tmp_path):
|
||||
result = run_helper(tmp_path, gated=True, cancelled=True)
|
||||
assert 'CANCELLED_BEFORE_SAVE' in result.stdout
|
||||
assert 'TEST_SAVE_CALLED' not in result.stdout
|
||||
assert 'VALIDATE_START' not in result.stdout
|
||||
assert result.returncode == 9
|
||||
@@ -499,8 +499,7 @@ def test_parallelism_rejected_for_shared_library(tmp_path):
|
||||
run_batch([], max_workers=2)
|
||||
|
||||
|
||||
def test_timeout_stops_automation_and_allows_retry_when_no_native_owner_remains(tmp_path, monkeypatch):
|
||||
"""A timed-out item must not leave a Mentor process holding the library."""
|
||||
def test_timeout_without_release_evidence_preserves_native_caller(tmp_path, monkeypatch):
|
||||
fixture(tmp_path)
|
||||
killed = []
|
||||
|
||||
@@ -520,11 +519,11 @@ def test_timeout_stops_automation_and_allows_retry_when_no_native_owner_remains(
|
||||
port_check=PORTS_OK)
|
||||
|
||||
assert result.status == 'TIMEOUT'
|
||||
assert killed == [True]
|
||||
assert result.safe_to_continue
|
||||
assert killed == []
|
||||
assert result.safe_to_continue is False
|
||||
|
||||
|
||||
def test_fatal_dialog_terminates_current_worker_and_cannot_become_pass(tmp_path, monkeypatch):
|
||||
def test_fatal_dialog_preserves_current_worker_and_cannot_become_pass(tmp_path, monkeypatch):
|
||||
fixture(tmp_path)
|
||||
killed = []
|
||||
|
||||
@@ -557,7 +556,7 @@ def test_fatal_dialog_terminates_current_worker_and_cannot_become_pass(tmp_path,
|
||||
|
||||
assert result.status == 'FAIL'
|
||||
assert result.stderr.startswith('SAVE_REUSABLE_BLOCK_FAILED')
|
||||
assert killed == [True]
|
||||
assert killed == []
|
||||
|
||||
|
||||
def test_worker_events_advance_dialog_phase():
|
||||
@@ -631,7 +630,7 @@ def test_unknown_dialog_writes_snapshot_before_current_item_fails(tmp_path, monk
|
||||
assert '"error_code": "UNKNOWN_DIALOG"' in dialog_records
|
||||
assert 'Unknown recovery prompt' in dialog_records
|
||||
assert (evidence/'process_tree.json').is_file()
|
||||
assert killed == [True]
|
||||
assert killed == []
|
||||
|
||||
|
||||
def test_library_flag_is_reported_verbatim_and_never_fabricated(tmp_path, monkeypatch):
|
||||
|
||||
Reference in new issue
Block a user