fix: preserve native calls on stop and keep status reads observational

This commit is contained in:
阿白叔 committed 2026-11-06 15:42:33 +08:00
1 parent 97a3de20c9
commit 8d3eab1164
19 files changed
+631 -290

No files matched your search

+1
View File
@@ -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
+67 -25
View File
@@ -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:
+8 -41
View File
@@ -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):
+73 -162
View File
@@ -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,
+2 -2
View File
@@ -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:
+80 -9
View File
@@ -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
+64 -15
View File
@@ -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)