fix: preserve safe stop and explicit forced interruption lifecycle
This commit is contained in:
1 parent
b939101565
commit
9c03cd5900
29 files changed
+1829
-86
No files matched your search
@@ -66,10 +66,11 @@ class _DesktopLease:
|
||||
for process in reversed(self.processes):
|
||||
try:
|
||||
self.owner._release_process(process, desktop=self.desktop, generation=self.generation)
|
||||
records.append(getattr(process, 'cleanup_record', {}))
|
||||
except Exception as error:
|
||||
errors.append(str(error))
|
||||
remaining.append(process)
|
||||
finally:
|
||||
records.append(getattr(process, 'cleanup_record', {}))
|
||||
self.processes = list(reversed(remaining))
|
||||
self.cleanup_record = {'scope': 'operation', 'processes': records,
|
||||
'workers_closed': not errors, 'desktop_retained_by_batch': True, 'errors': errors}
|
||||
@@ -99,6 +100,7 @@ class BatchCadRuntime:
|
||||
self._retry_counts = {}
|
||||
self._project_attempts = {}
|
||||
self._logging = None
|
||||
self._active_evidence = None
|
||||
|
||||
def bind_logs(self, context, task_ids):
|
||||
"""Keep every participating task's final release outcome visible."""
|
||||
@@ -116,6 +118,14 @@ class BatchCadRuntime:
|
||||
return self
|
||||
|
||||
def __exit__(self, error_type, error, traceback):
|
||||
if error is not None and self._active_evidence is not None:
|
||||
attempts = [item for values in self._project_attempts.values() for item in values]
|
||||
try:
|
||||
self._retain_uncertain(self._active_evidence, None, attempts, error)
|
||||
except WorkerMonitorError:
|
||||
if not getattr(getattr(self.stop_event, 'force_event', None), 'is_set', lambda: False)():
|
||||
raise
|
||||
# Explicit force has durable protection; cleanup is now allowed.
|
||||
try:
|
||||
self.close()
|
||||
except Exception as cleanup:
|
||||
@@ -190,7 +200,8 @@ class BatchCadRuntime:
|
||||
started = time.monotonic()
|
||||
self._save(cad_start_requested=True)
|
||||
cad = factory(self.path.parent / f'generation-{self.generation + (self.desktop is None)}',
|
||||
abort_event=abort_event, desktop=lease)
|
||||
abort_event=abort_event, desktop=lease,
|
||||
**({'stop_control': self.stop_event} if hasattr(self.stop_event, 'force_event') else {}))
|
||||
self.cad = cad # Retain cleanup ownership even if startup fails.
|
||||
try:
|
||||
cad.__enter__()
|
||||
@@ -247,6 +258,7 @@ class BatchCadRuntime:
|
||||
from .isolated_cad import PrivateCadStartupError, is_identity_conflict
|
||||
from .worker_monitor import run_monitored_process
|
||||
root = canonical_path(command[3])
|
||||
self._active_evidence = root
|
||||
while True:
|
||||
check_cancelled(abort_event or self.stop_event)
|
||||
attempt_id = uuid4().hex
|
||||
@@ -272,7 +284,11 @@ class BatchCadRuntime:
|
||||
def start_worker(launch, **options):
|
||||
return cad.start_worker(launch, extra_environment=environment, **options)
|
||||
result = run_monitored_process(command, timeout, abort_event=abort_event,
|
||||
cooperative_abort=cooperative_abort, process_factory=start_worker)
|
||||
cooperative_abort=cooperative_abort, process_factory=start_worker,
|
||||
**({'force_control': self.stop_event} if hasattr(self.stop_event, 'force_event') else {}))
|
||||
if result.returncode:
|
||||
self._retain_uncertain(root, project, expected,
|
||||
WorkerMonitorError(result.stderr or 'worker failed after possible mutation'))
|
||||
self._checkpoint(root, project, attempt_id)
|
||||
if result.returncode not in (2, 3):
|
||||
return result
|
||||
@@ -294,6 +310,7 @@ class BatchCadRuntime:
|
||||
and not (abort_event is not None and abort_event.is_set())
|
||||
and not (self.stop_event is not None and self.stop_event.is_set()))
|
||||
if not safe:
|
||||
self._retain_uncertain(root, project, expected, failure)
|
||||
raise failure
|
||||
key = str(project).casefold()
|
||||
self._retry_counts[key] = 1
|
||||
@@ -302,6 +319,13 @@ class BatchCadRuntime:
|
||||
self.close(rebuilding=True) # Prove disappearance before creating another.
|
||||
self.desktop = self.cad = None
|
||||
|
||||
def _retain_uncertain(self, root, project, expected, error):
|
||||
from .batch_attempt import can_retry_attempt
|
||||
from .stop_control import wait_for_resolution
|
||||
attempts = self._project_attempts.get(str(project).casefold(), expected)
|
||||
if attempts and not all(can_retry_attempt(path, record) for path, record in attempts):
|
||||
wait_for_resolution(self.stop_event, root, error)
|
||||
|
||||
def recover_native_failure(self, project, evidence, reason):
|
||||
"""One read-only recovery, based on durable source and worker proof."""
|
||||
from .batch_attempt import can_retry_attempt
|
||||
@@ -387,7 +411,8 @@ class BatchCadRuntime:
|
||||
cad_record = cad_record if isinstance(cad_record, dict) else {}
|
||||
self.record['cad_shutdown'] = {key: cad_record[key] for key in (
|
||||
'state', 'clean', 'cad_exit_code', 'quit_helper_exit_code', 'cleanup_errors',
|
||||
'shutdown_seconds') if key in cad_record}
|
||||
'shutdown_seconds', 'orderly_shutdown', 'diagnostic_errors', 'forced_termination',
|
||||
'forced_root_termination', 'forced_descendant_pids', 'termination_reason') if key in cad_record}
|
||||
if self.desktop is not None:
|
||||
try:
|
||||
self.desktop.close()
|
||||
|
||||
@@ -24,27 +24,31 @@ _WRITE_OPERATIONS = frozenset({'execute_task_queue', 'execute_quick_run_queue',
|
||||
|
||||
|
||||
def _mark_interrupted(root, journal, reason):
|
||||
from .batch_resources import write_record
|
||||
from .batch_resources import write_record, _valid_record
|
||||
from .stop_control import protect_interruption
|
||||
journal.update(state='blocked', outcome='interrupted', error=str(reason))
|
||||
if journal['operation'] in _WRITE_OPERATIONS:
|
||||
# A missing final result is not proof of no mutation. Publish the same
|
||||
# protection the existing recovery UI understands, without overwriting
|
||||
# any earlier, more specific marker.
|
||||
journal['business_uncertain'] = True
|
||||
for task_id in journal['task_ids']:
|
||||
task_ids = journal['task_ids']
|
||||
resource_path = Path(root) / 'batch-resources' / journal['batch_id'] / 'session.json'
|
||||
try:
|
||||
resource = json.loads(internal_path(resource_path).read_text(encoding='utf-8'))
|
||||
if (not journal.get('protect_all_targets') and _valid_record(resource, resource_path)
|
||||
and resource.get('active_task') in task_ids):
|
||||
task_ids = [resource['active_task']]
|
||||
except (OSError, ValueError, TypeError):
|
||||
pass # Without valid active ownership, protect every possible target.
|
||||
journal['protected_task_ids'] = list(task_ids)
|
||||
for task_id in task_ids:
|
||||
allowed = {canonical_path(root), canonical_path(Path(root) / 'tasks' / task_id)}
|
||||
actual = journal.get('uncertainty_roots', {}).get(task_id)
|
||||
roots = {canonical_path(actual)} if actual and canonical_path(actual) in allowed else allowed
|
||||
for evidence in roots:
|
||||
marker = internal_path(evidence / 'quick-run/uncertain.flag')
|
||||
marker.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
with marker.open('x', encoding='utf-8') as stream:
|
||||
stream.write('reason=supervisor_interrupted; batch=' + journal['batch_id'] + '; manual reconciliation required\n')
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
except FileExistsError:
|
||||
pass
|
||||
protect_interruption(evidence / 'quick-run',
|
||||
'reason=supervisor_interrupted; batch=' + journal['batch_id'] + '; manual reconciliation required\n')
|
||||
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
|
||||
|
||||
|
||||
@@ -53,6 +57,61 @@ def _worker_context(root):
|
||||
_WORKER_ROOT = canonical_path(root)
|
||||
|
||||
|
||||
def _force_owned_supervisor(root, journal, process):
|
||||
"""Persist uncertainty before terminating the exact process/Job we own."""
|
||||
journal['stop_mode'] = 'forced'
|
||||
journal['force_requested_at'] = time.time()
|
||||
# The running worker can cross a task boundary while evidence is written.
|
||||
# Protect all possible targets before force; keep their saved results intact.
|
||||
journal['protect_all_targets'] = True
|
||||
_mark_interrupted(root, journal, '用户明确强制结束;写入与保存结果须核验,禁止自动重放。')
|
||||
try:
|
||||
process.terminate()
|
||||
except Exception as error:
|
||||
if not getattr(process, 'cleanup_record', {}).get('forced_termination'):
|
||||
raise
|
||||
journal['force_cleanup_error'] = str(error)
|
||||
try:
|
||||
from .batch_resources import write_record
|
||||
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
|
||||
except OSError:
|
||||
pass # The forced intent and uncertainty were already durably saved.
|
||||
|
||||
|
||||
def _retain_supervisor_after_control_error(root, journal, process, control, error):
|
||||
"""Do not turn a GUI/transport exception into an unconfirmed Job kill."""
|
||||
from .batch_resources import write_record
|
||||
control.set()
|
||||
control.control_error = '控制通信异常,已请求安全停止并保留应用;可导出诊断或明确强制结束:' + str(error)
|
||||
journal['protect_all_targets'] = True
|
||||
try:
|
||||
_mark_interrupted(root, journal, error)
|
||||
except Exception as failure:
|
||||
control.control_error += ';中断证据尚未落盘:' + str(failure)
|
||||
try:
|
||||
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'cancel.json',
|
||||
{'version': VERSION, 'batch_id': journal['batch_id'], 'attempt_id': journal['attempt_id']})
|
||||
except OSError:
|
||||
pass # Keep ownership; failure to request stop is not permission to kill.
|
||||
while True:
|
||||
if control.force_event.is_set():
|
||||
try:
|
||||
_force_owned_supervisor(root, journal, process)
|
||||
except Exception as failure:
|
||||
control.force_event.clear()
|
||||
control.control_error = '强制结束未确认,应用仍保留:' + str(failure)
|
||||
else:
|
||||
return True
|
||||
try:
|
||||
process.wait(timeout=.2)
|
||||
return False
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
except Exception as failure:
|
||||
control.control_error = '无法确认应用退出,保留所有权等待处理:' + str(failure)
|
||||
threading.Event().wait(.2)
|
||||
|
||||
|
||||
def _file_lock(handle, acquire):
|
||||
from .task_queue import _os_lock
|
||||
_os_lock(handle, acquire)
|
||||
@@ -170,6 +229,19 @@ def _finish_response(root, journal, response, context):
|
||||
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
|
||||
if related:
|
||||
raise resource_pending_error(journal['operation'], result, error, primary)
|
||||
resource_path = internal_path(Path(root) / 'batch-resources' / journal['batch_id'] / 'session.json')
|
||||
try:
|
||||
resource = json.loads(resource_path.read_text(encoding='utf-8'))
|
||||
except FileNotFoundError:
|
||||
resource = {}
|
||||
shutdown = resource.get('cad_shutdown') or {}
|
||||
if (shutdown.get('orderly_shutdown') is False or shutdown.get('forced_termination')
|
||||
or shutdown.get('diagnostic_errors')
|
||||
or any(item.get('stage') != 'desktop_release' for item in shutdown.get('cleanup_errors', ()))):
|
||||
failure = TaskCenterError('application_shutdown_failed',
|
||||
'已核验业务结果保留,但应用未正常收尾;请查看退出诊断,不能将资源消失视为正常退出。')
|
||||
failure.completed_result, failure.cleanup_error = result, error
|
||||
raise failure
|
||||
if response.get('business_succeeded'):
|
||||
if response.get('error'):
|
||||
context.logger.info('supervisor_resource_recovery_passed batch_id=%s business_replayed=false', journal['batch_id'])
|
||||
@@ -186,6 +258,7 @@ def _finish_response(root, journal, response, context):
|
||||
def run_supervised(service, operation, arguments, *, stop_event=None, on_progress=None, on_phase=None):
|
||||
from .batch_resources import write_record, process_identity
|
||||
from .isolated_desktop import _Win32Api
|
||||
from .stop_control import StopControl
|
||||
root = canonical_path(service._logging.root)
|
||||
if stop_event is not None and stop_event.is_set():
|
||||
raise TaskCenterError('operation_cancelled', '本批操作已取消,未启动监督进程。')
|
||||
@@ -216,13 +289,15 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
journal['parent_process'] = process_identity(parent)
|
||||
write_record(request, {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id,
|
||||
'root': str(root), 'database': str(canonical_path(service._store.path)),
|
||||
'operation': operation, 'arguments': encode(arguments), 'task_ids': journal['task_ids']})
|
||||
'operation': operation, 'arguments': encode(arguments), 'task_ids': journal['task_ids'],
|
||||
'interactive_stop': isinstance(stop_event, StopControl)})
|
||||
journal['request_sha256'] = hashlib.sha256(internal_path(request).read_bytes()).hexdigest()
|
||||
write_record(directory / 'supervisor.json', journal)
|
||||
gate, messages = MessageGate(batch_id, attempt_id), queue.Queue()
|
||||
api, process, reader = _Win32Api(), None, None
|
||||
sent_cancel, last_heartbeat = False, time.monotonic()
|
||||
transport_error = None
|
||||
force_accepted = False
|
||||
def receive():
|
||||
try:
|
||||
while line := process.stdout.readline(1024 * 1024):
|
||||
@@ -242,9 +317,26 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
reader = threading.Thread(target=receive, daemon=True)
|
||||
reader.start()
|
||||
while process.poll() is None or not messages.empty():
|
||||
force = getattr(stop_event, 'force_event', None)
|
||||
if force is not None and force.is_set() and process.poll() is None:
|
||||
try:
|
||||
_force_owned_supervisor(root, journal, process)
|
||||
except Exception as error:
|
||||
force.clear()
|
||||
stop_event.control_error = '强制结束未执行或未确认;请保留窗口和诊断:' + str(error)
|
||||
service._logging.logger.error('force_stop_failed batch_id=%s error=%s', batch_id, error)
|
||||
else:
|
||||
force_accepted = True
|
||||
break
|
||||
if stop_event is not None and stop_event.is_set() and not sent_cancel:
|
||||
write_record(directory / 'cancel.json', {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id})
|
||||
sent_cancel = True
|
||||
try:
|
||||
write_record(directory / 'cancel.json', {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id})
|
||||
journal.update(stop_mode='safe', stop_requested_at=time.time())
|
||||
write_record(directory / 'supervisor.json', journal)
|
||||
sent_cancel = True
|
||||
except OSError as error:
|
||||
if hasattr(stop_event, 'control_error'):
|
||||
stop_event.control_error = '停止请求尚未成功记录,正在重试:' + str(error)
|
||||
try:
|
||||
value = messages.get(timeout=.1)
|
||||
except queue.Empty:
|
||||
@@ -264,6 +356,7 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
state = decode(value['payload'])
|
||||
service._task_queue_feedback = state['queue']
|
||||
service._batch_feedback = state['batch']
|
||||
service._supervisor_waiting = bool(state.get('waiting_for_resolution'))
|
||||
if on_phase is not None and state['phase'] in {'recycling', 'closing'}:
|
||||
from .bom_import_state import BomImportPhase
|
||||
on_phase(BomImportPhase.RECOVERING if state['phase'] == 'recycling' else BomImportPhase.RELEASING,
|
||||
@@ -271,9 +364,12 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
process.wait(timeout=15)
|
||||
except Exception as error:
|
||||
transport_error = error
|
||||
if process is not None and isinstance(stop_event, StopControl):
|
||||
force_accepted = _retain_supervisor_after_control_error(root, journal, process, stop_event, error)
|
||||
finally:
|
||||
service._task_queue_feedback = None
|
||||
service._batch_feedback = None
|
||||
service._supervisor_waiting = False
|
||||
try:
|
||||
if process is not None:
|
||||
process.close() # Waits, and confines termination to the owned Job.
|
||||
@@ -285,6 +381,14 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
'batch_resources_pending', f'监督进程错误:{transport_error};收尾错误:{error}')
|
||||
if reader is not None:
|
||||
reader.join(3)
|
||||
if force_accepted:
|
||||
from .batch_resources import cleanup_pending_resources
|
||||
try:
|
||||
cleanup_pending_resources(root, logging_context=service._logging)
|
||||
except Exception as error:
|
||||
service._logging.logger.error('forced_stop_cleanup_pending batch_id=%s error=%s', batch_id, error)
|
||||
raise TaskCenterError('user_forced_stop',
|
||||
'已按确认强制结束;已保存的执行证据保留,当前结果待核验。请先核验恢复,不要重复替换。')
|
||||
try:
|
||||
try:
|
||||
response = json.loads(internal_path(directory / 'result.json').read_text(encoding='utf-8'))
|
||||
|
||||
@@ -75,7 +75,7 @@ def run(request_path):
|
||||
request = json.loads(request_bytes)
|
||||
batch_id, attempt_id = request['batch_id'], request['attempt_id']
|
||||
if (request.get('version') != VERSION or UUID(batch_id).hex != batch_id or UUID(attempt_id).hex != attempt_id
|
||||
or request['operation'] not in OPERATIONS):
|
||||
or request['operation'] not in OPERATIONS or type(request.get('interactive_stop', False)) is not bool):
|
||||
raise ValueError('Invalid batch supervisor request')
|
||||
root = canonical_path(request['root'])
|
||||
directory = root / 'batch-resources' / batch_id
|
||||
@@ -83,7 +83,9 @@ def run(request_path):
|
||||
raise ValueError('Supervisor request ownership path mismatch')
|
||||
_admit_request(directory, request, request_bytes)
|
||||
_worker_context(root)
|
||||
stop, finished, output_lock = threading.Event(), threading.Event(), threading.Lock()
|
||||
from .stop_control import StopControl
|
||||
stop = StopControl() if request.get('interactive_stop', False) else threading.Event()
|
||||
finished, output_lock = threading.Event(), threading.Lock()
|
||||
kind = {'inspect_bom_batch': 'bom_import', 'preview_bom_batch': 'bom_import',
|
||||
'execute_task_queue': 'task_queue', 'execute_quick_run_queue': 'quick_run_queue'}.get(request['operation'], request['operation'])
|
||||
runtime = BatchCadRuntime(root, kind, stop, session_id=batch_id)
|
||||
@@ -113,7 +115,9 @@ def run(request_path):
|
||||
emit('heartbeat')
|
||||
feedback = getattr(service, '_task_queue_feedback', None)
|
||||
emit('state', encode({'phase': runtime.record['state'], 'queue': feedback,
|
||||
'batch': service.batch_feedback()}))
|
||||
'batch': service.batch_feedback(),
|
||||
'waiting_for_resolution': getattr(stop, 'waiting_for_resolution', False),
|
||||
'resolution_error': getattr(stop, 'resolution_error', '')}))
|
||||
except Exception:
|
||||
stop.set() # Lost control evidence cannot authorize new work.
|
||||
finished.wait(1)
|
||||
|
||||
@@ -13,6 +13,7 @@ class ExecutionFeedback:
|
||||
message: str = '正在准备执行'
|
||||
stage: str = ''
|
||||
stage_seconds: float = 0.0
|
||||
waiting_for_safe_completion: bool = False
|
||||
|
||||
|
||||
def read_feedback(task_id, position, total, message, root: Path, started_after: float):
|
||||
@@ -27,15 +28,16 @@ def read_feedback(task_id, position, total, message, root: Path, started_after:
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
pass
|
||||
path = root / 'quick-run' / 'worker-progress.json'
|
||||
stage, seconds = '', 0.0
|
||||
stage, seconds, waiting = '', 0.0, False
|
||||
try:
|
||||
modified = path.stat().st_mtime
|
||||
if modified >= started_after:
|
||||
record = json.loads(path.read_text(encoding='utf-8'))
|
||||
waiting = record.get('waiting_for_safe_completion') is True
|
||||
candidate = record.get('stage', '')
|
||||
if candidate and candidate != 'finished':
|
||||
seconds = float(record.get('stage_seconds', {}).get(candidate, 0)) + max(0, time.time() - modified)
|
||||
stage = candidate
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
pass # Display feedback is optional; it never changes execution state.
|
||||
return ExecutionFeedback(task_id, position, total, message, stage, seconds)
|
||||
return ExecutionFeedback(task_id, position, total, message, stage, seconds, waiting)
|
||||
@@ -87,7 +87,7 @@ def _designer_executable():
|
||||
|
||||
class IsolatedCadSession:
|
||||
"""The supervisor never attaches to COM on the user's input desktop."""
|
||||
def __init__(self, root, *, abort_event=None, desktop=None):
|
||||
def __init__(self, root, *, abort_event=None, desktop=None, stop_control=None):
|
||||
self.root = canonical_path(root)
|
||||
self.token = uuid4().hex
|
||||
self.borrowed_desktop = desktop is not None
|
||||
@@ -96,6 +96,7 @@ class IsolatedCadSession:
|
||||
self.binding = None
|
||||
self.started = time.monotonic()
|
||||
self.abort_event = abort_event
|
||||
self.stop_control = stop_control
|
||||
self.record = {'desktop': self.desktop.name, 'token': self.token, 'state': 'starting'}
|
||||
|
||||
def _record(self, **values):
|
||||
@@ -206,52 +207,115 @@ class IsolatedCadSession:
|
||||
|
||||
def __exit__(self, error_type, error, traceback):
|
||||
closing_started = time.monotonic()
|
||||
cleanup_error = None
|
||||
cleanup_errors = []
|
||||
diagnostic_errors = []
|
||||
failures = []
|
||||
exit_codes = {}
|
||||
closing = None
|
||||
|
||||
def remember(stage, failure):
|
||||
cleanup_errors.append({'stage': stage, 'message': str(failure)})
|
||||
message = '; '.join(f"{item['stage']}: {item['message']}" for item in cleanup_errors)
|
||||
self._uncertain(message, cleanup_errors=cleanup_errors,
|
||||
failures.append(failure)
|
||||
|
||||
def diagnose(stage, action):
|
||||
try:
|
||||
action()
|
||||
except Exception as failure:
|
||||
diagnostic_errors.append({'stage': stage, 'message': str(failure)})
|
||||
failures.append(failure)
|
||||
self.record['clean'] = False
|
||||
|
||||
def failure_message():
|
||||
return '; '.join(f"{item['stage']}: {item['message']}"
|
||||
for item in cleanup_errors + diagnostic_errors)
|
||||
|
||||
def persist_uncertain():
|
||||
message = failure_message() or str(error)
|
||||
self.record.update(state='uncertain', clean=False, error=message,
|
||||
cleanup_errors=cleanup_errors, diagnostic_errors=diagnostic_errors,
|
||||
shutdown_seconds=time.monotonic() - closing_started,
|
||||
desktop_cleanup=getattr(self.desktop, 'cleanup_record', None), **exit_codes)
|
||||
diagnose('uncertain_record', lambda: self._uncertain(message,
|
||||
cleanup_errors=cleanup_errors, diagnostic_errors=diagnostic_errors,
|
||||
clean=False, orderly_shutdown=self.record['orderly_shutdown'],
|
||||
shutdown_seconds=time.monotonic() - closing_started,
|
||||
desktop_cleanup=getattr(self.desktop, 'cleanup_record', None), **exit_codes))
|
||||
|
||||
self.record.update(clean=False, orderly_shutdown=False, forced_termination=False,
|
||||
forced_root_termination=False, forced_descendant_pids=[], termination_reason=None,
|
||||
cleanup_errors=cleanup_errors, diagnostic_errors=diagnostic_errors)
|
||||
diagnose('closing_record', lambda: self._record(state='closing', clean=False,
|
||||
cleanup_errors=cleanup_errors, diagnostic_errors=diagnostic_errors))
|
||||
try:
|
||||
self._record(state='closing', cleanup_errors=cleanup_errors)
|
||||
if error is not None:
|
||||
self._uncertain(str(error))
|
||||
if self.cad is not None and self.cad.poll() is not None:
|
||||
raise WorkerMonitorError('owned CAD exited before the authorized quit request')
|
||||
if self.cad is not None and self.binding is not None:
|
||||
closing = self.desktop.start_process(_helper_command('quit', self.root / 'private-desktop.json', self.cad.pid),
|
||||
env=_child_environment(self.binding.environment()), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
try:
|
||||
quit_code = closing.wait(timeout=20)
|
||||
exit_codes['quit_helper_exit_code'] = quit_code
|
||||
if quit_code:
|
||||
raise WorkerMonitorError('owned CAD refused orderly exit: ' + closing.stderr.read().decode('utf-8', errors='replace'))
|
||||
cad_code = self.cad.wait(timeout=15)
|
||||
exit_codes['cad_exit_code'] = cad_code
|
||||
if cad_code != 0:
|
||||
raise WorkerMonitorError('owned CAD returned a nonzero exit code after quit')
|
||||
finally:
|
||||
closing.close()
|
||||
quit_code = closing.wait(timeout=20)
|
||||
exit_codes['quit_helper_exit_code'] = quit_code
|
||||
if quit_code:
|
||||
raise WorkerMonitorError('owned CAD refused orderly exit: ' + closing.stderr.read().decode('utf-8', errors='replace'))
|
||||
cad_code = self.cad.wait(timeout=15)
|
||||
exit_codes['cad_exit_code'] = cad_code
|
||||
if cad_code != 0:
|
||||
raise WorkerMonitorError('owned CAD returned a nonzero exit code after quit')
|
||||
self.record['orderly_shutdown'] = True
|
||||
except Exception as failure:
|
||||
cleanup_error = failure
|
||||
remember('orderly_shutdown', failure)
|
||||
finally:
|
||||
if error is not None or failures:
|
||||
# Evidence failure must never prevent the identity-checked Quit
|
||||
# above or release of the handles we own below.
|
||||
persist_uncertain()
|
||||
if self.stop_control is not None and cleanup_errors and self.cad is not None:
|
||||
cad_running = True
|
||||
try:
|
||||
cad_running = self.cad.poll() is None
|
||||
except Exception as failure:
|
||||
remember('cad_exit_check', failure)
|
||||
if cad_running:
|
||||
# A refused/timed-out Quit may still be saving or closing.
|
||||
# Keep both CAD and its helper owned and alive until the
|
||||
# interactive caller confirms force, including ordinary stop.
|
||||
from .stop_control import wait_for_resolution
|
||||
try:
|
||||
wait_for_resolution(self.stop_control, self.root, failure_message())
|
||||
except WorkerMonitorError as failure:
|
||||
force_event = getattr(self.stop_control, 'force_event', None)
|
||||
if force_event is None or not force_event.is_set():
|
||||
raise
|
||||
remember('forced_stop', failure)
|
||||
if closing is not None:
|
||||
try:
|
||||
closing.close()
|
||||
except Exception as failure:
|
||||
remember('quit_helper_release', failure)
|
||||
try:
|
||||
self.desktop.close()
|
||||
self._record(state='session_closed' if self.borrowed_desktop else 'released',
|
||||
desktop_retained_by_batch=self.borrowed_desktop,
|
||||
clean=error is None and cleanup_error is None,
|
||||
shutdown_seconds=time.monotonic() - closing_started,
|
||||
desktop_cleanup=getattr(self.desktop, 'cleanup_record', None), **exit_codes)
|
||||
except Exception as failure:
|
||||
cleanup_error = failure
|
||||
remember('desktop_release', failure)
|
||||
if cleanup_error is not None:
|
||||
message = '; '.join(f"{item['stage']}: {item['message']}" for item in cleanup_errors)
|
||||
raise WorkerMonitorError('private CAD cleanup requires reconciliation: ' + message) from cleanup_error
|
||||
desktop_cleanup = getattr(self.desktop, 'cleanup_record', None) or {}
|
||||
forced = [item for item in desktop_cleanup.get('processes', []) if item.get('forced_termination')]
|
||||
self.record.update(forced_termination=bool(forced),
|
||||
forced_root_termination=any(item.get('forced_root_termination') for item in forced),
|
||||
termination_reason=next((item.get('termination_reason') for item in forced
|
||||
if item.get('termination_reason')), None),
|
||||
forced_descendant_pids=sorted({pid for item in forced for pid in item.get('forced_descendant_pids', [])}))
|
||||
if forced:
|
||||
remember('forced_cleanup', WorkerMonitorError('owned processes required forced termination'))
|
||||
if error is not None or failures:
|
||||
persist_uncertain()
|
||||
else:
|
||||
diagnose('released_record', lambda: self._record(
|
||||
state='session_closed' if self.borrowed_desktop else 'released',
|
||||
desktop_retained_by_batch=self.borrowed_desktop, clean=True,
|
||||
shutdown_seconds=time.monotonic() - closing_started,
|
||||
desktop_cleanup=desktop_cleanup, **exit_codes))
|
||||
if failures:
|
||||
persist_uncertain()
|
||||
if failures:
|
||||
raise WorkerMonitorError('private CAD cleanup requires reconciliation: ' + failure_message()) from failures[0]
|
||||
|
||||
def _uncertain(self, message, **details):
|
||||
from .quick_run import _write_uncertain_flag
|
||||
|
||||
@@ -23,6 +23,7 @@ from .errors import TaskCenterError
|
||||
|
||||
|
||||
DESKTOP_RELEASE_TIMEOUT_SECONDS = 5.0
|
||||
DESCENDANT_EXIT_GRACE_SECONDS = 2.0
|
||||
|
||||
|
||||
def _native_handle(handle):
|
||||
@@ -192,7 +193,10 @@ def _stop_and_wait(process):
|
||||
errors.append(error)
|
||||
if running:
|
||||
try:
|
||||
process.terminate()
|
||||
if isinstance(process, _Win32Process):
|
||||
process.terminate(reason='root_process_active')
|
||||
else:
|
||||
process.terminate()
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
try:
|
||||
@@ -313,7 +317,9 @@ class _Win32Process:
|
||||
self.job_assigned = False
|
||||
self.returncode = None
|
||||
self.stdout = self.stderr = None
|
||||
self.cleanup_record = {'pid': self.pid}
|
||||
self.cleanup_record = {'pid': self.pid, 'forced_termination': False,
|
||||
'forced_root_termination': False, 'forced_descendant_pids': [],
|
||||
'termination_reason': None}
|
||||
|
||||
def poll(self):
|
||||
if self.returncode is not None or self.handle is None:
|
||||
@@ -340,34 +346,59 @@ class _Win32Process:
|
||||
self.returncode = self._process_api.GetExitCodeProcess(self.handle)
|
||||
return self.returncode
|
||||
|
||||
def terminate(self):
|
||||
def terminate(self, *, reason='explicit_termination'):
|
||||
if self.handle is None:
|
||||
return
|
||||
errors = []
|
||||
root_active = True
|
||||
try:
|
||||
root_active = self.poll() is None
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
self.cleanup_record.setdefault('root_exit_before_cleanup', not root_active)
|
||||
if not self.job_assigned:
|
||||
self._process_api.TerminateProcess(self.handle, 1)
|
||||
self._record_termination(reason, root_active, ())
|
||||
_raise_cleanup_errors(errors)
|
||||
return
|
||||
errors = []
|
||||
descendants = set()
|
||||
try:
|
||||
self._remember_descendants()
|
||||
# Keep confirmed members of this snapshot even if opening a later
|
||||
# member fails; the Job termination below still includes them.
|
||||
self._remember_descendants(active=descendants)
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
try:
|
||||
self._job_api.TerminateJobObject(self.job, 1)
|
||||
self._record_termination(reason, root_active, descendants)
|
||||
except Exception:
|
||||
self._process_api.TerminateProcess(self.handle, 1)
|
||||
self._record_termination(reason, root_active, ())
|
||||
_raise_cleanup_errors(errors)
|
||||
|
||||
kill = terminate
|
||||
|
||||
def _remember_descendants(self):
|
||||
def _record_termination(self, reason, root_active, descendants):
|
||||
self.cleanup_record.update(forced_termination=True,
|
||||
forced_root_termination=self.cleanup_record['forced_root_termination'] or root_active,
|
||||
forced_descendant_pids=sorted(set(self.cleanup_record['forced_descendant_pids']) | set(descendants)),
|
||||
termination_reason=self.cleanup_record['termination_reason'] or reason)
|
||||
|
||||
def _remember_descendants(self, *, active=None):
|
||||
if active is None:
|
||||
active = set()
|
||||
if self._open_process is None or self.job is None:
|
||||
return
|
||||
return active
|
||||
for pid in self._job_api.QueryInformationJobObject(self.job, self._job_api.JobObjectBasicProcessIdList):
|
||||
if pid == self.pid or pid in self._descendant_pids:
|
||||
if pid == self.pid:
|
||||
continue
|
||||
if pid in self._descendant_pids:
|
||||
active.add(pid)
|
||||
continue
|
||||
try:
|
||||
self._descendant_handles.append(self._open_process(0x100000, False, pid))
|
||||
self._descendant_pids.add(pid)
|
||||
active.add(pid)
|
||||
except Exception as error:
|
||||
# pywintypes.error is not an OSError. A child that exited
|
||||
# between the job snapshot and OpenProcess reports error 87.
|
||||
@@ -376,22 +407,47 @@ class _Win32Process:
|
||||
code = error.args[0]
|
||||
if code != 87:
|
||||
raise
|
||||
return active
|
||||
|
||||
def close(self):
|
||||
errors = []
|
||||
job_empty = not self.job_assigned or self.job is None
|
||||
if self.handle is not None:
|
||||
if 'root_exit_before_cleanup' not in self.cleanup_record:
|
||||
try:
|
||||
self.cleanup_record['root_exit_before_cleanup'] = self.poll() is not None
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
errors.extend(_stop_and_wait(self))
|
||||
deadline = time.monotonic() + 5.0
|
||||
if self.job is not None and self.job_assigned:
|
||||
try:
|
||||
# A completed root can leave grandchildren holding the desktop.
|
||||
self._remember_descendants()
|
||||
self._job_api.TerminateJobObject(self.job, 1)
|
||||
grace_started = time.monotonic()
|
||||
grace_deadline = grace_started + DESCENDANT_EXIT_GRACE_SECONDS
|
||||
# A completed root may leave children finishing normal shutdown.
|
||||
# An empty job takes no grace delay; an active root was already
|
||||
# stopped above and does not receive this normal-exit allowance.
|
||||
while True:
|
||||
active = self._job_api.QueryInformationJobObject(
|
||||
self.job, self._job_api.JobObjectBasicAccountingInformation)['ActiveProcesses']
|
||||
self.cleanup_record['job_active_processes'] = active
|
||||
if not active:
|
||||
job_empty = True
|
||||
break
|
||||
self._remember_descendants()
|
||||
if (self.cleanup_record.get('root_exit_before_cleanup') is not True
|
||||
or self.cleanup_record['forced_termination'] or time.monotonic() >= grace_deadline):
|
||||
self.terminate(reason='descendant_grace_expired')
|
||||
break
|
||||
time.sleep(min(0.01, max(0, grace_deadline - time.monotonic())))
|
||||
self.cleanup_record['descendant_grace_seconds'] = time.monotonic() - grace_started
|
||||
deadline = time.monotonic() + 5.0
|
||||
while True:
|
||||
active = self._job_api.QueryInformationJobObject(
|
||||
self.job, self._job_api.JobObjectBasicAccountingInformation)['ActiveProcesses']
|
||||
self.cleanup_record['job_active_processes'] = active
|
||||
if not active:
|
||||
job_empty = True
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError('owned job descendants did not exit within 5 seconds')
|
||||
@@ -417,6 +473,10 @@ class _Win32Process:
|
||||
self._descendant_handles = retained
|
||||
for name in ('job', 'thread', 'handle'):
|
||||
handle = getattr(self, name)
|
||||
if name in ('job', 'handle') and not job_empty:
|
||||
# Closing a KILL_ON_JOB_CLOSE job would silently force remaining
|
||||
# children and discard the capability needed for cleanup retry.
|
||||
continue
|
||||
if name == 'handle' and self.returncode is None:
|
||||
# Keep the only termination/wait capability until cleanup can retry.
|
||||
continue
|
||||
|
||||
@@ -111,6 +111,13 @@ class ProjectSessionWorker:
|
||||
return
|
||||
if not self._done.is_set():
|
||||
_write_control(self.root / 'project-session-next.tsv', f'{self.token}\tclose')
|
||||
from .stop_control import StopControl
|
||||
interactive = isinstance(getattr(self.runtime, 'stop_event', None), StopControl)
|
||||
if interactive:
|
||||
# The monitor owns the safe/unsafe distinction. Do not
|
||||
# turn a GUI close or ordinary pause into a timed kill.
|
||||
while not self._done.wait(.1):
|
||||
pass
|
||||
close_grace = 60 if self.private_desktop else min(30, max(10, self._timeout))
|
||||
if not self._done.wait(close_grace):
|
||||
self._abort.set()
|
||||
|
||||
@@ -925,6 +925,9 @@ class TaskCenterService:
|
||||
message = batch[2] if batch else '正在准备执行'
|
||||
value = read_feedback(task_id, position, total, message,
|
||||
child._quick_run_preparer.data_root, started_after)
|
||||
if getattr(self, '_supervisor_waiting', False):
|
||||
from dataclasses import replace
|
||||
value = replace(value, stage='awaiting_reconciliation', waiting_for_safe_completion=True)
|
||||
if read_control is not None:
|
||||
read_control.checkpoint()
|
||||
return value
|
||||
@@ -951,12 +954,12 @@ class TaskCenterService:
|
||||
return delegated.has_interrupted_quick_run(task_id)
|
||||
return self._quick_run_preparer.has_interrupted(task_id)
|
||||
|
||||
def recover_quick_run(self, task_id: str, *, confirmed: bool = False, runtime=None) -> QuickRunStepResult:
|
||||
def recover_quick_run(self, task_id: str, *, confirmed: bool = False, runtime=None, stop_event=None) -> QuickRunStepResult:
|
||||
if runtime is None and self._supervised:
|
||||
return self._supervise('recover_quick_run', {'task_id': task_id, 'confirmed': confirmed})
|
||||
return self._supervise('recover_quick_run', {'task_id': task_id, 'confirmed': confirmed}, stop_event=stop_event)
|
||||
if runtime is None:
|
||||
return self._owned_cad_operation('recover_quick_run', lambda owned:
|
||||
self.recover_quick_run(task_id, confirmed=confirmed, runtime=owned), task_id=task_id)
|
||||
self.recover_quick_run(task_id, confirmed=confirmed, runtime=owned), stop_event, task_id=task_id)
|
||||
delegated = self._project_task_service(task_id)
|
||||
if delegated is not self:
|
||||
return delegated.recover_quick_run(task_id, confirmed=confirmed, runtime=runtime)
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Separate ordinary stop intent from an explicitly confirmed forced interruption."""
|
||||
from threading import Event
|
||||
import json
|
||||
import os
|
||||
|
||||
from .path_access import internal_path
|
||||
|
||||
|
||||
class StopControl(Event):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.force_event = Event()
|
||||
self.control_error = ''
|
||||
self.waiting_for_resolution = False
|
||||
self.resolution_error = ''
|
||||
|
||||
def request_force(self):
|
||||
self.set()
|
||||
self.control_error = ''
|
||||
self.force_event.set()
|
||||
|
||||
|
||||
def protect_interruption(root, reason):
|
||||
"""Create or re-sync a marker without overwriting prior protection evidence."""
|
||||
root = internal_path(root)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
marker = root / 'uncertain.flag'
|
||||
try:
|
||||
stream = marker.open('x', encoding='utf-8')
|
||||
except FileExistsError:
|
||||
# A previous create/write/fsync may have failed. Existence alone does
|
||||
# not establish durable evidence; preserve its bytes but sync again.
|
||||
with marker.open('r+b') as existing:
|
||||
os.fsync(existing.fileno())
|
||||
else:
|
||||
with stream:
|
||||
stream.write(str(reason))
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def wait_for_resolution(control, root, error):
|
||||
"""Interactive owners retain a possibly changed project until explicit force.
|
||||
|
||||
The GUI-side supervisor can also terminate its own Job after durable force
|
||||
evidence. Ordinary cancellation never releases this wait.
|
||||
"""
|
||||
if not isinstance(control, StopControl):
|
||||
return
|
||||
from .worker_monitor import WorkerMonitorError, _publish_progress
|
||||
root = internal_path(root)
|
||||
control.set()
|
||||
control.waiting_for_resolution = True
|
||||
control.resolution_error = str(error)
|
||||
def protect():
|
||||
protect_interruption(root, 'operation_interrupted: ' + str(error))
|
||||
try:
|
||||
protect()
|
||||
except OSError as failure:
|
||||
control.control_error = '保护记录写入失败,保留应用等待处理:' + str(failure)
|
||||
try:
|
||||
record = json.loads((root / 'worker-progress.json').read_text(encoding='utf-8'))
|
||||
if not isinstance(record, dict):
|
||||
record = {}
|
||||
except (OSError, ValueError):
|
||||
record = {}
|
||||
record.update(stage='awaiting_reconciliation', waiting_for_safe_completion=True,
|
||||
resolution_error=str(error), stop_requested=True, safe_stop=False)
|
||||
_publish_progress(root / 'worker-progress.json', record)
|
||||
while True:
|
||||
if control.force_event.wait(.1):
|
||||
try:
|
||||
protect()
|
||||
except OSError as failure:
|
||||
control.force_event.clear()
|
||||
control.control_error = '强制结束未执行,保护记录无法保存:' + str(failure)
|
||||
continue
|
||||
raise WorkerMonitorError('user forced stop of uncertain operation; reconciliation required')
|
||||
@@ -15,6 +15,7 @@ STAGES = {
|
||||
'restore_attribute_fields': '恢复属性字段', 'restore_attributes': '恢复属性',
|
||||
'verify_restoration': '核验恢复结果', 'verify_attribute_fields': '核验属性字段',
|
||||
'save_and_close': '保存并关闭工程', 'verify_saved_project': '回读已保存工程',
|
||||
'awaiting_reconciliation': '当前结果待核验,已保留工程现场',
|
||||
}
|
||||
|
||||
|
||||
@@ -22,4 +23,6 @@ def format_feedback(value, task_name, elapsed, stopping):
|
||||
stage = STAGES.get(value.stage, '')
|
||||
details = f'{stage}({value.stage_seconds:.1f} 秒)' if stage else value.message
|
||||
prefix = '等待当前步骤保存核验后暂停 · ' if stopping else ''
|
||||
if value.waiting_for_safe_completion:
|
||||
prefix = '当前保存或核验尚未确认,未自动结束应用;可继续等待、导出诊断,或确认强制结束后核验 · '
|
||||
return f'{prefix}任务 {value.position}/{value.total}:{task_name} · {details} · 总计 {elapsed} 秒'
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Single-project task presentation; persistence and CAD remain in the service."""
|
||||
from __future__ import annotations
|
||||
from threading import Event
|
||||
from ..stop_control import StopControl
|
||||
from shiboken6 import isValid
|
||||
import time
|
||||
from PySide6.QtCore import QElapsedTimer, QSettings, QSignalBlocker, QThreadPool, QTimer, Qt
|
||||
@@ -39,6 +40,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self._tasks = ()
|
||||
self._known_task_groups = {}
|
||||
self._workers = set()
|
||||
self._diagnostic_worker = None
|
||||
self._closed = False
|
||||
self._batch_stop = None
|
||||
self._active_quick_run_task_id = None
|
||||
@@ -88,6 +90,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self._log_presenter = TaskLogPresenter(service, self.run_panel, self)
|
||||
self.run_panel.quick_run_button.clicked.connect(self._prepare_quick_run)
|
||||
self.run_panel.stop_queue_button.clicked.connect(self._pause_queue)
|
||||
self.run_panel.force_stop_button.clicked.connect(self._force_batch_stop)
|
||||
self.run_panel.retry_button.clicked.connect(self._retry_failed)
|
||||
self.run_panel.recover_button.clicked.connect(self._recover_quick_run)
|
||||
self.run_panel.cleanup_resources_button.clicked.connect(self._cleanup_batch_resources)
|
||||
@@ -337,6 +340,10 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self.run_panel.history_button.setEnabled(bool(context and not busy))
|
||||
self.run_panel.stop_queue_button.setVisible(self._batch_stop is not None)
|
||||
self.run_panel.stop_queue_button.setEnabled(bool(self._batch_stop and not self._batch_stop.is_set()))
|
||||
self.run_panel.force_stop_button.setVisible(self._batch_stop is not None)
|
||||
self.run_panel.force_stop_button.setEnabled(bool(self._batch_stop and
|
||||
not self._batch_stop.force_event.is_set()))
|
||||
self.run_panel.diagnostics_button.setEnabled(self._diagnostic_worker is None)
|
||||
self.run_panel.copy_value_check.setEnabled(state.editable)
|
||||
rule_editable = state.editable and not group_unsaved
|
||||
self.mapping_table.set_rules_editable(rule_editable)
|
||||
@@ -571,6 +578,8 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self._finish_run()
|
||||
self._metadata_changed(None)
|
||||
failures = sum(e.state in {'failed', 'blocked'} for e in result.entries)
|
||||
if failures:
|
||||
self._close_pending = False
|
||||
self._show_task_log(force=True)
|
||||
self._set_operator_message(f'本批任务已暂停。失败/阻断 {failures} 项。' if result.paused else f'本批任务已结束。失败 {failures} 项。',
|
||||
'warning' if result.paused or failures else 'success')
|
||||
@@ -578,7 +587,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self.task_list.queue_button)
|
||||
|
||||
def _begin_run(self, task_id):
|
||||
self._batch_stop = Event()
|
||||
self._batch_stop = StopControl()
|
||||
self._active_quick_run_task_id = task_id
|
||||
self._run_started_at = time.time()
|
||||
self._quick_run_elapsed.start()
|
||||
@@ -601,6 +610,24 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self._set_operator_message('已请求暂停;当前项安全收尾后停止。', 'warning')
|
||||
self._update_gates()
|
||||
|
||||
def _force_batch_stop(self):
|
||||
control = self._batch_stop
|
||||
if control is None or control.force_event.is_set():
|
||||
return
|
||||
if QMessageBox.question(self, '强制结束当前操作',
|
||||
'当前操作可能正在修改或保存工程。强制结束可能留下未保存或部分保存的结果。\n\n'
|
||||
'已完成的执行证据会保留;中断后必须先核验恢复,不能直接重复替换。'
|
||||
'建议先导出诊断包。确定强制结束本程序当前操作吗?',
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes:
|
||||
return
|
||||
if self._batch_stop is not control:
|
||||
return # Completion/new run while the confirmation dialog was open.
|
||||
self._close_pending = False
|
||||
control.request_force()
|
||||
self._set_operator_message('已请求强制结束;正在记录中断证据,结果将进入待核验。', 'warning')
|
||||
self._update_gates()
|
||||
|
||||
def _show_batch_result(self, result):
|
||||
owner = self._active_quick_run_task_id or self._task_id
|
||||
name = next((t.name for t in self._tasks if t.task_id == owner), owner)
|
||||
@@ -609,6 +636,8 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
if owner == self._task_id:
|
||||
self._show_task_log(force=True)
|
||||
p = result.progress
|
||||
if p.failed_items:
|
||||
self._close_pending = False
|
||||
self._set_operator_message(f"任务「{name}」{'已暂停' if result.paused else '已结束'}:已保存 {p.saved_items},失败 {p.failed_items},未命中 {p.no_match_items}。",
|
||||
'warning' if result.paused or p.failed_items else 'success')
|
||||
|
||||
@@ -637,10 +666,31 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
from pathlib import Path
|
||||
name = 'DxPartReplace-诊断-' + time.strftime('%Y%m%d-%H%M%S') + '.zip'
|
||||
value, _ = QFileDialog.getSaveFileName(self, '导出脱敏诊断包', name, 'ZIP 文件 (*.zip)')
|
||||
if value:
|
||||
self._run_async(lambda: self.service.export_diagnostics(Path(value)),
|
||||
lambda path: self._set_operator_message(f'脱敏诊断包已导出:{path}', 'success'),
|
||||
self.run_panel.diagnostics_button)
|
||||
if not value or self._diagnostic_worker is not None:
|
||||
return
|
||||
# A read-only support export remains available while CAD is waiting.
|
||||
worker = ServiceWorker(lambda: self.service.export_diagnostics(Path(value)))
|
||||
self._diagnostic_worker = worker
|
||||
self._workers.add(worker)
|
||||
def exported(path):
|
||||
if not self._closed:
|
||||
self._set_operator_message(f'脱敏诊断包已导出:{path}', 'success')
|
||||
def failed(error):
|
||||
self._close_pending = False
|
||||
if not self._closed:
|
||||
self._show_error(error)
|
||||
def finished():
|
||||
self._workers.discard(worker)
|
||||
self._diagnostic_worker = None
|
||||
if not self._closed:
|
||||
self._update_gates()
|
||||
if self._close_pending and not self._workers:
|
||||
QTimer.singleShot(0, self.close)
|
||||
worker.signals.succeeded.connect(exported)
|
||||
worker.signals.failed.connect(failed)
|
||||
worker.signals.finished.connect(finished)
|
||||
self._update_gates()
|
||||
QThreadPool.globalInstance().start(worker)
|
||||
|
||||
def _retry_failed(self):
|
||||
if self.run_panel.retry_button.isEnabled():
|
||||
@@ -700,7 +750,8 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self._finish_run()
|
||||
self._metadata_changed(None)
|
||||
self._set_operator_message(result.message)
|
||||
self._run_async(lambda: self.service.recover_quick_run(task_id, confirmed=True), done,
|
||||
stop = self._batch_stop
|
||||
self._run_async(lambda: self.service.recover_quick_run(task_id, confirmed=True, stop_event=stop), done,
|
||||
self.run_panel.recover_button, expected_task_id=task_id)
|
||||
|
||||
def _confirm_quick_run(self, scope, selected_projects, enabled_rules):
|
||||
@@ -725,6 +776,9 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self.run_panel.execution_status.setText(format_feedback(
|
||||
value, name, self._quick_run_elapsed.elapsed() // 1000,
|
||||
bool(self._batch_stop and self._batch_stop.is_set())))
|
||||
if self._batch_stop and self._batch_stop.control_error:
|
||||
self._set_operator_message(self._batch_stop.control_error, 'warning')
|
||||
self._update_gates()
|
||||
self._feedback_query.request(lambda control: self.service.execution_feedback(task_id, started_after=started, read_control=control),
|
||||
received, lambda _: None, cancellable=True)
|
||||
if self.run_panel.toggle_log_button.isChecked():
|
||||
@@ -799,6 +853,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
callback(result)
|
||||
except Exception as error:
|
||||
operation_error = error
|
||||
self._close_pending = False
|
||||
self.operation_state = self.operation_state.finish(error)
|
||||
self._show_error(error)
|
||||
def failed(error):
|
||||
|
||||
@@ -4,6 +4,8 @@ import json
|
||||
import re
|
||||
|
||||
ERROR_TEXT = {
|
||||
'user_forced_stop': '操作已强制中断,结果待核验。',
|
||||
'application_shutdown_failed': '业务结果已保留,但应用收尾异常。',
|
||||
"batch_resources_pending": "后台资源尚未确认释放,请使用“重新清理资源”后再开始下一批。",
|
||||
"supervisor_busy": "另一批操作正在执行,请先安全收尾。",
|
||||
"supervisor_interrupted": "批次监督连接异常,保护记录已保留,没有自动重放替换。",
|
||||
|
||||
@@ -23,6 +23,8 @@ class RunPanel(QWidget):
|
||||
self.busy_indicator.hide()
|
||||
self.quick_run_button = QPushButton('执行当前任务', objectName='quickRunButton')
|
||||
self.stop_queue_button = QPushButton('完成当前项后暂停', objectName='stopQueueButton')
|
||||
self.force_stop_button = QPushButton('强制结束…', objectName='forceStopButton')
|
||||
self.force_stop_button.setToolTip('异常情况下使用;会中断当前操作,结果必须重新核验。')
|
||||
self.retry_button = QPushButton('重试失败项', objectName='retryTaskItems')
|
||||
self.recover_button = QPushButton('核验并恢复', objectName='recoverQuickRunButton')
|
||||
self.cleanup_resources_button = QPushButton('重新清理资源', objectName='cleanupBatchResources')
|
||||
@@ -42,7 +44,7 @@ class RunPanel(QWidget):
|
||||
self.toggle_log_button.toggled.connect(self._toggle_log)
|
||||
buttons = QHBoxLayout()
|
||||
for button in (self.quick_run_button, self.retry_button, self.recover_button, self.cleanup_resources_button, self.diagnostics_button,
|
||||
self.new_round_button, self.history_button, self.stop_queue_button):
|
||||
self.new_round_button, self.history_button, self.stop_queue_button, self.force_stop_button):
|
||||
buttons.addWidget(button)
|
||||
buttons.addStretch()
|
||||
buttons.addWidget(self.toggle_log_button)
|
||||
|
||||
@@ -35,6 +35,7 @@ class ProgressWatch:
|
||||
self.done = 0
|
||||
self.total = 0
|
||||
self.safe_stop = True
|
||||
self.waiting_for_safe_completion = False
|
||||
self.started = started
|
||||
self.stage_started = started
|
||||
self.stage_seconds: dict[str, float] = {}
|
||||
@@ -67,6 +68,7 @@ class ProgressWatch:
|
||||
self.native_sequence = 0
|
||||
self.last_progress = now
|
||||
self.stage, self.done, self.total, self.safe_stop = fields[4], done, total, bool(safe)
|
||||
self.waiting_for_safe_completion = False
|
||||
return True
|
||||
|
||||
def accept_native(self, line: bytes, now: float) -> bool:
|
||||
@@ -102,6 +104,11 @@ class ProgressWatch:
|
||||
self.stop_requested = True
|
||||
return 'request_stop'
|
||||
if self.stop_requested and idle >= self.idle_timeout * 2:
|
||||
if not self.safe_stop:
|
||||
if not self.waiting_for_safe_completion:
|
||||
self.waiting_for_safe_completion = True
|
||||
return 'await_safe_completion'
|
||||
return None
|
||||
return 'unresponsive'
|
||||
return None
|
||||
|
||||
@@ -109,7 +116,7 @@ class ProgressWatch:
|
||||
now = time.monotonic() if now is None else now
|
||||
stages = dict(self.stage_seconds)
|
||||
stages[self.stage] = stages.get(self.stage, 0.0) + max(0.0, now - self.stage_started)
|
||||
return {name: getattr(self, name) for name in ('token', 'sequence', 'stage', 'done', 'total', 'safe_stop', 'stop_requested')} | {
|
||||
return {name: getattr(self, name) for name in ('token', 'sequence', 'stage', 'done', 'total', 'safe_stop', 'stop_requested', 'waiting_for_safe_completion')} | {
|
||||
'job_id': self.current_job_id,
|
||||
'native_progress_frames': self.native_progress_frames,
|
||||
'elapsed_seconds': max(0.0, now - self.started), 'stage_seconds': stages}
|
||||
@@ -124,9 +131,8 @@ def _atomic_text(path: Path, text: str) -> None:
|
||||
def _publish_progress(path: Path, snapshot: dict) -> None:
|
||||
try:
|
||||
_atomic_text(path, json.dumps(snapshot, ensure_ascii=False))
|
||||
except OSError as error:
|
||||
if not isinstance(error, PermissionError) and getattr(error, 'winerror', None) not in {5, 32, 33}:
|
||||
raise
|
||||
except OSError:
|
||||
pass # Display telemetry failure must not terminate a possible CAD write.
|
||||
|
||||
|
||||
def _decode(data: bytes) -> str:
|
||||
@@ -190,7 +196,7 @@ class _OwnedWorkers:
|
||||
|
||||
|
||||
def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abort_event=None,
|
||||
process_factory=None, cooperative_abort=False) -> subprocess.CompletedProcess[str]:
|
||||
process_factory=None, cooperative_abort=False, force_event=None, force_control=None) -> subprocess.CompletedProcess[str]:
|
||||
root = Path(command[3]).resolve()
|
||||
job_id = command[-1]
|
||||
token = uuid4().hex
|
||||
@@ -200,8 +206,11 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
native_progress_path = root / f'monitor-{token}.native-progress'
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
watch = ProgressWatch(token, job_id, idle_timeout, time.monotonic())
|
||||
if force_control is not None:
|
||||
force_event = force_control.force_event
|
||||
owned = _OwnedWorkers(token, {command[0], command[4]})
|
||||
process = None
|
||||
durable_force_accepted = False
|
||||
threads = []
|
||||
messages = queue.Queue(maxsize=1024)
|
||||
stop_readers = threading.Event()
|
||||
@@ -244,15 +253,32 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
_atomic_text(ready, token)
|
||||
while process.poll() is None:
|
||||
if force_event is not None and force_event.is_set():
|
||||
from .stop_control import protect_interruption
|
||||
try:
|
||||
protect_interruption(root, 'user_forced_stop')
|
||||
except OSError as error:
|
||||
force_event.clear()
|
||||
if force_control is not None:
|
||||
force_control.control_error = '强制结束未执行,保护记录无法保存:' + str(error)
|
||||
watch.waiting_for_safe_completion = True
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
else:
|
||||
durable_force_accepted = True
|
||||
raise WorkerMonitorError('user forced stop; execution requires reconciliation')
|
||||
if abort_event is not None and abort_event.is_set():
|
||||
if not cooperative_abort:
|
||||
if not cooperative_abort and watch.safe_stop:
|
||||
raise WorkerMonitorError('project session supervisor requested worker cleanup')
|
||||
if not watch.stop_requested:
|
||||
# Read-only callers request the VBS safe boundary first.
|
||||
# The existing idle watchdog still bounds a stalled COM call.
|
||||
watch.stop_requested = True
|
||||
watch.last_progress = time.monotonic()
|
||||
_atomic_text(stop, token)
|
||||
try:
|
||||
_atomic_text(stop, token)
|
||||
except OSError:
|
||||
if watch.safe_stop:
|
||||
raise
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
try:
|
||||
receive(*messages.get(timeout=min(0.1, idle_timeout / 10)))
|
||||
@@ -273,7 +299,17 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
break
|
||||
action = watch.action(time.monotonic())
|
||||
if action == 'request_stop':
|
||||
_atomic_text(stop, token)
|
||||
try:
|
||||
_atomic_text(stop, token)
|
||||
except OSError:
|
||||
if watch.safe_stop:
|
||||
raise
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
elif action == 'await_safe_completion':
|
||||
if cooperative_abort:
|
||||
# This entry point is explicitly read-only. A blocked COM
|
||||
# read has no write to finish and retains its bounded cancel.
|
||||
raise subprocess.TimeoutExpired(command, idle_timeout * 2)
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
elif action == 'unresponsive':
|
||||
raise subprocess.TimeoutExpired(command, idle_timeout * 2)
|
||||
@@ -287,6 +323,15 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
return subprocess.CompletedProcess(command, process.returncode, _decode(output[0]), _decode(output[1]))
|
||||
except Exception as error:
|
||||
if process is not None:
|
||||
if (not watch.safe_stop and not cooperative_abort and force_control is not None
|
||||
and not durable_force_accepted):
|
||||
from .stop_control import wait_for_resolution
|
||||
try:
|
||||
wait_for_resolution(force_control, root, error)
|
||||
except WorkerMonitorError:
|
||||
if not force_event.is_set():
|
||||
raise
|
||||
durable_force_accepted = True
|
||||
failures = owned.stop_workers(process)
|
||||
process.wait(timeout=10)
|
||||
for thread in threads:
|
||||
|
||||
Reference in new issue
Block a user