fix: prove prewrite cancellation and bound recovery metadata lifetime

This commit is contained in:
阿白叔 committed 2026-11-17 12:45:59 +08:00
1 parent 32dcd80d1e
commit 906cfc06be
14 files changed
+633 -34

No files matched your search

+31 -10
View File
@@ -164,7 +164,7 @@ def _align_library(project, pcb, library):
def recover_from_backup(request, source, *, progress=None, verifier=None, idle_check=None, version_prompt=None,stop=None): def recover_from_backup(request, source, *, progress=None, verifier=None, idle_check=None, version_prompt=None,stop=None):
"""Validate in copies before changing Work; preserve all recovery evidence.""" """Validate in copies before changing Work; preserve all recovery evidence."""
import pythoncom, win32con, win32event from .operation_queue import check_active, local_commit, note_metadata_progress, QueueCancelled
from .network_path import absolute_preserving_drive from .network_path import absolute_preserving_drive
from .verify_runner import run_verify, read_library_flag_if_available from .verify_runner import run_verify, read_library_flag_if_available
verifier = verifier or run_verify verifier = verifier or run_verify
@@ -187,11 +187,16 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
return VerifyResult('BLOCKED', stderr='恢复记录目录不能位于备份工程内。') return VerifyResult('BLOCKED', stderr='恢复记录目录不能位于备份工程内。')
if validation_dir.is_relative_to(library_root) or validation_dir.is_relative_to(source.parent): if validation_dir.is_relative_to(library_root) or validation_dir.is_relative_to(source.parent):
return VerifyResult('BLOCKED', stderr='本机验证目录不能位于目标库或备份工程内。') return VerifyResult('BLOCKED', stderr='本机验证目录不能位于目标库或备份工程内。')
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
library_lock = None library_lock = None
release_confirmed = True release_confirmed = True
installed = False installed = False
def check():
check_active()
if stop is not None and stop.is_set():
raise QueueCancelled('恢复已取消,未提交后续操作。')
def completed():
check()
note_metadata_progress()
record = {'operation': 'same_cbb_complete_project_restore', 'source': str(source), record = {'operation': 'same_cbb_complete_project_restore', 'source': str(source),
'library': str(library), 'block': request.block_name, 'installed': False, 'library': str(library), 'block': request.block_name, 'installed': False,
'validation_library': str(validation_dir/library.name), 'backup_policy': 'manual'} 'validation_library': str(validation_dir/library.name), 'backup_policy': 'manual'}
@@ -216,23 +221,25 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
from .com_runtime import initialize_com, uninitialize_com from .com_runtime import initialize_com, uninitialize_com
initialized = initialize_com() initialized = initialize_com()
try: try:
acquired = win32event.WaitForSingleObject(mutex, 0) in ( check()
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
return VerifyResult('BLOCKED', stderr='已有 CBB 任务运行,请等待结束。', safe_to_continue=False)
from .library_lock import LibraryLock from .library_lock import LibraryLock
library_lock = LibraryLock(library, safe_to_release=lambda: release_confirmed) library_lock = LibraryLock(library, safe_to_release=lambda: release_confirmed)
library_lock.__enter__() library_lock.__enter__()
if source.is_relative_to(library_root): if source.is_relative_to(library_root):
raise ValueError('请选择目标中心库之外的独立备份工程。') raise ValueError('请选择目标中心库之外的独立备份工程。')
project, pcb = preflight(replace(request, lmc_file=library)) project, pcb = preflight(replace(request, lmc_file=library))
completed()
source_pcb = _source_check(source, request.block_name, project) source_pcb = _source_check(source, request.block_name, project)
completed()
root.mkdir(parents=True, exist_ok=False) root.mkdir(parents=True, exist_ok=False)
idle_check(library, project, pcb) idle_check(library, project, pcb)
completed()
idle_check(library, source, source_pcb) idle_check(library, source, source_pcb)
completed()
validation_base.mkdir(parents=True, exist_ok=True) validation_base.mkdir(parents=True, exist_ok=True)
library_size = sum(info.st_size for info in _scan(library_root).values() if stat.S_ISREG(info.st_mode)) library_size = sum(info.st_size for info in _scan(library_root).values() if stat.S_ISREG(info.st_mode))
source_size = sum(info.st_size for info in _scan(source.parent).values() if stat.S_ISREG(info.st_mode)) source_size = sum(info.st_size for info in _scan(source.parent).values() if stat.S_ISREG(info.st_mode))
completed()
same_drive = root.anchor.casefold() == validation_dir.anchor.casefold() same_drive = root.anchor.casefold() == validation_dir.anchor.casefold()
required = (library_size + source_size * 2) if same_drive else 0 required = (library_size + source_size * 2) if same_drive else 0
if (shutil.disk_usage(root).free < required if (shutil.disk_usage(root).free < required
@@ -244,6 +251,7 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
library_scope = ManifestScope.library(request.block_name, library.name) library_scope = ManifestScope.library(request.block_name, library.name)
original_manifest = _copy_verified(library_root, validation_dir, scope=library_scope, original_manifest = _copy_verified(library_root, validation_dir, scope=library_scope,
progress=copy_progress('prepare_source', '正在准备验证库:')) progress=copy_progress('prepare_source', '正在准备验证库:'))
completed()
(root/'library-baseline-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8') (root/'library-baseline-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8')
staged_library = validation_dir/library.name staged_library = validation_dir/library.name
staged_work = staged_library.parent/'ReusableBlocksLP'/request.block_name/'Work' staged_work = staged_library.parent/'ReusableBlocksLP'/request.block_name/'Work'
@@ -252,8 +260,10 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
if not resolved_work.is_relative_to(validation_dir.resolve()): if not resolved_work.is_relative_to(validation_dir.resolve()):
raise ValueError('验证副本工程路径越界。') raise ValueError('验证副本工程路径越界。')
shutil.rmtree(resolved_work) shutil.rmtree(resolved_work)
completed()
source_manifest = _copy_verified(source.parent, staged_work, source_manifest = _copy_verified(source.parent, staged_work,
progress=copy_progress('prepare_source', '正在准备备份验证工程:')) progress=copy_progress('prepare_source', '正在准备备份验证工程:'))
completed()
(root/'source-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8') (root/'source-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8')
staged_project = staged_work/source.name staged_project = staged_work/source.name
staged_pcb = staged_work/source_pcb.relative_to(source.parent) staged_pcb = staged_work/source_pcb.relative_to(source.parent)
@@ -263,32 +273,44 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
auto_repair=False, libspec='', dms_login_config='', mapped_drive='', mapped_remote_root='', auto_repair=False, libspec='', dms_login_config='', mapped_drive='', mapped_remote_root='',
native_lm_verify=False, interactive_input=False) native_lm_verify=False, interactive_input=False)
preflight(validation) preflight(validation)
completed()
emit('validate_source', '正在副本中打开备份工程并执行原生校验…') emit('validate_source', '正在副本中打开备份工程并执行原生校验…')
check()
release_confirmed = False release_confirmed = False
choice_options = {'version_prompt': version_prompt} if version_prompt is not None else {} choice_options = {'version_prompt': version_prompt} if version_prompt is not None else {}
if stop is not None:choice_options['stop']=stop if stop is not None:choice_options['stop']=stop
source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available, **choice_options) source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available, **choice_options)
release_confirmed = source_result.safe_to_continue release_confirmed = source_result.safe_to_continue
record['source_validation'] = asdict(source_result) record['source_validation'] = asdict(source_result)
completed()
if (source_result.status != 'PASS' or source_result.library_flag != 'GREEN' if (source_result.status != 'PASS' or source_result.library_flag != 'GREEN'
or not source_result.safe_to_continue): or not source_result.safe_to_continue):
return save(replace(source_result, status='FAIL', stderr= return save(replace(source_result, status='FAIL', stderr=
'备份校验未通过,目标未更改。\n' + (source_result.stderr or source_result.library_flag_detail))) '备份校验未通过,目标未更改。\n' + (source_result.stderr or source_result.library_flag_detail)))
idle_check(library, project, pcb) idle_check(library, project, pcb)
completed()
idle_check(staged_library, staged_project, staged_pcb) idle_check(staged_library, staged_project, staged_pcb)
completed()
token = root.name.removeprefix('backup-restore-') token = root.name.removeprefix('backup-restore-')
work = project.parent.resolve() work = project.parent.resolve()
incoming = work.with_name('Work.restore-' + token) incoming = work.with_name('Work.restore-' + token)
retained = work.with_name('Work.before-restore-' + token) retained = work.with_name('Work.before-restore-' + token)
_copy_verified(staged_work, incoming, _copy_verified(staged_work, incoming,
progress=copy_progress('prepare_source', '正在准备恢复工程:')) progress=copy_progress('prepare_source', '正在准备恢复工程:'))
completed()
_align_library(incoming/source.name, incoming/source_pcb.relative_to(source.parent), library) _align_library(incoming/source.name, incoming/source_pcb.relative_to(source.parent), library)
completed()
idle_check(library, source, source_pcb) idle_check(library, source, source_pcb)
completed()
if _manifest(source.parent) != source_manifest: if _manifest(source.parent) != source_manifest:
raise ValueError('备份来源在验证期间发生变化,目标未更改。') raise ValueError('备份来源在验证期间发生变化,目标未更改。')
completed()
if _manifest(library_root, scope=library_scope, exclude=incoming.resolve()) != original_manifest: if _manifest(library_root, scope=library_scope, exclude=incoming.resolve()) != original_manifest:
raise ValueError('目标中心库在验证期间发生变化,停止恢复。') raise ValueError('目标中心库在验证期间发生变化,停止恢复。')
completed()
emit('install', '备份已通过验证,正在保留原工程并恢复…') emit('install', '备份已通过验证,正在保留原工程并恢复…')
check()
with local_commit():
work.rename(retained) work.rename(retained)
try: try:
incoming.rename(work) incoming.rename(work)
@@ -297,7 +319,9 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
raise raise
installed = True installed = True
record['retained_work'] = str(retained) record['retained_work'] = str(retained)
completed()
emit('verify_target', '正在重新打开恢复后的目标工程并校验…') emit('verify_target', '正在重新打开恢复后的目标工程并校验…')
check()
release_confirmed = False release_confirmed = False
final = verifier(replace(request, lmc_file=library, evidence_dir=root/'target-verify', final = verifier(replace(request, lmc_file=library, evidence_dir=root/'target-verify',
auto_repair=False, native_lm_verify=False, interactive_input=False), auto_repair=False, native_lm_verify=False, interactive_input=False),
@@ -320,7 +344,4 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
if library_lock is not None: if library_lock is not None:
library_lock.__exit__(None, None, None) library_lock.__exit__(None, None, None)
finally: finally:
if acquired:
win32event.ReleaseMutex(mutex)
mutex.Close()
uninitialize_com(initialized) uninitialize_com(initialized)
+6 -2
View File
@@ -100,9 +100,10 @@ class DialogBackend(Protocol):
class AgentDialogBackend: class AgentDialogBackend:
"""Adapt the private-desktop JSONL client to the supervisor backend.""" """Adapt the private-desktop JSONL client to the supervisor backend."""
def __init__(self, client, *, pids=None) -> None: def __init__(self, client, *, pids=None, before_action=None) -> None:
self.client = client self.client = client
self.pids = pids self.pids = pids
self.before_action = before_action
def observe(self, phase: DialogPhase): def observe(self, phase: DialogPhase):
if self.pids is None: if self.pids is None:
@@ -111,6 +112,7 @@ class AgentDialogBackend:
return tuple(w for w in self.client.observe(phase, pids=pids) if w.pid in pids) return tuple(w for w in self.client.observe(phase, pids=pids) if w.pid in pids)
def perform(self, snapshot: WindowSnapshot, action: dict, phase: DialogPhase) -> ActionResult: def perform(self, snapshot: WindowSnapshot, action: dict, phase: DialogPhase) -> ActionResult:
if self.before_action is not None:self.before_action(snapshot,action)
return self.client.perform( return self.client.perform(
hwnd=snapshot.hwnd, hwnd=snapshot.hwnd,
fingerprint=stable_fingerprint(snapshot), fingerprint=stable_fingerprint(snapshot),
@@ -123,7 +125,7 @@ class Win32DialogBackend:
"""Observe and act on dialogs without moving focus, cursor, or desktop.""" """Observe and act on dialogs without moving focus, cursor, or desktop."""
def __init__(self, pids, *, desktop=None, win32gui=None, win32process=None, def __init__(self, pids, *, desktop=None, win32gui=None, win32process=None,
win32con=None) -> None: win32con=None, before_action=None) -> None:
if win32gui is None: if win32gui is None:
import win32gui as win32gui_module import win32gui as win32gui_module
win32gui = win32gui_module win32gui = win32gui_module
@@ -138,6 +140,7 @@ class Win32DialogBackend:
self.win32gui = win32gui self.win32gui = win32gui
self.win32process = win32process self.win32process = win32process
self.win32con = win32con self.win32con = win32con
self.before_action = before_action
def _allowed_pids(self) -> set[int]: def _allowed_pids(self) -> set[int]:
values = self.pids() if callable(self.pids) else self.pids values = self.pids() if callable(self.pids) else self.pids
@@ -256,6 +259,7 @@ class Win32DialogBackend:
return control.control_id return control.control_id
def perform(self, snapshot: DialogSnapshot, action: str) -> tuple[int, ...]: def perform(self, snapshot: DialogSnapshot, action: str) -> tuple[int, ...]:
if self.before_action is not None:self.before_action(snapshot,action)
buttons = self._buttons(snapshot) buttons = self._buttons(snapshot)
positive = ("yes", "ok", "continue", "retry", "restore", "open", "use", "load", positive = ("yes", "ok", "continue", "retry", "restore", "open", "use", "load",
"是", "确定", "继续", "重试", "恢复", "打开", "使用", "加载") "是", "确定", "继续", "重试", "恢复", "打开", "使用", "加载")
+73 -4
View File
@@ -62,6 +62,51 @@ def _tip_target(snapshot):
return target if target is not None and target.class_name == 'Button' else None return target if target is not None and target.class_name == 'Button' else None
def cancelled_prewrite_startup(job, pcb_pid=None):
"""Positive ordinary pre-document cancellation proof; absence of Save is insufficient."""
from .session_record import IDENTITY_KEYS, read_session_record
try:
if (job.get('diagnostic_only') is not False or job.get('interactive_input')
or job.get('native_lm_verify') or job.get('post_repair_consent')
or job.get('operation') != 'verify' or not job.get('operation_id')
or not job.get('desktop', '').startswith('CbbVerify_')):
return None
root=Path(job['root'])
if not Path(job['cancel_signal']).is_file() or (root/'save.log').exists():return None
path=root/'events.jsonl'
if path.stat().st_size>1024*1024:return None
events=[json.loads(line) for line in path.read_text(encoding='utf-8').splitlines()]
if any(str(e.get('stage','')).startswith(('save','integration','validate','failure_close'))
or e.get('stage') in ('startup_write_admitted','startup_supervisor_write_possible','identity_verified')
for e in events):return None
stages=('startup_supervisor_no_write','startup_prewrite_ready','startup_cancelled_prewrite')
selected=[]
for stage in stages:
matches=[(i,e) for i,e in enumerate(events) if e.get('stage')==stage]
if len(matches)!=1:return None
selected.append(matches[0])
if [i for i,_ in selected]!=sorted(i for i,_ in selected):return None
binding={k:job[k] for k in ('operation_id','project','pcb','desktop')}
if any(any(e.get(k)!=v for k,v in binding.items()) for _,e in selected):return None
ready,cancelled=selected[1][1],selected[2][1]
pid=cancelled.get('pcb_pid')
if (not pid or pcb_pid is not None and pid!=pcb_pid
or cancelled.get('identity_verified') is not False or cancelled.get('write_admitted') is not False):return None
if not any(e.get('stage')=='pcb_worker_started' and e.get('pcb_pid')==pid
for e in events[selected[1][0]+1:selected[2][0]]):return None
session=read_session_record(Path(job['session_record_path']),evidence_root=root)
workers=[p for p in session.get('processes',()) if p.get('role')=='worker']
if (session.get('operation_id')!=job['operation_id'] or session.get('desktop')!=job['desktop']
or session.get('library')!=job['library'] or len(workers)!=1
or not set(IDENTITY_KEYS)<=ready.get('worker_identity',{}).keys()
or any(ready.get('worker_identity',{}).get(k)!=workers[0].get(k) for k in IDENTITY_KEYS)):return None
baseline=ready.get('baseline')
if not isinstance(baseline,dict) or not {'started_ns','files'}<=baseline.keys():return None
return baseline
except (OSError,ValueError,KeyError,TypeError):
return None
def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: None, def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: None,
timeout_seconds=None, launcher_process=None): timeout_seconds=None, launcher_process=None):
"""Normally close our empty PCB after a diagnosed database startup failure. """Normally close our empty PCB after a diagnosed database startup failure.
@@ -95,10 +140,12 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
and isinstance(job.get('diagnostic_log_baseline'), dict) and isinstance(job.get('diagnostic_log_baseline'), dict)
and {'started_ns', 'files'} <= job['diagnostic_log_baseline'].keys() and {'started_ns', 'files'} <= job['diagnostic_log_baseline'].keys()
and not (root/'save.log').exists()) and not (root/'save.log').exists())
ordinary_baseline=cancelled_prewrite_startup(job,pcb_pid)
cancelled_prewrite=ordinary_baseline is not None
# Diagnostic close already owns a 30-second cleanup budget. Start it # Diagnostic close already owns a 30-second cleanup budget. Start it
# once here; the empty-to-loaded transition never resets that deadline. # once here; the empty-to-loaded transition never resets that deadline.
if timeout_seconds is None: if timeout_seconds is None:
timeout_seconds = 30 if cancelled_diagnostic else 20 timeout_seconds = 30 if cancelled_diagnostic or cancelled_prewrite else 20
deadline = time.monotonic() + max(0, timeout_seconds) deadline = time.monotonic() + max(0, timeout_seconds)
sent = False sent = False
declined_hwnd = None declined_hwnd = None
@@ -111,6 +158,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
diagnostic_state = {'clicked': set()} diagnostic_state = {'clicked': set()}
def cleanup_post(hwnd, message): def cleanup_post(hwnd, message):
if (time.monotonic() >= deadline or _current_desktop_name() != desktop if (time.monotonic() >= deadline or _current_desktop_name() != desktop
or cancelled_prewrite and cancelled_prewrite_startup(job,pcb_pid)!=ordinary_baseline
or win32event.WaitForSingleObject(close_handle, 0) != win32con.WAIT_TIMEOUT or win32event.WaitForSingleObject(close_handle, 0) != win32con.WAIT_TIMEOUT
or residual_sessions._handle_identity(close_handle) != close_identity or residual_sessions._handle_identity(close_handle) != close_identity
or win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid): or win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid):
@@ -150,19 +198,31 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
or '-reusablecircuit' not in [a.casefold() for a in args] or '-reusablecircuit' not in [a.casefold() for a in args]
or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]): or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
raise ValueError('STARTUP_PROCESS_UNCONFIRMED') raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
if cancelled_diagnostic and time.monotonic() < deadline: if cancelled_diagnostic or cancelled_prewrite:
if time.monotonic() >= deadline:
result['detail']='STARTUP_CLEANUP_TIMEOUT: original cleanup deadline reached'
break
if cancelled_prewrite and cancelled_prewrite_startup(job,pcb_pid)!=ordinary_baseline:
raise ValueError('STARTUP_IDENTITY_UNCONFIRMED: pre-write phase proof changed')
if (cancelled_diagnostic or cancelled_prewrite) and time.monotonic() < deadline:
if close_handle is None: if close_handle is None:
close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid)) close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid))
close_identity = residual_sessions._handle_identity(close_handle) close_identity = residual_sessions._handle_identity(close_handle)
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe': if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
raise ValueError('STARTUP_PROCESS_UNCONFIRMED') raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
from .diagnostic_open import cancelled_startup_step from .diagnostic_open import cancelled_startup_step
def ordinary_identity():
from .diagnostic_open import _load_evidence
return (cancelled_prewrite_startup(job,pcb_pid)==ordinary_baseline
and _load_evidence(job,pcb_pid,ordinary_baseline,require_autosave=False) is not None)
closed, acted = cancelled_startup_step(job, pcb_pid, diagnostic_state, closed, acted = cancelled_startup_step(job, pcb_pid, diagnostic_state,
closed_frame=close_frame, deadline=deadline, post=cleanup_post, emit=emit) closed_frame=close_frame, deadline=deadline, post=cleanup_post, emit=emit,
identity_check=ordinary_identity if cancelled_prewrite else None)
if closed is not None and not sent: if closed is not None and not sent:
sent, close_frame = True, closed sent, close_frame = True, closed
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=closed, emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=closed,
document_identity='native_path_pid_logs', cleanup='cancelled_diagnostic') document_identity='native_path_pid_logs',
cleanup='cancelled_prewrite' if cancelled_prewrite else 'cancelled_diagnostic')
if acted: if acted:
continue continue
if not sent: if not sent:
@@ -187,6 +247,9 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
current = _startup_snapshot(hwnd, pcb_pid) current = _startup_snapshot(hwnd, pcb_pid)
if current != snapshot or _tip_target(current) != target: if current != snapshot or _tip_target(current) != target:
raise ValueError('STARTUP_TIP_CHANGED') raise ValueError('STARTUP_TIP_CHANGED')
if cancelled_diagnostic or cancelled_prewrite:
cleanup_post(target.handle,win32con.BM_CLICK)
else:
win32gui.PostMessage(target.handle, win32con.BM_CLICK, 0, 0) win32gui.PostMessage(target.handle, win32con.BM_CLICK, 0, 0)
dismissed_tips.add(hwnd) dismissed_tips.add(hwnd)
dismissed = True dismissed = True
@@ -207,6 +270,9 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
if _cancel_target(current) != target or current != snapshot: if _cancel_target(current) != target or current != snapshot:
raise ValueError('STARTUP_CANCEL_PROMPT_CHANGED') raise ValueError('STARTUP_CANCEL_PROMPT_CHANGED')
declined_kind, cancel = target declined_kind, cancel = target
if cancelled_diagnostic or cancelled_prewrite:
cleanup_post(cancel.handle,win32con.BM_CLICK)
else:
win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0) win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0)
declined_hwnd = hwnd declined_hwnd = hwnd
emit(stage='startup_open_declined', pcb_pid=pcb_pid, hwnd=hwnd, emit(stage='startup_open_declined', pcb_pid=pcb_pid, hwnd=hwnd,
@@ -251,6 +317,9 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
close_identity = residual_sessions._handle_identity(close_handle) close_identity = residual_sessions._handle_identity(close_handle)
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe': if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
raise ValueError('STARTUP_PROCESS_UNCONFIRMED') raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
if cancelled_diagnostic or cancelled_prewrite:
cleanup_post(main[0],win32con.WM_CLOSE)
else:
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0) win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
close_frame = main[0] close_frame = main[0]
sent = True sent = True
+18
View File
@@ -684,6 +684,11 @@ def execute_job(job, emit):
launcher_process = None launcher_process = None
completed = False completed = False
identity_verified = False identity_verified = False
write_admitted = False
prewrite_eligible = (job.get('diagnostic_only') is False and not job.get('native_lm_verify')
and not job.get('post_repair_consent') and not job.get('interactive_input')
and all(job.get(k) for k in ('operation_id','session_record_path','desktop')))
startup_binding={k:job.get(k) for k in ('operation_id','project','pcb','desktop')}
diagnostic_close_attempted = False diagnostic_close_attempted = False
helper = None helper = None
app = doc = pi = None app = doc = pi = None
@@ -706,6 +711,11 @@ def execute_job(job, emit):
for index, config in enumerate(maintenance_project_files(job['project'], job['pcb'])): for index, config in enumerate(maintenance_project_files(job['project'], job['pcb'])):
ensure_project_central_library(config, job['lmc_file'], ensure_project_central_library(config, job['lmc_file'],
evidence_dir=Path(root)/'diagnostics'/f'project-{index}', emit=emit) evidence_dir=Path(root)/'diagnostics'/f'project-{index}', emit=emit)
if prewrite_eligible:
from .diagnostic_open import snapshot_diagnostic_logs
from .session_record import process_identity
emit(stage='startup_prewrite_ready',baseline=snapshot_diagnostic_logs(job),
worker_identity=process_identity(os.getpid()),**startup_binding)
emit( emit(
stage='verify_mode', stage='verify_mode',
mode=('library_manager_native' if bool(job.get('native_lm_verify', False)) mode=('library_manager_native' if bool(job.get('native_lm_verify', False))
@@ -810,6 +820,10 @@ def execute_job(job, emit):
# the old, working path acquires the token inside the SysWOW64 # the old, working path acquires the token inside the SysWOW64
# cscript save helper below. The PCB UI license dialog has already # cscript save helper below. The PCB UI license dialog has already
# been handled by the private-desktop supervisor. # been handled by the private-desktop supervisor.
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
raise RuntimeError('VERIFY_CANCELLED: 未开始工程集成')
write_admitted = True
if prewrite_eligible:emit(stage='startup_write_admitted',**startup_binding)
refresh_integration( refresh_integration(
pi, pi,
emit=emit, emit=emit,
@@ -915,6 +929,10 @@ def execute_job(job, emit):
elif not completed and worker_pid is not None: elif not completed and worker_pid is not None:
try: try:
from .failed_session import close_failed_startup from .failed_session import close_failed_startup
if (prewrite_eligible and not write_admitted and not identity_verified
and job.get('cancel_signal') and Path(job['cancel_signal']).exists()):
emit(stage='startup_cancelled_prewrite',pcb_pid=worker_pid,
identity_verified=False,write_admitted=False,**startup_binding)
failed_close = close_failed_startup(job, worker_pid, baseline_pids=pcb_before, emit=emit, failed_close = close_failed_startup(job, worker_pid, baseline_pids=pcb_before, emit=emit,
launcher_process=launcher_process) launcher_process=launcher_process)
if failed_close.get('status') == 'CLOSED' and lm_session is not None: if failed_close.get('status') == 'CLOSED' and lm_session is not None:
+24 -4
View File
@@ -68,6 +68,7 @@ class _Call:
done: Event = field(default_factory=Event) done: Event = field(default_factory=Event)
abandoned: bool = False abandoned: bool = False
native_depth: int = 0 native_depth: int = 0
commit_depth: int = 0
readonly_depth: int = 0 readonly_depth: int = 0
supervised_depth: int = 0 supervised_depth: int = 0
worker_sessions: list = field(default_factory=list) worker_sessions: list = field(default_factory=list)
@@ -175,6 +176,25 @@ def hold_native_handoff(process, session_record_path):
raise TaskHandoff(call.context, cancelled=call.handoff_cancelled, result=call.last_result) raise TaskHandoff(call.context, cancelled=call.handoff_cancelled, result=call.last_result)
@contextmanager
def local_commit():
"""Finish an admitted filesystem rename/rollback without native ownership claims."""
call = getattr(_local, 'call', None)
with _tasks_guard:
check_active()
if call is not None:
if call.metadata_only or call.readonly_depth:
raise RuntimeError('Read-only metadata cannot commit filesystem changes')
call.commit_depth += 1
try:
yield
finally:
if call is not None:
with _tasks_guard:
call.commit_depth -= 1
call.phase_started = time.monotonic()
@contextmanager @contextmanager
def native_phase(*, read_only=False, supervised=False): def native_phase(*, read_only=False, supervised=False):
"""Never abandon a transaction between native writes (including Remove/Add).""" """Never abandon a transaction between native writes (including Remove/Add)."""
@@ -266,7 +286,7 @@ class BatchTaskContext:
'CANCELLED' if self.stop.is_set() else 'CANCELLED' if self.stop.is_set() else
'HANDED_OFF' if any(c.abandoned for c in calls) else 'HANDED_OFF' if any(c.abandoned for c in calls) else
'RUNNING' if pending else 'IDLE', pending=pending, 'RUNNING' if pending else 'IDLE', pending=pending,
pending_native=any(c.native_depth for c in calls)) pending_native=any(c.native_depth or c.commit_depth for c in calls))
def shutdown(self): def shutdown(self):
"""Yield UI supervision, never a native worker's write/lease ownership. """Yield UI supervision, never a native worker's write/lease ownership.
@@ -285,7 +305,7 @@ class BatchTaskContext:
call.supervised_depth == call.native_depth and call.supervised_depth == call.native_depth and
all(s.get('worker_protection') in ('duplicated_lease', 'worker_owned_lease', 'inspection_only', 'catalog_readonly') all(s.get('worker_protection') in ('duplicated_lease', 'worker_owned_lease', 'inspection_only', 'catalog_readonly')
for s in call.worker_sessions)) for s in call.worker_sessions))
if not call.native_depth or readonly or external: if not call.commit_depth and (not call.native_depth or readonly or external):
call.shutdown_handoff = call.abandoned = True call.shutdown_handoff = call.abandoned = True
return {**self.snapshot(), 'safe_to_continue': False, return {**self.snapshot(), 'safe_to_continue': False,
'shutdown_handoff': all(c.shutdown_handoff for c in calls), 'shutdown_handoff': all(c.shutdown_handoff for c in calls),
@@ -319,7 +339,7 @@ class BatchTaskContext:
call.done.wait(max(0, deadline-time.monotonic())) call.done.wait(max(0, deadline-time.monotonic()))
with _tasks_guard: with _tasks_guard:
for call in calls: for call in calls:
if not call.done.is_set() and not call.native_depth: if not call.done.is_set() and not call.native_depth and not call.commit_depth:
call.abandoned = True call.abandoned = True
return self.snapshot() return self.snapshot()
@@ -357,7 +377,7 @@ class BatchTaskContext:
call.abandoned = True call.abandoned = True
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result) raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
elapsed = time.monotonic()-call.phase_started elapsed = time.monotonic()-call.phase_started
if not call.native_depth and (call.abandoned or elapsed >= timeout_seconds): if not call.native_depth and not call.commit_depth and (call.abandoned or elapsed >= timeout_seconds):
cancelled = call.is_set() cancelled = call.is_set()
call.abandoned = True call.abandoned = True
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result) raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
+8 -2
View File
@@ -600,7 +600,7 @@ def _cancelled_diagnostic_record(row):
operation = session['operation_id'] operation = session['operation_id']
scope = session.get('resource_scope', {}) scope = session.get('resource_scope', {})
if (record.get('operation_id') != operation or job.get('operation_id') != operation if (record.get('operation_id') != operation or job.get('operation_id') != operation
or job.get('diagnostic_only') is not True or job.get('interactive_input') is not False or job.get('diagnostic_only') not in (True,False) or job.get('interactive_input') is not False
or job.get('operation') != 'verify' or session.get('operation') != 'verify' or job.get('operation') != 'verify' or session.get('operation') != 'verify'
or not all(same(value, row['library']) for value in (job['library'], job['lmc_file'], session['library'])) or not all(same(value, row['library']) for value in (job['library'], job['lmc_file'], session['library']))
or not same(job['root'], root) or not same(job['session_record_path'], path) or not same(job['root'], root) or not same(job['session_record_path'], path)
@@ -644,6 +644,12 @@ def _cancelled_diagnostic_record(row):
continue continue
if any(r.get('operation_id') != operation for r in active_write_records(row['library'])): if any(r.get('operation_id') != operation for r in active_write_records(row['library'])):
continue continue
if job.get('diagnostic_only') is False:
from .failed_session import cancelled_prewrite_startup
from .diagnostic_open import _load_evidence
baseline=cancelled_prewrite_startup(job,row['pid'])
if baseline is None or _load_evidence(job,row['pid'],baseline,require_autosave=False) is None:
continue
matches.append(dict(job=job, record_path=str(path), operation_id=operation, matches.append(dict(job=job, record_path=str(path), operation_id=operation,
closed_frame=closes[0]['hwnd'] if closes else None)) closed_frame=closes[0]['hwnd'] if closes else None))
except (OSError, pywintypes.error, ValueError, KeyError, TypeError): except (OSError, pywintypes.error, ValueError, KeyError, TypeError):
@@ -679,7 +685,7 @@ def _close_registered_startup(row, handle, proof, *, stop=None):
from .diagnostic_open import cancelled_startup_step from .diagnostic_open import cancelled_startup_step
from .operation_queue import check_active from .operation_queue import check_active
job = proof['job']; bound = dict(row, cleanup_desktop=job['desktop']) job = proof['job']; bound = dict(row, cleanup_desktop=job['desktop'])
deadline = time.monotonic()+30 # One diagnostic cleanup intent; ordinary close still uses 3 seconds. deadline = time.monotonic()+30 # One proved cancelled-startup intent; generic close still uses 3 seconds.
def active_owner(): def active_owner():
check_active() check_active()
if stop is not None and stop.is_set(): if stop is not None and stop.is_set():
+6 -8
View File
@@ -4,7 +4,6 @@ Unknown engineering files are primary. Only explicit runtime, history and
generated categories are ignored by semantic comparisons; they are still copied generated categories are ignored by semantic comparisons; they are still copied
and their membership/size/mtime must remain stable throughout the snapshot. and their membership/size/mtime must remain stable throughout the snapshot.
""" """
from concurrent.futures import ThreadPoolExecutor
from contextlib import ExitStack from contextlib import ExitStack
from dataclasses import asdict, dataclass from dataclasses import asdict, dataclass
import hashlib import hashlib
@@ -252,8 +251,8 @@ def build_manifest(root, *, scope=None, exclude=None, progress=None, hash_functi
files = {} files = {}
hashed_bytes = 0 hashed_bytes = 0
_emit(progress, 'hash', 0, 0, total_files=len(selected)) _emit(progress, 'hash', 0, 0, total_files=len(selected))
with ThreadPoolExecutor(max_workers=8) as pool: # Stay on the bounded task thread: executor workers are joined at interpreter exit.
for count, (relative, item) in enumerate(pool.map(hashed, selected), 1): for count, (relative, item) in enumerate(map(hashed, selected), 1):
note_metadata_progress() note_metadata_progress()
files[relative] = item files[relative] = item
hashed_bytes += item['size'] hashed_bytes += item['size']
@@ -332,7 +331,7 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
destination.mkdir(parents=True, exist_ok=False) destination.mkdir(parents=True, exist_ok=False)
files = [path for path, info in entries.items() if stat.S_ISREG(info.st_mode)] files = [path for path, info in entries.items() if stat.S_ISREG(info.st_mode)]
from .library_lock import owned_snapshot from .library_lock import owned_snapshot
# Resolve ownership on the operation thread, before parallel copy workers. # Resolve ownership on the operation thread before copying.
owned = {path: data for path in files owned = {path: data for path in files
if path.name.endswith('.cbb-upload.lock') if path.name.endswith('.cbb-upload.lock')
and (data := owned_snapshot(path)) is not None} and (data := owned_snapshot(path)) is not None}
@@ -390,8 +389,7 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
raise OSError(f'复制期间文件变化:{path}') raise OSError(f'复制期间文件变化:{path}')
return relative.as_posix(), digest, label return relative.as_posix(), digest, label
with ThreadPoolExecutor(max_workers=8) as pool: for count, (relative, digest, label) in enumerate(map(copy_file, files), 1):
for count, (relative, digest, label) in enumerate(pool.map(copy_file, files), 1):
note_metadata_progress() note_metadata_progress()
if label is not None: if label is not None:
size = entries[source/relative].st_size size = entries[source/relative].st_size
@@ -409,8 +407,8 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
raise OSError(f'复制期间主要文件内容变化:{path}') raise OSError(f'复制期间主要文件内容变化:{path}')
if hash_function(destination/relative) != item['sha256']: if hash_function(destination/relative) != item['sha256']:
raise OSError(f'复制内容校验失败:{path}') raise OSError(f'复制内容校验失败:{path}')
with ThreadPoolExecutor(max_workers=8) as pool: for relative in record:
for _ in pool.map(validate_bytes, record): validate_bytes(relative)
note_metadata_progress() note_metadata_progress()
if _metadata_record(source, scan_tree(source)) != expected_metadata: if _metadata_record(source, scan_tree(source)) != expected_metadata:
raise OSError(f'复制期间目录内容变化:{source}') raise OSError(f'复制期间目录内容变化:{source}')
+17 -4
View File
@@ -243,7 +243,8 @@ def _stop_worker(process, *, timeout=5, wait_for_native_write=True):
process.wait(timeout=timeout) process.wait(timeout=timeout)
except Exception: except Exception:
pending = getattr(process, 'native_write_pending', lambda: False)() pending = getattr(process, 'native_write_pending', lambda: False)()
if wait_for_native_write and pending is not False and not getattr(process, '_stop_wait_complete', False): wait_required = wait_for_native_write() if callable(wait_for_native_write) else wait_for_native_write
if wait_required and pending is not False and not getattr(process, '_stop_wait_complete', False):
from .defaults import NATIVE_WRITE_STOP_WAIT_SECONDS from .defaults import NATIVE_WRITE_STOP_WAIT_SECONDS
try: try:
process.wait(timeout=max(0, NATIVE_WRITE_STOP_WAIT_SECONDS - timeout)) process.wait(timeout=max(0, NATIVE_WRITE_STOP_WAIT_SECONDS - timeout))
@@ -985,6 +986,15 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
except Exception as error: except Exception as error:
return finish(VerifyResult('FAIL', stderr=str(error))) return finish(VerifyResult('FAIL', stderr=str(error)))
events = root/'events.jsonl' events = root/'events.jsonl'
prewrite_eligible = not (request.diagnostic_only or request.interactive_input or request.native_lm_verify or consent)
def startup_phase(stage,**facts):
record={k:job[k] for k in ('operation_id','project','pcb','desktop')}
with events.open('a',encoding='utf-8') as stream:
stream.write(json.dumps(dict(stage=stage,**record,**facts))+'\n')
def before_dialog_action(snapshot,action):
name=action.get('action') if isinstance(action,dict) else action
if name not in ('dismiss_tip','accept_license','decline_database_log'):
startup_phase('startup_supervisor_write_possible',action=name,pid=snapshot.pid,hwnd=snapshot.hwnd)
offset = 0 offset = 0
target_pid = None target_pid = None
diagnostic_closing = False diagnostic_closing = False
@@ -1011,6 +1021,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
native.__exit__(None, None, None) native.__exit__(None, None, None)
phase_entered = False phase_entered = False
try: try:
if prewrite_eligible:startup_phase('startup_supervisor_no_write')
timing.begin('worker_setup') timing.begin('worker_setup')
with (root/'worker.log').open('w', encoding='utf-8') as log: with (root/'worker.log').open('w', encoding='utf-8') as log:
check_active() check_active()
@@ -1037,14 +1048,14 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
from .dialog_rules import default_rules_path, load_rules from .dialog_rules import default_rules_path, load_rules
dialog_agent = DialogAgentClient.start(process, root/'dialog-agent', stop=stop) dialog_agent = DialogAgentClient.start(process, root/'dialog-agent', stop=stop)
dialog_supervisor = DialogSupervisor( dialog_supervisor = DialogSupervisor(
AgentDialogBackend(dialog_agent, pids=lambda: { AgentDialogBackend(dialog_agent, before_action=before_dialog_action if prewrite_eligible else None, pids=lambda: {
int(pid) for pid in (target_pid, lm_pid, launcher_pid) if pid}), int(pid) for pid in (target_pid, lm_pid, launcher_pid) if pid}),
rules=load_rules(default_rules_path(), diagnostic_only=request.diagnostic_only), rules=load_rules(default_rules_path(), diagnostic_only=request.diagnostic_only),
) )
else: else:
dialog_supervisor = DialogSupervisor(Win32DialogBackend( dialog_supervisor = DialogSupervisor(Win32DialogBackend(
lambda: ({value for value in (target_pid, lm_pid) if value is not None}), lambda: ({value for value in (target_pid, lm_pid) if value is not None}),
desktop=process.desktop, desktop=process.desktop,before_action=before_dialog_action if prewrite_eligible else None,
)) ))
else: else:
dialog_supervisor = dialog_supervisor_factory( dialog_supervisor = dialog_supervisor_factory(
@@ -1070,7 +1081,9 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'已请求停止,等待当前原生操作返回') '已请求停止,等待当前原生操作返回')
_notify_progress(progress, {'stage': 'save_stop_requested', 'block': request.block_name, _notify_progress(progress, {'stage': 'save_stop_requested', 'block': request.block_name,
'detail': detail}) 'detail': detail})
_stop_worker(process, wait_for_native_write=not request.diagnostic_only) from .failed_session import cancelled_prewrite_startup
_stop_worker(process, wait_for_native_write=False if request.diagnostic_only else
lambda:cancelled_prewrite_startup(job,target_pid) is None)
return finish(VerifyResult('CANCELLED', stderr='已取消当前校验。', return finish(VerifyResult('CANCELLED', stderr='已取消当前校验。',
safe_to_continue=False, error_stage=phase.value)) safe_to_continue=False, error_stage=phase.value))
if events.exists(): if events.exists():
+41
View File
@@ -0,0 +1,41 @@
"""Real application close while one disposable metadata boundary is held."""
from pathlib import Path
import sys,time
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QApplication
from cbb_refresh_verify import scoped_manifest as manifest
from cbb_refresh_verify.operation_queue import check_active
from cbb_refresh_verify.ui.main_window import MainWindow
root=Path(sys.argv[1]);mode=sys.argv[2]
source=root/'source';source.mkdir()
(source/('one.log' if mode=='copy' else 'one.dat')).write_bytes(b'isolated fixture')
def held():
(root/'entered').touch()
while not (root/'release').exists():time.sleep(.02)
def hash_file(path):
held()
return manifest.hash_file(path)
if mode=='copy':
original=manifest.shutil.copy2
def copy_file(*args,**kwargs):
held()
return original(*args,**kwargs)
manifest.shutil.copy2=copy_file
def action():
if mode=='hash':manifest.build_manifest(source,hash_function=hash_file)
else:manifest.copy_verified(source,root/'partial-copy',hash_function=hash_file)
check_active()
(root/'late-dispatch').touch()
app=QApplication([])
window=MainWindow(reader=lambda _:None,data_root=root/'data');window.show()
job=window._new_job('management',library=root/'library.lmc')
window._start(action,lambda _:None,queued=False,job=job)
def close_when_entered():
if (root/'entered').exists():window.close()
else:QTimer.singleShot(20,close_when_entered)
QTimer.singleShot(20,close_when_entered)
code=app.exec()
(root/'main-returning').touch()
raise SystemExit(code)
+198
View File
@@ -0,0 +1,198 @@
import json
from pathlib import Path
import pytest
from cbb_refresh_verify import failed_session,session_record,diagnostic_open
from test_cancelled_loaded_startup import loaded_fixture
def ordinary_proof(job,root,baseline,*,worker=None,pid=12):
worker=worker or dict(pid=11,created_handle='worker-created',image='C:/App/python.exe',owner_sid='current',session_id=1)
job.update(diagnostic_only=False,operation='verify',operation_id=job.get('operation_id','verify-ordinary'),
library=job['lmc_file'],session_record_path=str(root/'session.json'),interactive_input=False)
job.pop('diagnostic_log_baseline',None)
session_record.write_session_record(root/'session.json',dict(operation_id=job['operation_id'],operation='verify',
library=job['library'],desktop=job['desktop'],cancel_signal=job['cancel_signal'],processes=[dict(role='worker',**worker)],
resource_scope=dict(scope_state='DECLARED',library=job['library'],operation_id=job['operation_id'],projects=[job['project']])))
binding={k:job[k] for k in ('operation_id','project','pcb','desktop')}
events=[dict(stage='startup_supervisor_no_write',**binding),
dict(stage='startup_prewrite_ready',worker_identity=worker,baseline=baseline,**binding),
dict(stage='pcb_baseline',pids=[]),dict(stage='pcb_worker_started',pcb_pid=pid),
dict(stage='startup_cancelled_prewrite',pcb_pid=pid,identity_verified=False,write_admitted=False,**binding)]
(root/'events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events))
return events
@pytest.mark.parametrize('prior_close',[False,True])
def test_proved_ordinary_cancel_finishes_tip_to_loaded_without_annotation_or_second_close(tmp_path,monkeypatch,prior_close):
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch,empty_close_first=prior_close)
ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
result=failed_session.close_failed_startup(job,12,timeout_seconds=1)
assert result['status']=='CLOSED' and not records
assert messages==([(100,16),(31,245)] if prior_close else [(201,245),(31,245),(100,16)])
@pytest.mark.parametrize('obstacle',['missing_ready','missing_cancel_phase','supervisor_write','worker_write',
'missing_supervisor','missing_baseline','foreign_worker','foreign_target','save','missing_cancel','interactive','native_lm'])
def test_ordinary_cleanup_requires_positive_bound_no_write_evidence(tmp_path,monkeypatch,obstacle):
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
events=ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
if obstacle=='missing_ready':events=[e for e in events if e['stage']!='startup_prewrite_ready']
if obstacle=='missing_cancel_phase':events=[e for e in events if e['stage']!='startup_cancelled_prewrite']
if obstacle=='missing_supervisor':events=events[1:]
if obstacle=='supervisor_write':events.append(dict(stage='startup_supervisor_write_possible'))
if obstacle=='worker_write':events.append(dict(stage='startup_write_admitted'))
if obstacle=='missing_baseline':events[1].pop('baseline')
if obstacle=='foreign_worker':events[1]['worker_identity']['created_handle']='other'
if obstacle=='foreign_target':events[-1]['pcb']='C:/foreign.pcb'
if obstacle=='save':(tmp_path/'save.log').write_text('SAVE_ENTERED')
if obstacle=='missing_cancel':Path(job['cancel_signal']).unlink()
if obstacle=='interactive':job['interactive_input']=True
if obstacle=='native_lm':job['native_lm_verify']=True
(tmp_path/'events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events))
result=failed_session.close_failed_startup(job,12,timeout_seconds=.3)
assert result['status']=='RETAINED' and records
assert not any(h==31 or m==16 for h,m in messages)
def test_worker_publishes_bound_baseline_before_launch_and_revokes_before_integration(tmp_path,monkeypatch):
from test_verify_worker_stability import exercise_worker
from cbb_refresh_verify import mentor_adapter,integration
job,events,execute=exercise_worker(tmp_path,monkeypatch)
job.update(operation_id='op',operation='verify',library=job['lmc_file'],desktop='CbbVerify_test',
session_record_path=str(Path(job['root'])/'session.json'),diagnostic_only=False)
launch=mentor_adapter.launch_pcb_process
def start(*args):
assert any(e['stage']=='startup_prewrite_ready' and 'baseline' in e for e in events)
return launch(*args)
def write(*args,**kwargs):
assert any(e['stage']=='startup_write_admitted' for e in events)
monkeypatch.setattr(mentor_adapter,'launch_pcb_process',start)
monkeypatch.setattr(integration,'refresh_integration',write)
assert execute()['status']=='PASS'
def test_cancelled_worker_records_positive_prewrite_phase_before_startup_cleanup(tmp_path,monkeypatch):
from test_verify_worker_stability import exercise_worker
from cbb_refresh_verify import pcb_bridge
job,events,execute=exercise_worker(tmp_path,monkeypatch)
job.update(operation_id='op',operation='verify',library=job['lmc_file'],desktop='CbbVerify_test',
session_record_path=str(Path(job['root'])/'session.json'),diagnostic_only=False,
cancel_signal=str(tmp_path/'cancel.signal'))
def cancel(*args,**kwargs):
Path(job['cancel_signal']).touch();raise RuntimeError('VERIFY_CANCELLED')
monkeypatch.setattr(pcb_bridge,'wait_for_target_document',cancel)
observed=[]
def cleanup(*args,**kwargs):observed.extend(events);return {'status':'RETAINED'}
monkeypatch.setattr(failed_session,'close_failed_startup',cleanup)
with pytest.raises(RuntimeError,match='VERIFY_CANCELLED'):execute()
assert any(e['stage']=='startup_cancelled_prewrite' and e['write_admitted'] is False
and e['identity_verified'] is False for e in observed)
@pytest.mark.parametrize('journal_fails',[False,True])
def test_dialog_backend_records_write_revocation_before_action(journal_fails):
from types import SimpleNamespace
from cbb_refresh_verify.dialog_supervisor import Win32DialogBackend,DialogSnapshot,DialogControl
calls=[]
gui=SimpleNamespace(PostMessage=lambda *args:calls.append('native'))
backend=Win32DialogBackend((),win32gui=gui,win32process=object(),win32con=SimpleNamespace(BM_CLICK=245))
def before(snapshot,action):
calls.append('journal')
if journal_fails:raise OSError('cannot record phase')
backend.before_action=before
snapshot=DialogSnapshot(100,12,'Expedition PCB',(DialogControl(101,6,'Button','Yes',True),))
if journal_fails:
with pytest.raises(OSError):backend.perform(snapshot,'confirm_forward_annotation')
assert calls==['journal']
else:
backend.perform(snapshot,'confirm_forward_annotation');assert calls==['journal','native']
def test_positive_ordinary_cancel_phase_yields_after_initial_wait(tmp_path,monkeypatch):
from test_cancelled_session_handoff import worker_fixture
state,stop,run=worker_fixture(tmp_path,monkeypatch)
# The real worker publishes its cancellation fact during the first wait.
from cbb_refresh_verify import desktop_worker
Worker=desktop_worker.DesktopWorker;wait=Worker.wait
def complete_proof(worker,timeout=5):
job=state['job']
baseline={'started_ns':1,'files':{}}
ordinary_proof(job,state['path'].parent,baseline,pid=901,
worker=dict(pid=700,created_handle='worker',image='C:/App/python.exe',owner_sid='current',session_id=1))
return wait(worker,timeout)
monkeypatch.setattr(Worker,'wait',complete_proof)
assert run(False).status=='CANCELLED'
assert state['waits']==[5]
@pytest.mark.parametrize('proof_present',[True,False])
def test_normal_release_of_ordinary_retained_startup_requires_new_complete_prewrite_proof(tmp_path,monkeypatch,proof_present):
from test_registered_startup_release import registered_fixture
from cbb_refresh_verify import residual_sessions
load=diagnostic_open._load_evidence
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
monkeypatch.setattr(diagnostic_open,'_load_evidence',load)
job['diagnostic_only']=False
if proof_present:ordinary_proof(job,tmp_path,state['prelaunch_baseline'])
(tmp_path/'request.json').write_text(json.dumps(job))
result=residual_sessions._request_close(row)
assert result['release_status']==('RELEASED' if proof_present else 'WAITING'),result
assert messages==([(31,245),(100,16)] if proof_present else [])
@pytest.mark.parametrize('obstacle',['unknown','hidden_document','progress','foreign_log_pid','foreign_log_path','revoked'])
def test_ordinary_cleanup_keeps_native_window_write_and_identity_vetoes(tmp_path,monkeypatch,obstacle):
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch,
obstacle=obstacle if obstacle in ('unknown','progress','foreign_log_pid','foreign_log_path') else '')
ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
read=diagnostic_open._windows
def windows(pid):
values=read(pid)
if values and obstacle=='hidden_document':
values[0]['children'].append(dict(hwnd=888,**{'class':'Afx:document'},text='Other',parent=101,visible=False))
if state['declined'] and obstacle=='revoked':
with (tmp_path/'events.jsonl').open('a') as stream:stream.write(json.dumps(dict(stage='startup_write_admitted'))+'\n')
return values
monkeypatch.setattr(diagnostic_open,'_windows',windows)
result=failed_session.close_failed_startup(job,12,timeout_seconds=.5)
assert result['status']=='RETAINED' and records
assert not any(message==16 for _,message in messages)
assert messages==[(201,245)]+([(31,245)] if obstacle in ('progress','revoked') else [])
def test_proved_cancelled_startup_cannot_ack_tip_after_absolute_deadline(tmp_path,monkeypatch):
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
assert failed_session.close_failed_startup(job,12,timeout_seconds=0)['status']=='RETAINED'
assert not messages and records
def test_agent_backend_cannot_dispatch_before_phase_journal():
from types import SimpleNamespace
from cbb_refresh_verify.dialog_supervisor import AgentDialogBackend
from cbb_refresh_verify.dialog_models import WindowSnapshot,DialogPhase
calls=[]
backend=AgentDialogBackend(SimpleNamespace(perform=lambda **kwargs:calls.append('native')),
before_action=lambda *args:calls.append('journal'))
snapshot=WindowSnapshot(100,12,'ExpeditionPCB.exe','pcb','#32770','Expedition PCB',DialogPhase.PCB_STARTING,())
backend.perform(snapshot,{'action':'confirm_forward_annotation'},DialogPhase.PCB_STARTING)
assert calls==['journal','native']
@pytest.mark.parametrize('action',['tip','empty_close'])
def test_startup_deadline_is_rechecked_after_window_read_before_post(tmp_path,monkeypatch,action):
import win32gui
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch,empty_close_first=action=='empty_close')
ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
if action=='tip':
snapshot=failed_session._startup_snapshot
def read(*args):
value=snapshot(*args);state['ticks']=2;return value
monkeypatch.setattr(failed_session,'_startup_snapshot',read)
else:
def children(*args):state['ticks']=2
monkeypatch.setattr(win32gui,'EnumChildWindows',children)
assert failed_session.close_failed_startup(job,12,timeout_seconds=1)['status']=='RETAINED'
assert not messages
+32
View File
@@ -0,0 +1,32 @@
from threading import Event,Thread
from cbb_refresh_verify.operation_queue import QueueCancelled
from test_issue15_ui_integration import window_for
def test_actual_global_stop_button_cancels_running_and_same_app_queued_jobs(qtbot,tmp_path,monkeypatch):
window=window_for(qtbot,tmp_path,monkeypatch)
first=window._new_job('verify',library=tmp_path/'lib.lmc')
second=window._new_job('native_session',library=tmp_path/'lib.lmc')
entered,release,waiting,done=Event(),Event(),Event(),Event();calls=[];errors=[]
def current():
calls.append('first');entered.set();release.wait(3)
def run_first():
try:window.native_queue.run(current,context=first.context,stop=first.context.stop)
except QueueCancelled:pass
def queued():
try:window.native_queue.run(lambda:calls.append('second'),context=second.context,
stop=second.context.stop,waiting=waiting.set)
except QueueCancelled as error:errors.append(error)
finally:done.set()
a=Thread(target=run_first);b=Thread(target=queued)
a.start();assert entered.wait(2);b.start()
try:
qtbot.waitUntil(waiting.is_set);window._update()
assert window.stop_button.isEnabled()
window.stop_button.click()
qtbot.waitUntil(done.is_set)
assert first.context.stop.is_set() and second.context.stop.is_set()
assert calls==['first'] and len(errors)==1
finally:
release.set();a.join(3);b.join(3)
+35
View File
@@ -0,0 +1,35 @@
import os
from pathlib import Path
import subprocess
import sys
import time
import pytest
@pytest.mark.parametrize('mode',['hash','copy','validate'])
def test_actual_app_exits_without_releasing_stalled_manifest_boundary(tmp_path,mode):
script=Path(__file__).parent/'support/manifest_process_exit.py'
env=dict(os.environ,QT_QPA_PLATFORM='offscreen')
child=subprocess.Popen([sys.executable,'-X','utf8',str(script),str(tmp_path),mode],
env=env,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
exited=False
try:
deadline=time.monotonic()+8
while not (tmp_path/'main-returning').exists() and child.poll() is None and time.monotonic()<deadline:
time.sleep(.02)
assert (tmp_path/'entered').exists()
assert (tmp_path/'main-returning').exists()
try:
child.wait(timeout=1)
exited=True
except subprocess.TimeoutExpired:
pass
assert not (tmp_path/'late-dispatch').exists()
finally:
(tmp_path/'release').touch() # Failed-version cleanup is cooperative, never termination.
stdout,stderr=child.communicate(timeout=5)
assert child.returncode==0,(stdout,stderr)
assert not (tmp_path/'late-dispatch').exists()
if mode!='hash':assert (tmp_path/'partial-copy').is_dir()
assert exited,'Interpreter waited for nested metadata executor despite the completed UI close'
+143
View File
@@ -0,0 +1,143 @@
from threading import Event
import pytest
from test_backup_recovery import recovery_files
from cbb_refresh_verify import backup_recovery as recovery
from cbb_refresh_verify.library_lock import LibraryLock,LibraryBusy
from cbb_refresh_verify.operation_queue import BatchTaskContext,TaskHandoff,native_channel
from cbb_refresh_verify.verify_runner import VerifyResult
@pytest.mark.parametrize('boundary',['idle','staging','final_manifest'])
@pytest.mark.parametrize('cancel',[False,True])
def test_real_recovery_handoff_preserves_A_lease_without_blocking_B_or_late_install(recovery_files,monkeypatch,boundary,cancel):
request,original,source=recovery_files
entered,release,done=Event(),Event(),Event();calls=[]
context=BatchTaskContext(str(request.lmc_file),native_policy='external')
def hold():
entered.set()
if cancel:context.cancel()
assert release.wait(5)
def idle(*args):
if boundary=='idle' and not entered.is_set():hold()
copier=recovery._copy_verified
def copy(*args,**kwargs):
value=copier(*args,**kwargs)
if boundary=='staging' and not entered.is_set():hold()
return value
monkeypatch.setattr(recovery,'_copy_verified',copy)
manifest=recovery._manifest
def build(root,**kwargs):
value=manifest(root,**kwargs)
if boundary=='final_manifest' and root==request.lmc_file.parent:hold()
return value
monkeypatch.setattr(recovery,'_manifest',build)
def verify(req,**kwargs):
calls.append(req.lmc_file)
return VerifyResult('PASS',library_flag='GREEN')
def action():
try:return recovery.recover_from_backup(request,source,verifier=verify,idle_check=idle)
finally:done.set()
refusal=None
try:
with pytest.raises(TaskHandoff):context.run(action,timeout_seconds=.3)
assert entered.is_set()
with pytest.raises(LibraryBusy):
with LibraryLock(request.lmc_file):pytest.fail('A lease lost during stalled metadata')
def B():
with native_channel():return 'admitted'
try:
result=BatchTaskContext(str(request.lmc_file.parent.parent/'B/library.lmc'),native_policy='external').run(B)
except RuntimeError as error:refusal=str(error)
finally:
release.set();assert done.wait(5);context.close(timeout_seconds=2)
assert (original.parent/'database/icdb.dat').read_bytes()==b'damaged'
assert not list(original.parent.parent.glob('Work.before-restore-*'))
assert len(calls)==(1 if boundary=='final_manifest' else 0)
assert request.lmc_file not in calls
assert refusal is None,refusal
assert result=='admitted'
def test_cancel_during_work_swap_finishes_atomic_pair_without_target_verify(recovery_files,monkeypatch):
from pathlib import Path
request,original,source=recovery_files
context=BatchTaskContext(str(request.lmc_file),native_policy='external');calls=[]
rename=Path.rename
def swap(path,target):
value=rename(path,target)
if path==original.parent:context.cancel()
return value
monkeypatch.setattr(Path,'rename',swap)
def verify(req,**kwargs):
calls.append(req.lmc_file)
return VerifyResult('PASS',library_flag='GREEN')
result=context.run(lambda:recovery.recover_from_backup(request,source,verifier=verify,idle_check=lambda *a:None))
assert result.status!='PASS'
assert (original.parent/'database/icdb.dat').read_bytes()==b'healthy'
retained=list(original.parent.parent.glob('Work.before-restore-*'))
assert len(retained)==1 and (retained[0]/'database/icdb.dat').read_bytes()==b'damaged'
assert len(calls)==1 and request.lmc_file not in calls
def test_shutdown_cannot_abandon_local_work_swap_or_hold_host_channel(recovery_files,monkeypatch):
from pathlib import Path
from threading import Thread
request,original,source=recovery_files
context=BatchTaskContext(str(request.lmc_file),native_policy='external')
entered,release,done=Event(),Event(),Event();calls=[];errors=[]
rename=Path.rename
def swap(path,target):
value=rename(path,target)
if path==original.parent:
entered.set();assert release.wait(5)
return value
monkeypatch.setattr(Path,'rename',swap)
def verify(req,**kwargs):
calls.append(req.lmc_file);return VerifyResult('PASS',library_flag='GREEN')
def run():
try:context.run(lambda:recovery.recover_from_backup(request,source,verifier=verify,idle_check=lambda *a:None))
except Exception as error:errors.append(error)
finally:done.set()
thread=Thread(target=run);thread.start()
try:
assert entered.wait(3)
state=context.shutdown()
assert state['shutdown_handoff'] is False
assert not done.wait(.1)
def B():
with native_channel():return True
assert BatchTaskContext(str(request.lmc_file.parent.parent/'B/library.lmc'),native_policy='external').run(B)
finally:
release.set();thread.join(5)
assert done.is_set() and len(calls)==1
assert (original.parent/'database/icdb.dat').read_bytes()==b'healthy'
def test_cancelled_failed_install_rolls_back_before_releasing_commit(recovery_files,monkeypatch):
from pathlib import Path
request,original,source=recovery_files;calls=[]
context=BatchTaskContext(str(request.lmc_file),native_policy='external');rename=Path.rename
def swap(path,target):
if path.name.startswith('Work.restore-'):
context.cancel();raise OSError('install rename refused')
return rename(path,target)
monkeypatch.setattr(Path,'rename',swap)
def verify(req,**kwargs):
calls.append(req.lmc_file);return VerifyResult('PASS',library_flag='GREEN')
result=context.run(lambda:recovery.recover_from_backup(request,source,verifier=verify,idle_check=lambda *a:None))
assert result.status!='PASS' and 'install rename refused' in result.stderr
assert (original.parent/'database/icdb.dat').read_bytes()==b'damaged'
assert not list(original.parent.parent.glob('Work.before-restore-*'))
assert len(calls)==1
def test_metadata_only_context_cannot_enter_local_commit(tmp_path):
from cbb_refresh_verify.operation_queue import local_commit
mutations=[]
def commit():
with local_commit():mutations.append('rename')
with pytest.raises(RuntimeError,match='Read-only metadata'):
BatchTaskContext(str(tmp_path/'lib.lmc')).run(commit,metadata_only=True)
assert not mutations
+1
View File
@@ -17,6 +17,7 @@ def registered_fixture(tmp_path,monkeypatch,*,closed=False,obstacle=''):
state['observer_requests'].append((path,list(messages),kw))) state['observer_requests'].append((path,list(messages),kw)))
job.update(operation_id='verify-old',operation='verify',library=job['lmc_file'],block='IP101GR', job.update(operation_id='verify-old',operation='verify',library=job['lmc_file'],block='IP101GR',
session_record_path=str(tmp_path/'session.json'),interactive_input=False) session_record_path=str(tmp_path/'session.json'),interactive_input=False)
state['prelaunch_baseline']=job['diagnostic_log_baseline']
job.pop('diagnostic_log_baseline') # Old builds never persisted this; do not invent it. job.pop('diagnostic_log_baseline') # Old builds never persisted this; do not invent it.
identity=dict(pid=12,created_handle='native-created',image=records[0][1],owner_sid='current',session_id=1) identity=dict(pid=12,created_handle='native-created',image=records[0][1],owner_sid='current',session_id=1)
worker=dict(pid=11,created_handle='worker-created',image='C:/App/CbbRefreshVerify.exe',owner_sid='current',session_id=1) worker=dict(pid=11,created_handle='worker-created',image='C:/App/CbbRefreshVerify.exe',owner_sid='current',session_id=1)