fix: confirm safe worker tree exit within the cleanup budget

This commit is contained in:
阿白叔 committed 2026-11-08 19:37:59 +08:00
1 parent c3a6e59420
commit f1cd6bf974
2 files changed
+111 -1

No files matched your search

@@ -301,7 +301,9 @@ class _OwnedWorkers:
else:
failures.append(f'preserved_non_worker pid={process_id}')
except Exception as error:
failures.append(f'child_cleanup pid={process_id} error={error}')
code = getattr(error, 'winerror', error.args[0] if error.args else None)
if handle is not None or code != 87: # OpenProcess may observe an already exited PID.
failures.append(f'child_cleanup pid={process_id} error={error}')
finally:
if handle is not None:
handle.Close()
@@ -512,10 +514,18 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
if not force_event.is_set():
raise
durable_force_accepted = True
cleanup_deadline = time.monotonic() + 10
failures = owned.stop_workers(process)
process.wait(timeout=10)
for thread in threads:
thread.join(2)
if (isinstance(error, WorkerMonitorSafeTimeout) and not watch.unsafe_seen
and all(note.startswith('preserved_non_worker ') for note in failures)):
# Root exit and Job accounting need not become observable in
# the same tick. Confirm naturally exiting descendants within
# the existing worker-cleanup budget; never force unknown ones.
while not _worker_tree_exited(process, owned) and time.monotonic() < cleanup_deadline:
time.sleep(.01)
diagnostic = watch.snapshot() | {'monitor_error': str(error), 'worker_cleanup_notes': failures}
try:
_atomic_text(progress_path, json.dumps(diagnostic, ensure_ascii=False))
@@ -0,0 +1,100 @@
"""An exited root is insufficient; use the existing cleanup budget for its tree."""
import io
import os
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import worker_monitor
@pytest.mark.parametrize('descendants_exit', [True, False])
def test_safe_timeout_waits_for_positive_tree_exit_without_extending_cleanup_budget(tmp_path, monkeypatch, descendants_exit):
clock = SimpleNamespace(now=0.0)
def monotonic():
clock.now += .01
return clock.now
monkeypatch.setattr(worker_monitor, 'time', SimpleNamespace(monotonic=monotonic,
sleep=lambda delay: setattr(clock, 'now', clock.now + delay)))
process = SimpleNamespace(pid=123, returncode=None, stdout=io.BytesIO(), stderr=io.BytesIO(), closed=False)
process.poll = lambda: process.returncode
process.close = lambda: setattr(process, 'closed', True)
process.wait = lambda timeout: process.returncode
class Owned:
def __init__(self, *_args):
self.closed, self.observations, self.cleanup_started, self.exited = False, 0, None, False
owners.append(self)
def tree_exited(self):
self.observations += 1
return self.exited or descendants_exit and self.observations >= 4
def stop_workers(self, _process):
self.cleanup_started = clock.now
process.returncode = 1
return ['preserved_non_worker pid=456']
def close(self):
self.closed = True
class StalledOpen(worker_monitor.ProgressWatch):
def __init__(self, *args):
super().__init__(*args)
self.stage = 'open_project'
def action(self, _now):
return 'unresponsive'
owners = []
monkeypatch.setattr(worker_monitor, '_OwnedWorkers', Owned)
monkeypatch.setattr(worker_monitor, 'ProgressWatch', StalledOpen)
try:
expected = worker_monitor.WorkerMonitorSafeTimeout if descendants_exit else worker_monitor.WorkerMonitorError
with pytest.raises(expected) as caught:
worker_monitor.run_monitored_process(('worker', '', '', str(tmp_path), 'python', 'job'), 1,
process_factory=lambda *_a, **_k: process)
if descendants_exit:
assert caught.value.prewrite_cleanup_confirmed
assert owners[0].observations >= 4 and owners[0].closed and process.closed
else:
assert not getattr(caught.value, 'prewrite_cleanup_confirmed', False)
assert any(entry['process'] is process for entry in worker_monitor.RETAINED_WORKERS.values())
assert not owners[0].closed and not process.closed
assert clock.now - owners[0].cleanup_started <= 10.2
finally:
owners[0].exited = True
worker_monitor.cleanup_retained_workers(tmp_path)
@pytest.mark.skipif(os.name != 'nt', reason='Win32 vanished PID observation')
def test_child_that_exits_during_job_enumeration_is_not_a_cleanup_failure(monkeypatch):
import pywintypes
import win32api
import win32job
owned = worker_monitor._OwnedWorkers.__new__(worker_monitor._OwnedWorkers)
owned.job, owned.allowed = object(), set()
monkeypatch.setattr(win32job, 'QueryInformationJobObject', lambda *_: (1, 2))
def vanished(*_args):
raise pywintypes.error(87, 'OpenProcess', 'process already exited')
monkeypatch.setattr(win32api, 'OpenProcess', vanished)
process = SimpleNamespace(pid=1, poll=lambda: 0)
assert owned.stop_workers(process) == []
@pytest.mark.skipif(os.name != 'nt', reason='Win32 post-open cleanup error')
def test_error_87_after_opening_child_remains_a_cleanup_failure(monkeypatch):
import ctypes
import win32api
import win32job
owned = worker_monitor._OwnedWorkers.__new__(worker_monitor._OwnedWorkers)
owned.job, owned.allowed = object(), set()
monkeypatch.setattr(win32job, 'QueryInformationJobObject', lambda *_: (1, 2))
closed = []
class Handle:
def __int__(self):
return 2
def Close(self):
closed.append(True)
monkeypatch.setattr(win32api, 'OpenProcess', lambda *_: Handle())
def failed_image_query(*_args):
ctypes.set_last_error(87)
return 0
monkeypatch.setattr(worker_monitor.ctypes, 'WinDLL', lambda *_a, **_k:
SimpleNamespace(QueryFullProcessImageNameW=failed_image_query))
notes = owned.stop_workers(SimpleNamespace(pid=1, poll=lambda: 0))
assert len(notes) == 1 and notes[0].startswith('child_cleanup pid=2')
assert closed == [True]