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
+659 -60

No files matched your search

+39 -18
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):
"""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 .verify_runner import run_verify, read_library_flag_if_available
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='恢复记录目录不能位于备份工程内。')
if validation_dir.is_relative_to(library_root) or validation_dir.is_relative_to(source.parent):
return VerifyResult('BLOCKED', stderr='本机验证目录不能位于目标库或备份工程内。')
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
library_lock = None
release_confirmed = True
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),
'library': str(library), 'block': request.block_name, 'installed': False,
'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
initialized = initialize_com()
try:
acquired = win32event.WaitForSingleObject(mutex, 0) in (
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
return VerifyResult('BLOCKED', stderr='已有 CBB 任务运行,请等待结束。', safe_to_continue=False)
check()
from .library_lock import LibraryLock
library_lock = LibraryLock(library, safe_to_release=lambda: release_confirmed)
library_lock.__enter__()
if source.is_relative_to(library_root):
raise ValueError('请选择目标中心库之外的独立备份工程。')
project, pcb = preflight(replace(request, lmc_file=library))
completed()
source_pcb = _source_check(source, request.block_name, project)
completed()
root.mkdir(parents=True, exist_ok=False)
idle_check(library, project, pcb)
completed()
idle_check(library, source, source_pcb)
completed()
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))
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()
required = (library_size + source_size * 2) if same_drive else 0
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)
original_manifest = _copy_verified(library_root, validation_dir, scope=library_scope,
progress=copy_progress('prepare_source', '正在准备验证库:'))
completed()
(root/'library-baseline-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8')
staged_library = validation_dir/library.name
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()):
raise ValueError('验证副本工程路径越界。')
shutil.rmtree(resolved_work)
completed()
source_manifest = _copy_verified(source.parent, staged_work,
progress=copy_progress('prepare_source', '正在准备备份验证工程:'))
completed()
(root/'source-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8')
staged_project = staged_work/source.name
staged_pcb = staged_work/source_pcb.relative_to(source.parent)
@@ -263,41 +273,55 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
auto_repair=False, libspec='', dms_login_config='', mapped_drive='', mapped_remote_root='',
native_lm_verify=False, interactive_input=False)
preflight(validation)
completed()
emit('validate_source', '正在副本中打开备份工程并执行原生校验…')
check()
release_confirmed = False
choice_options = {'version_prompt': version_prompt} if version_prompt is not None else {}
if stop is not None:choice_options['stop']=stop
source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available, **choice_options)
release_confirmed = source_result.safe_to_continue
record['source_validation'] = asdict(source_result)
completed()
if (source_result.status != 'PASS' or source_result.library_flag != 'GREEN'
or not source_result.safe_to_continue):
return save(replace(source_result, status='FAIL', stderr=
'备份校验未通过,目标未更改。\n' + (source_result.stderr or source_result.library_flag_detail)))
idle_check(library, project, pcb)
completed()
idle_check(staged_library, staged_project, staged_pcb)
completed()
token = root.name.removeprefix('backup-restore-')
work = project.parent.resolve()
incoming = work.with_name('Work.restore-' + token)
retained = work.with_name('Work.before-restore-' + token)
_copy_verified(staged_work, incoming,
progress=copy_progress('prepare_source', '正在准备恢复工程:'))
completed()
_align_library(incoming/source.name, incoming/source_pcb.relative_to(source.parent), library)
completed()
idle_check(library, source, source_pcb)
completed()
if _manifest(source.parent) != source_manifest:
raise ValueError('备份来源在验证期间发生变化,目标未更改。')
completed()
if _manifest(library_root, scope=library_scope, exclude=incoming.resolve()) != original_manifest:
raise ValueError('目标中心库在验证期间发生变化,停止恢复。')
completed()
emit('install', '备份已通过验证,正在保留原工程并恢复…')
work.rename(retained)
try:
incoming.rename(work)
except Exception:
retained.rename(work)
raise
installed = True
record['retained_work'] = str(retained)
check()
with local_commit():
work.rename(retained)
try:
incoming.rename(work)
except Exception:
retained.rename(work)
raise
installed = True
record['retained_work'] = str(retained)
completed()
emit('verify_target', '正在重新打开恢复后的目标工程并校验…')
check()
release_confirmed = False
final = verifier(replace(request, lmc_file=library, evidence_dir=root/'target-verify',
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:
library_lock.__exit__(None, None, None)
finally:
if acquired:
win32event.ReleaseMutex(mutex)
mutex.Close()
uninitialize_com(initialized)
+6 -2
View File
@@ -100,9 +100,10 @@ class DialogBackend(Protocol):
class AgentDialogBackend:
"""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.pids = pids
self.before_action = before_action
def observe(self, phase: DialogPhase):
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)
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(
hwnd=snapshot.hwnd,
fingerprint=stable_fingerprint(snapshot),
@@ -123,7 +125,7 @@ class Win32DialogBackend:
"""Observe and act on dialogs without moving focus, cursor, or desktop."""
def __init__(self, pids, *, desktop=None, win32gui=None, win32process=None,
win32con=None) -> None:
win32con=None, before_action=None) -> None:
if win32gui is None:
import win32gui as win32gui_module
win32gui = win32gui_module
@@ -138,6 +140,7 @@ class Win32DialogBackend:
self.win32gui = win32gui
self.win32process = win32process
self.win32con = win32con
self.before_action = before_action
def _allowed_pids(self) -> set[int]:
values = self.pids() if callable(self.pids) else self.pids
@@ -256,6 +259,7 @@ class Win32DialogBackend:
return control.control_id
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)
positive = ("yes", "ok", "continue", "retry", "restore", "open", "use", "load",
"是", "确定", "继续", "重试", "恢复", "打开", "使用", "加载")
+76 -7
View File
@@ -62,6 +62,51 @@ def _tip_target(snapshot):
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,
timeout_seconds=None, launcher_process=None):
"""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 {'started_ns', 'files'} <= job['diagnostic_log_baseline'].keys()
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
# once here; the empty-to-loaded transition never resets that deadline.
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)
sent = False
declined_hwnd = None
@@ -111,6 +158,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
diagnostic_state = {'clicked': set()}
def cleanup_post(hwnd, message):
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 residual_sessions._handle_identity(close_handle) != close_identity
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 expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
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:
close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid))
close_identity = residual_sessions._handle_identity(close_handle)
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
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_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:
sent, close_frame = True, 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:
continue
if not sent:
@@ -187,7 +247,10 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
current = _startup_snapshot(hwnd, pcb_pid)
if current != snapshot or _tip_target(current) != target:
raise ValueError('STARTUP_TIP_CHANGED')
win32gui.PostMessage(target.handle, win32con.BM_CLICK, 0, 0)
if cancelled_diagnostic or cancelled_prewrite:
cleanup_post(target.handle,win32con.BM_CLICK)
else:
win32gui.PostMessage(target.handle, win32con.BM_CLICK, 0, 0)
dismissed_tips.add(hwnd)
dismissed = True
emit(stage='startup_tip_dismissed', pcb_pid=pcb_pid, hwnd=hwnd)
@@ -207,7 +270,10 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
if _cancel_target(current) != target or current != snapshot:
raise ValueError('STARTUP_CANCEL_PROMPT_CHANGED')
declined_kind, cancel = target
win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0)
if cancelled_diagnostic or cancelled_prewrite:
cleanup_post(cancel.handle,win32con.BM_CLICK)
else:
win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0)
declined_hwnd = hwnd
emit(stage='startup_open_declined', pcb_pid=pcb_pid, hwnd=hwnd,
control_id=cancel.control_id, prompt=declined_kind)
@@ -251,7 +317,10 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
close_identity = residual_sessions._handle_identity(close_handle)
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
if cancelled_diagnostic or cancelled_prewrite:
cleanup_post(main[0],win32con.WM_CLOSE)
else:
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
close_frame = main[0]
sent = True
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=main[0])
+18
View File
@@ -684,6 +684,11 @@ def execute_job(job, emit):
launcher_process = None
completed = 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
helper = 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'])):
ensure_project_central_library(config, job['lmc_file'],
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(
stage='verify_mode',
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
# cscript save helper below. The PCB UI license dialog has already
# 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(
pi,
emit=emit,
@@ -915,6 +929,10 @@ def execute_job(job, emit):
elif not completed and worker_pid is not None:
try:
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,
launcher_process=launcher_process)
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)
abandoned: bool = False
native_depth: int = 0
commit_depth: int = 0
readonly_depth: int = 0
supervised_depth: int = 0
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)
@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
def native_phase(*, read_only=False, supervised=False):
"""Never abandon a transaction between native writes (including Remove/Add)."""
@@ -266,7 +286,7 @@ class BatchTaskContext:
'CANCELLED' if self.stop.is_set() else
'HANDED_OFF' if any(c.abandoned for c in calls) else
'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):
"""Yield UI supervision, never a native worker's write/lease ownership.
@@ -285,7 +305,7 @@ class BatchTaskContext:
call.supervised_depth == call.native_depth and
all(s.get('worker_protection') in ('duplicated_lease', 'worker_owned_lease', 'inspection_only', 'catalog_readonly')
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
return {**self.snapshot(), 'safe_to_continue': False,
'shutdown_handoff': all(c.shutdown_handoff for c in calls),
@@ -319,7 +339,7 @@ class BatchTaskContext:
call.done.wait(max(0, deadline-time.monotonic()))
with _tasks_guard:
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
return self.snapshot()
@@ -357,7 +377,7 @@ class BatchTaskContext:
call.abandoned = True
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
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()
call.abandoned = True
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']
scope = session.get('resource_scope', {})
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 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)
@@ -644,6 +644,12 @@ def _cancelled_diagnostic_record(row):
continue
if any(r.get('operation_id') != operation for r in active_write_records(row['library'])):
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,
closed_frame=closes[0]['hwnd'] if closes else None))
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 .operation_queue import check_active
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():
check_active()
if stop is not None and stop.is_set():
+21 -23
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
and their membership/size/mtime must remain stable throughout the snapshot.
"""
from concurrent.futures import ThreadPoolExecutor
from contextlib import ExitStack
from dataclasses import asdict, dataclass
import hashlib
@@ -252,13 +251,13 @@ def build_manifest(root, *, scope=None, exclude=None, progress=None, hash_functi
files = {}
hashed_bytes = 0
_emit(progress, 'hash', 0, 0, total_files=len(selected))
with ThreadPoolExecutor(max_workers=8) as pool:
for count, (relative, item) in enumerate(pool.map(hashed, selected), 1):
note_metadata_progress()
files[relative] = item
hashed_bytes += item['size']
if count % 256 == 0 or count == len(selected):
_emit(progress, 'hash', count, hashed_bytes, total_files=len(selected))
# Stay on the bounded task thread: executor workers are joined at interpreter exit.
for count, (relative, item) in enumerate(map(hashed, selected), 1):
note_metadata_progress()
files[relative] = item
hashed_bytes += item['size']
if count % 256 == 0 or count == len(selected):
_emit(progress, 'hash', count, hashed_bytes, total_files=len(selected))
# Check primary membership and metadata again after every hash completed.
# Runtime files can change/add/disappear without a semantic conflict.
after = scan_tree(root, scope=scope, exclude=exclude)
@@ -332,7 +331,7 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
destination.mkdir(parents=True, exist_ok=False)
files = [path for path, info in entries.items() if stat.S_ISREG(info.st_mode)]
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
if path.name.endswith('.cbb-upload.lock')
and (data := owned_snapshot(path)) is not None}
@@ -390,17 +389,16 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
raise OSError(f'复制期间文件变化:{path}')
return relative.as_posix(), digest, label
with ThreadPoolExecutor(max_workers=8) as pool:
for count, (relative, digest, label) in enumerate(pool.map(copy_file, files), 1):
note_metadata_progress()
if label is not None:
size = entries[source/relative].st_size
record[relative] = {'size': size, 'sha256': digest, 'scope': label}
hashed_count += 1
hashed_bytes += size
if count % 256 == 0 or count == len(files):
_emit(progress, 'copy', hashed_count, hashed_bytes,
copied_files=count, total_files=len(files))
for count, (relative, digest, label) in enumerate(map(copy_file, files), 1):
note_metadata_progress()
if label is not None:
size = entries[source/relative].st_size
record[relative] = {'size': size, 'sha256': digest, 'scope': label}
hashed_count += 1
hashed_bytes += size
if count % 256 == 0 or count == len(files):
_emit(progress, 'copy', hashed_count, hashed_bytes,
copied_files=count, total_files=len(files))
def validate_bytes(relative):
item = record[relative]
@@ -409,9 +407,9 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
raise OSError(f'复制期间主要文件内容变化:{path}')
if hash_function(destination/relative) != item['sha256']:
raise OSError(f'复制内容校验失败:{path}')
with ThreadPoolExecutor(max_workers=8) as pool:
for _ in pool.map(validate_bytes, record):
note_metadata_progress()
for relative in record:
validate_bytes(relative)
note_metadata_progress()
if _metadata_record(source, scan_tree(source)) != expected_metadata:
raise OSError(f'复制期间目录内容变化:{source}')
if _metadata_record(destination, scan_tree(destination)) != expected_metadata:
+17 -4
View File
@@ -243,7 +243,8 @@ def _stop_worker(process, *, timeout=5, wait_for_native_write=True):
process.wait(timeout=timeout)
except Exception:
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
try:
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:
return finish(VerifyResult('FAIL', stderr=str(error)))
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
target_pid = None
diagnostic_closing = False
@@ -1011,6 +1021,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
native.__exit__(None, None, None)
phase_entered = False
try:
if prewrite_eligible:startup_phase('startup_supervisor_no_write')
timing.begin('worker_setup')
with (root/'worker.log').open('w', encoding='utf-8') as log:
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
dialog_agent = DialogAgentClient.start(process, root/'dialog-agent', stop=stop)
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}),
rules=load_rules(default_rules_path(), diagnostic_only=request.diagnostic_only),
)
else:
dialog_supervisor = DialogSupervisor(Win32DialogBackend(
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:
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,
'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='已取消当前校验。',
safe_to_continue=False, error_stage=phase.value))
if events.exists():