fix: preserve CAD shutdown failures and record desktop cleanup evidence

This commit is contained in:
阿白叔 committed 2026-10-16 10:48:19 +08:00
1 parent 660bbe3736
commit f3d2570e48
5 files changed
+131 -14

No files matched your search

@@ -139,8 +139,16 @@ class IsolatedCadSession:
def __exit__(self, error_type, error, traceback):
closing_started = time.monotonic()
cleanup_error = None
cleanup_errors = []
exit_codes = {}
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,
shutdown_seconds=time.monotonic() - closing_started,
desktop_cleanup=getattr(self.desktop, 'cleanup_record', None), **exit_codes)
try:
self._record(state='closing')
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:
@@ -149,30 +157,36 @@ class IsolatedCadSession:
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:
if closing.wait(timeout=20):
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'))
if self.cad.wait(timeout=15) != 0:
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()
except Exception as failure:
cleanup_error = failure
self._uncertain(str(failure))
remember('orderly_shutdown', failure)
finally:
try:
self.desktop.close()
self._record(state='released', clean=error is None and cleanup_error is None,
shutdown_seconds=time.monotonic() - closing_started)
shutdown_seconds=time.monotonic() - closing_started,
desktop_cleanup=getattr(self.desktop, 'cleanup_record', None), **exit_codes)
except Exception as failure:
self._uncertain(str(failure))
cleanup_error = failure
remember('desktop_release', failure)
if cleanup_error is not None:
raise WorkerMonitorError('private CAD cleanup requires reconciliation: ' + str(cleanup_error)) from cleanup_error
message = '; '.join(f"{item['stage']}: {item['message']}" for item in cleanup_errors)
raise WorkerMonitorError('private CAD cleanup requires reconciliation: ' + message) from cleanup_error
def _uncertain(self, message):
def _uncertain(self, message, **details):
from .quick_run import _write_uncertain_flag
_write_uncertain_flag(self.root / 'uncertain.flag', 'private_desktop: ' + message)
self._record(state='uncertain', error=message)
self._record(state='uncertain', error=message, **details)
def run_isolated_process(command, timeout, *, abort_event=None, cooperative_abort=False):
@@ -15,6 +15,7 @@ import os
from pathlib import Path
import subprocess
import time
from threading import get_native_id
from typing import Mapping, Sequence
from .errors import TaskCenterError
@@ -46,14 +47,26 @@ class _Win32Api:
return self.service.CreateDesktop(name, 0, self.con.GENERIC_ALL, None)
def confirm_desktop_released(self, name: str):
deadline = time.monotonic() + 2.0
started = time.monotonic()
deadline = started + 2.0
self.desktop_release_check = {'desktop': name, 'released': None,
'elapsed_seconds': 0.0, 'budget_seconds': 2.0}
while True:
# EnumDesktops avoids reopening/closing a handle which Windows may
# share with another desktop handle held by this process.
names = self.service.GetProcessWindowStation().EnumDesktops()
if name.casefold() not in {value.casefold() for value in names}:
present = name.casefold() in {value.casefold() for value in names}
self.desktop_release_check = {'desktop': name, 'released': not present,
'elapsed_seconds': time.monotonic() - started, 'budget_seconds': 2.0,
'caller_pid': os.getpid(), 'caller_thread_id': get_native_id()}
if not present:
return
if time.monotonic() >= deadline:
try:
from .cad_identity import current_desktop_name
self.desktop_release_check['caller_desktop'] = current_desktop_name()
except Exception as error:
self.desktop_release_check['caller_desktop_error'] = str(error)
raise TaskCenterError('private_desktop_cleanup', 'owned private desktop still exists after cleanup')
time.sleep(0.05)
@@ -248,6 +261,7 @@ class _Win32Process:
self.job_assigned = False
self.returncode = None
self.stdout = self.stderr = None
self.cleanup_record = {'pid': self.pid}
def poll(self):
if self.returncode is not None or self.handle is None:
@@ -321,9 +335,12 @@ class _Win32Process:
# A completed root can leave grandchildren holding the desktop.
self._remember_descendants()
self._job_api.TerminateJobObject(self.job, 1)
while self._job_api.QueryInformationJobObject(
self.job, self._job_api.JobObjectBasicAccountingInformation,
)['ActiveProcesses']:
while True:
active = self._job_api.QueryInformationJobObject(
self.job, self._job_api.JobObjectBasicAccountingInformation)['ActiveProcesses']
self.cleanup_record['job_active_processes'] = active
if not active:
break
if time.monotonic() >= deadline:
raise TimeoutError('owned job descendants did not exit within 5 seconds')
time.sleep(0.01)
@@ -363,6 +380,10 @@ class _Win32Process:
stream.close()
except Exception as error:
errors.append(error)
self.cleanup_record.update(exit_code=self.returncode, descendant_pids=sorted(self._descendant_pids),
unconfirmed_descendant_handles=len(self._descendant_handles),
process_handle_closed=self.handle is None, job_handle_closed=self.job is None,
errors=[str(error) for error in errors])
_raise_cleanup_errors(errors)
@@ -375,6 +396,7 @@ class PrivateDesktop:
self._handle = None
self._processes: list[subprocess.Popen[str]] = []
self._api = api
self.cleanup_record = None
def __enter__(self) -> "PrivateDesktop":
if not self.enabled:
@@ -415,6 +437,7 @@ class PrivateDesktop:
def close(self) -> None:
errors, remaining = [], []
self.cleanup_record = {'desktop': self.name, 'processes': []}
for process in reversed(self._processes):
process_errors = _stop_and_wait(process)
errors.extend(process_errors)
@@ -424,6 +447,8 @@ class PrivateDesktop:
except Exception as error:
errors.append(error)
failed = True
self.cleanup_record['processes'].append(getattr(process, 'cleanup_record', {
'pid': getattr(process, 'pid', None), 'exit_code': getattr(process, 'returncode', None)}))
if failed:
remaining.append(process)
self._processes = list(reversed(remaining))
@@ -446,4 +471,7 @@ class PrivateDesktop:
confirm(self.name)
except Exception as error:
errors.append(error)
self.cleanup_record.update(desktop_handle_closed=self._handle is None,
desktop_confirmation=getattr(self._api, 'desktop_release_check', None),
errors=[str(error) for error in errors])
_raise_cleanup_errors(errors)