fix: bound read cancellation and forward safe project pause
This commit is contained in:
1 parent
75ee8bd33a
commit
a8da30aad2
5 files changed
+265
-17
No files matched your search
@@ -91,6 +91,11 @@ class ProjectSessionWorker:
|
||||
raise WorkerMonitorError('project session exited before authorized closing')
|
||||
self._failure_delivered = True
|
||||
return self._result
|
||||
stop_control = getattr(self.runtime, 'stop_event', None)
|
||||
if stop_control is not None and stop_control.is_set() and not self._abort.is_set():
|
||||
# A step cannot return to the queue's stop check before its checkpoint.
|
||||
# The owned monitor still decides whether the current stage can stop.
|
||||
self._abort.set()
|
||||
try:
|
||||
fields = (self.root / 'project-session-result.tsv').read_text(encoding='utf-8-sig').strip().split('\t')
|
||||
except (FileNotFoundError, PermissionError):
|
||||
|
||||
@@ -13,11 +13,31 @@ import time
|
||||
import threading
|
||||
from uuid import uuid4
|
||||
|
||||
PROJECT_OPEN_IDLE_TIMEOUT_SECONDS = 45
|
||||
READ_ONLY_CANCEL_GRACE_SECONDS = 5
|
||||
READ_ONLY_IDLE_TIMEOUT_SECONDS = 45
|
||||
|
||||
|
||||
class WorkerMonitorError(subprocess.SubprocessError):
|
||||
pass
|
||||
|
||||
|
||||
class WorkerMonitorCancelled(WorkerMonitorError):
|
||||
"""An owned worker was stopped at an admitted cancellation boundary."""
|
||||
def __init__(self, message, *, stage):
|
||||
super().__init__(message)
|
||||
self.stage = stage
|
||||
self.cleanup_notes = ()
|
||||
|
||||
|
||||
class WorkerMonitorSafeTimeout(WorkerMonitorError):
|
||||
"""A project-open stage timed out before any possible mutation."""
|
||||
def __init__(self, message, *, stage):
|
||||
super().__init__(message)
|
||||
self.stage = stage
|
||||
self.cleanup_notes = ()
|
||||
|
||||
|
||||
_PROGRESS_FAILURE_LOGGED: dict[str, float] = {}
|
||||
|
||||
|
||||
@@ -103,10 +123,13 @@ class ProgressWatch:
|
||||
|
||||
def action(self, now: float) -> str | None:
|
||||
idle = now - self.last_progress
|
||||
if not self.stop_requested and idle >= self.idle_timeout:
|
||||
idle_timeout = self.idle_timeout
|
||||
if self.stage == 'open_project' and self.safe_stop:
|
||||
idle_timeout = min(idle_timeout, PROJECT_OPEN_IDLE_TIMEOUT_SECONDS)
|
||||
if not self.stop_requested and idle >= idle_timeout:
|
||||
self.stop_requested = True
|
||||
return 'request_stop'
|
||||
if self.stop_requested and idle >= self.idle_timeout * 2:
|
||||
if self.stop_requested and idle >= idle_timeout * 2:
|
||||
if not self.safe_stop:
|
||||
if not self.waiting_for_safe_completion:
|
||||
self.waiting_for_safe_completion = True
|
||||
@@ -215,12 +238,18 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
progress_path = root / 'worker-progress.json'
|
||||
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())
|
||||
watch = ProgressWatch(token, job_id,
|
||||
min(idle_timeout, READ_ONLY_IDLE_TIMEOUT_SECONDS) if cooperative_abort else 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
|
||||
read_cancel_started = None
|
||||
read_idle_stop_started = None
|
||||
stop_write_pending = False
|
||||
stop_warning = ''
|
||||
threads = []
|
||||
messages = queue.Queue(maxsize=1024)
|
||||
stop_readers = threading.Event()
|
||||
@@ -247,6 +276,25 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
elif len(output[channel]) < 1024 * 1024:
|
||||
output[channel].extend(line[:1024 * 1024 - len(output[channel])])
|
||||
|
||||
def request_stop():
|
||||
nonlocal stop_write_pending, stop_warning
|
||||
try:
|
||||
_atomic_text(stop, token)
|
||||
except OSError as error:
|
||||
stop_write_pending = True
|
||||
warning = '暂停请求尚未写入,保留进程并重试:' + str(error)
|
||||
if warning != stop_warning:
|
||||
import logging
|
||||
logging.getLogger(__name__).warning('%s', warning)
|
||||
stop_warning = warning
|
||||
if force_control is not None:
|
||||
force_control.control_error = warning
|
||||
else:
|
||||
stop_write_pending = False
|
||||
if force_control is not None and force_control.control_error == stop_warning:
|
||||
force_control.control_error = ''
|
||||
stop_warning = ''
|
||||
|
||||
try:
|
||||
if process_factory is None:
|
||||
process = subprocess.Popen((*command, token), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
@@ -276,20 +324,25 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
else:
|
||||
durable_force_accepted = True
|
||||
raise WorkerMonitorError('user forced stop; execution requires reconciliation')
|
||||
if stop_write_pending:
|
||||
request_stop()
|
||||
if abort_event is not None and abort_event.is_set():
|
||||
if not cooperative_abort and watch.safe_stop:
|
||||
raise WorkerMonitorError('project session supervisor requested worker cleanup')
|
||||
if cooperative_abort and read_cancel_started is None:
|
||||
read_cancel_started = time.monotonic()
|
||||
if (read_cancel_started is not None and
|
||||
time.monotonic() - read_cancel_started >= READ_ONLY_CANCEL_GRACE_SECONDS):
|
||||
raise WorkerMonitorCancelled(
|
||||
'read-only worker did not acknowledge cancellation within its grace period', stage=watch.stage)
|
||||
if not watch.stop_requested:
|
||||
# Read-only callers request the VBS safe boundary first.
|
||||
# The existing idle watchdog still bounds a stalled COM call.
|
||||
# Request a worker boundary; queued unsafe progress may not
|
||||
# have reached watch yet, so ordinary pause cannot kill here.
|
||||
watch.stop_requested = True
|
||||
watch.last_progress = time.monotonic()
|
||||
try:
|
||||
_atomic_text(stop, token)
|
||||
except OSError:
|
||||
if watch.safe_stop:
|
||||
raise
|
||||
request_stop()
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
if (read_idle_stop_started is not None and time.monotonic() - read_idle_stop_started >=
|
||||
min(READ_ONLY_CANCEL_GRACE_SECONDS, watch.idle_timeout)):
|
||||
raise subprocess.TimeoutExpired(command, watch.idle_timeout)
|
||||
try:
|
||||
receive(*messages.get(timeout=min(0.1, idle_timeout / 10)))
|
||||
for pending in range(128):
|
||||
@@ -309,11 +362,9 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
break
|
||||
action = watch.action(time.monotonic())
|
||||
if action == 'request_stop':
|
||||
try:
|
||||
_atomic_text(stop, token)
|
||||
except OSError:
|
||||
if watch.safe_stop:
|
||||
raise
|
||||
if cooperative_abort:
|
||||
read_idle_stop_started = time.monotonic()
|
||||
request_stop()
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
elif action == 'await_safe_completion':
|
||||
if cooperative_abort:
|
||||
@@ -322,6 +373,13 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
raise subprocess.TimeoutExpired(command, idle_timeout * 2)
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
elif action == 'unresponsive':
|
||||
if stop_write_pending and not cooperative_abort:
|
||||
watch.waiting_for_safe_completion = True
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
continue
|
||||
if watch.safe_stop and watch.stage == 'open_project':
|
||||
raise WorkerMonitorSafeTimeout('project open made no progress; safe stop was requested',
|
||||
stage=watch.stage)
|
||||
raise subprocess.TimeoutExpired(command, idle_timeout * 2)
|
||||
drain_deadline = time.monotonic() + 5
|
||||
while (any(thread.is_alive() for thread in threads) or not messages.empty()) and time.monotonic() < drain_deadline:
|
||||
@@ -351,6 +409,8 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
_atomic_text(progress_path, json.dumps(diagnostic, ensure_ascii=False))
|
||||
except OSError:
|
||||
pass
|
||||
if isinstance(error, (WorkerMonitorCancelled, WorkerMonitorSafeTimeout)) and not failures:
|
||||
raise error
|
||||
if isinstance(error, subprocess.TimeoutExpired):
|
||||
raise
|
||||
raise WorkerMonitorError(f'Worker monitoring failed after launch; execution requires reconciliation: {error}') from error
|
||||
|
||||
Reference in new issue
Block a user