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
@@ -175,13 +175,13 @@ Set QP_App=FakeApp
|
||||
FakeApp.ProjectPath=Target
|
||||
QP_CurrentJobId="batch-job": QP_ExpectedJobId="batch-job"
|
||||
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"command.tsv"),"task_id" & vbTab & "job_id" & vbTab & "project_path" & vbTab & "old_part" & vbTab & "new_part" & vbTab & "value_mode" & vbCrLf & "task" & vbTab & "batch-job" & vbTab & Target & vbTab & "OLD" & vbTab & "NEW" & vbTab & "preserve" & vbCrLf
|
||||
QP_BatchMode=True: QP_OwnedProject=True
|
||||
QP_BatchMode=True: QP_OwnedProject=True: QP_OwnedProjectPath=Target
|
||||
QPWriteStatus QP_Root,QP_CurrentJobId,"no_match","","not found"
|
||||
Require Not QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root,"status.tsv")),"published success before close"
|
||||
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),QP_CurrentJobId)="no_match","pending no-match not visible to worker"
|
||||
QPFinishBatchItem
|
||||
Require FakeApp.CloseCount=1,"project not closed exactly once"
|
||||
Require FakeApp.SaveCount=1,"sheet not closed with saving allowed"
|
||||
Require FakeApp.SaveCount=0,"no-match must close without saving"
|
||||
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"batch_closed")>0,"no completion proof"
|
||||
''')
|
||||
|
||||
@@ -368,8 +368,8 @@ Require FakeApp.ProjectPath = "", "discovery left the project open"
|
||||
Require FakeApp.Documents.OpenCount = 0, "discovery opened a page"
|
||||
Dim Manifest
|
||||
Manifest = QPReadUtf8(QP_Fso.BuildPath(QP_Root, "sheets.tsv"))
|
||||
Require InStr(Manifest, Target & vbTab & "Main" & vbTab & "1") > 0, "sheet one missing"
|
||||
Require InStr(Manifest, Target & vbTab & "Main" & vbTab & "2") > 0, "sheet two missing"
|
||||
Require InStr(Manifest, LCase(Target) & vbTab & "Main" & vbTab & "1") > 0, "sheet one missing"
|
||||
Require InStr(Manifest, LCase(Target) & vbTab & "Main" & vbTab & "2") > 0, "sheet two missing"
|
||||
''')
|
||||
|
||||
|
||||
|
||||
@@ -253,6 +253,31 @@ End Sub''', routines)
|
||||
'Sub QPVerifyUntouched(ByRef Records)\n' + injection)
|
||||
|
||||
|
||||
def test_save_then_project_close_refusal_retains_save_boundary(tmp_path):
|
||||
run_vbs(tmp_path, 'part_number', '''
|
||||
Dim FullChecks
|
||||
FullChecks=0
|
||||
Command.Add "project_path",QPProjectPath()
|
||||
QP_BatchMode=True: QP_SessionMode=True
|
||||
QP_SessionToken=String(32,"b")
|
||||
QP_OwnedProject=True: QP_OwnedProjectPath=QPProjectPath()
|
||||
QPRestoreAfterOperatorReplace Command,SnapshotPath
|
||||
QP_App.RefuseClose=True
|
||||
On Error Resume Next
|
||||
QPFinishBatchItem
|
||||
Failure=Err.Number
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
Require Failure<>0,"refused close must stop the operation"
|
||||
Require QP_BatchSaveCommitted,"returned save was lost when project close failed"
|
||||
QP_App.RefuseClose=False
|
||||
QPDiscardFailedBatchProject CloseError
|
||||
Require Len(CloseError)>0,"uncertain save must not discard the open project"
|
||||
Require Len(QPProjectPath())>0,"failed saved project was silently discarded"
|
||||
Require Not QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root,"project-session-result.tsv")),"failure published success"
|
||||
''', routines_transform=_batch_readback_fixture)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ['', 'before_save', 'after_reopen'])
|
||||
def test_owned_batch_checks_full_state_at_save_and_disk_boundaries(tmp_path, fault):
|
||||
run_vbs(tmp_path, 'part_number', '''
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import weakref
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from threading import Timer
|
||||
from threading import Thread
|
||||
from types import SimpleNamespace
|
||||
from traceback import extract_tb
|
||||
|
||||
@@ -194,6 +196,121 @@ def test_clean_release_records_helper_and_cad_exit_codes(monkeypatch, tmp_path):
|
||||
assert record['cleanup_errors'] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('persistent', [False, True])
|
||||
def test_closing_journal_failure_still_quits_and_reports_diagnostic_error(monkeypatch, tmp_path, persistent):
|
||||
events, cad = fake_desktop(monkeypatch, tmp_path)
|
||||
session = runtime.IsolatedCadSession(tmp_path)
|
||||
session.__enter__()
|
||||
record = session._record
|
||||
def failing_record(**values):
|
||||
if persistent or values.get('state') == 'closing':
|
||||
raise PermissionError('closing journal locked')
|
||||
record(**values)
|
||||
session._record = failing_record
|
||||
with pytest.raises(WorkerMonitorError, match='closing journal locked'):
|
||||
session.__exit__(None, None, None)
|
||||
assert 'quit' in events and cad.returncode == 0
|
||||
assert session.record['orderly_shutdown'] is True
|
||||
assert session.record['clean'] is False
|
||||
assert session.record['diagnostic_errors'][0]['stage'] == 'closing_record'
|
||||
assert (tmp_path / 'uncertain.flag').exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('helper_failure', ['refused', 'timeout'])
|
||||
def test_interactive_quit_failure_retains_cad_and_helper_until_explicit_force(monkeypatch, tmp_path, helper_failure):
|
||||
from dx_productivity.trial_task_center.stop_control import StopControl
|
||||
from dx_productivity.trial_task_center import worker_monitor
|
||||
events, cad = fake_desktop(monkeypatch, tmp_path, quit_code=1, cad_exit_code=None)
|
||||
control = StopControl()
|
||||
session = runtime.IsolatedCadSession(tmp_path, stop_control=control)
|
||||
session.__enter__()
|
||||
start = session.desktop.start_process
|
||||
def start_quit(command, **options):
|
||||
helper = start(command, **options)
|
||||
if command[0] == 'quit':
|
||||
if helper_failure == 'timeout':
|
||||
helper.wait = lambda timeout: (_ for _ in ()).throw(subprocess.TimeoutExpired('quit', timeout))
|
||||
helper.poll = lambda: None
|
||||
helper.close = lambda: events.append('close-quit-helper')
|
||||
return helper
|
||||
session.desktop.start_process = start_quit
|
||||
waiting, finished = Event(), Event()
|
||||
publish = worker_monitor._publish_progress
|
||||
def observe_wait(path, snapshot):
|
||||
publish(path, snapshot)
|
||||
if snapshot.get('stage') == 'awaiting_reconciliation':
|
||||
waiting.set()
|
||||
monkeypatch.setattr(worker_monitor, '_publish_progress', observe_wait)
|
||||
failures = []
|
||||
def close_session():
|
||||
try:
|
||||
session.__exit__(None, None, None)
|
||||
except Exception as failure:
|
||||
failures.append(failure)
|
||||
finally:
|
||||
finished.set()
|
||||
thread = Thread(target=close_session)
|
||||
thread.start()
|
||||
try:
|
||||
assert waiting.wait(1), 'failed Quit must enter protected waiting before resource release'
|
||||
control.set()
|
||||
assert not finished.wait(.05)
|
||||
assert cad.poll() is None
|
||||
assert 'close-quit-helper' not in events
|
||||
assert not any(isinstance(event, tuple) and event[0] == 'release' for event in events)
|
||||
assert (tmp_path / 'uncertain.flag').exists()
|
||||
control.request_force()
|
||||
assert finished.wait(2)
|
||||
assert 'close-quit-helper' in events and ('release', True) in events
|
||||
assert cad.poll() == 1
|
||||
assert isinstance(failures[0], WorkerMonitorError)
|
||||
assert 'forced' in str(failures[0])
|
||||
assert session.record['orderly_shutdown'] is False and session.record['clean'] is False
|
||||
finally:
|
||||
control.request_force()
|
||||
thread.join(3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['cad_exited', 'diagnostic'])
|
||||
def test_interactive_exit_does_not_hold_completed_cad_for_resolution(monkeypatch, tmp_path, failure):
|
||||
from dx_productivity.trial_task_center.stop_control import StopControl
|
||||
from dx_productivity.trial_task_center import stop_control
|
||||
events, _cad = fake_desktop(monkeypatch, tmp_path, quit_code=1 if failure == 'cad_exited' else 0)
|
||||
session = runtime.IsolatedCadSession(tmp_path, stop_control=StopControl())
|
||||
session.__enter__()
|
||||
monkeypatch.setattr(stop_control, 'wait_for_resolution', lambda *_args: pytest.fail('exited CAD must not wait'))
|
||||
if failure == 'diagnostic':
|
||||
record = session._record
|
||||
def failed_journal(**values):
|
||||
if values.get('state') == 'closing':
|
||||
raise PermissionError('closing diagnostic unavailable')
|
||||
record(**values)
|
||||
session._record = failed_journal
|
||||
with pytest.raises(WorkerMonitorError):
|
||||
session.__exit__(None, None, None)
|
||||
assert ('release', True) in events
|
||||
|
||||
|
||||
def test_forced_descendant_cleanup_is_not_reported_as_clean_orderly_shutdown(monkeypatch, tmp_path):
|
||||
fake_desktop(monkeypatch, tmp_path)
|
||||
session = runtime.IsolatedCadSession(tmp_path)
|
||||
session.__enter__()
|
||||
release = session.desktop.close
|
||||
def forced_release():
|
||||
release()
|
||||
session.desktop.cleanup_record = {'processes': [{'pid': 123, 'forced_termination': True,
|
||||
'forced_root_termination': False, 'termination_reason': 'descendant_grace_expired',
|
||||
'forced_descendant_pids': [456]}]}
|
||||
session.desktop.close = forced_release
|
||||
with pytest.raises(WorkerMonitorError, match='forced'):
|
||||
session.__exit__(None, None, None)
|
||||
record = json.loads((tmp_path / 'private-desktop.json').read_text())
|
||||
assert record['clean'] is False and record['forced_termination'] is True
|
||||
assert record['orderly_shutdown'] is True
|
||||
assert record['forced_descendant_pids'] == [456]
|
||||
assert record['termination_reason'] == 'descendant_grace_expired'
|
||||
|
||||
|
||||
def test_exit_code_diagnostics_do_not_interrupt_the_normal_cad_wait(monkeypatch, tmp_path):
|
||||
_, cad = fake_desktop(monkeypatch, tmp_path)
|
||||
waited = []
|
||||
|
||||
@@ -367,6 +367,99 @@ def test_descendant_handles_are_owned_before_terminating_the_job():
|
||||
assert ('close', 'child') in events
|
||||
|
||||
|
||||
@pytest.mark.parametrize('child_exit_after', [0.5, None])
|
||||
def test_completed_root_gives_owned_descendants_bounded_natural_exit_grace(monkeypatch, child_exit_after):
|
||||
from dx_productivity.trial_task_center import isolated_desktop as module
|
||||
api, events, state, *_ = native_api()
|
||||
clock = [0.0]
|
||||
monkeypatch.setattr(module.time, 'monotonic', lambda: clock[0])
|
||||
monkeypatch.setattr(module.time, 'sleep', lambda seconds: clock.__setitem__(0, clock[0] + seconds))
|
||||
state['running'] = False
|
||||
child = Handle('child', events)
|
||||
child_running = lambda: not any(event[0] == 'terminate' for event in events) and (
|
||||
child_exit_after is None or clock[0] < child_exit_after)
|
||||
api.job.JobObjectBasicProcessIdList = 3
|
||||
api.job.QueryInformationJobObject = lambda job, kind: (
|
||||
{'BasicLimitInformation': {'LimitFlags': 0}} if kind == 9 else
|
||||
([43] if child_running() else []) if kind == 3 else {'ActiveProcesses': int(child_running())})
|
||||
api.open_process = lambda *_args: child
|
||||
root_wait = api.event.WaitForSingleObject
|
||||
api.event.WaitForSingleObject = lambda handle, timeout: (
|
||||
258 if child_running() else 0) if handle is child else root_wait(handle, timeout)
|
||||
process = api.create_process(('python.exe',), 'winsta0\\private', None, None)
|
||||
process.close()
|
||||
assert child.closed
|
||||
if child_exit_after is not None:
|
||||
assert child_exit_after <= clock[0] < 2
|
||||
assert ('terminate',) not in events
|
||||
assert process.cleanup_record['forced_termination'] is False
|
||||
assert process.cleanup_record['forced_descendant_pids'] == []
|
||||
else:
|
||||
assert 2 <= clock[0] < 2.1
|
||||
assert ('terminate',) in events
|
||||
assert process.cleanup_record['forced_termination'] is True
|
||||
assert process.cleanup_record['forced_root_termination'] is False
|
||||
assert process.cleanup_record['forced_descendant_pids'] == [43]
|
||||
assert process.cleanup_record['termination_reason'] == 'descendant_grace_expired'
|
||||
|
||||
|
||||
def test_completed_root_without_descendants_has_no_grace_delay(monkeypatch):
|
||||
from dx_productivity.trial_task_center import isolated_desktop as module
|
||||
api, events, state, *_ = native_api()
|
||||
state['running'] = False
|
||||
monkeypatch.setattr(module.time, 'sleep', lambda seconds: pytest.fail('empty job must not wait'))
|
||||
process = api.create_process(('python.exe',), 'winsta0\\private', None, None)
|
||||
process.close()
|
||||
assert ('terminate',) not in events
|
||||
assert process.cleanup_record['forced_termination'] is False
|
||||
|
||||
|
||||
def test_active_root_cleanup_is_forced_without_descendant_grace(monkeypatch):
|
||||
from dx_productivity.trial_task_center import isolated_desktop as module
|
||||
api, events, *_ = native_api()
|
||||
monkeypatch.setattr(module.time, 'sleep', lambda seconds: pytest.fail('active root must be bounded immediately'))
|
||||
process = api.create_process(('python.exe',), 'winsta0\\private', None, None)
|
||||
process.close()
|
||||
assert process.cleanup_record['forced_termination'] is True
|
||||
assert process.cleanup_record['forced_root_termination'] is True
|
||||
assert process.cleanup_record['termination_reason'] == 'root_process_active'
|
||||
|
||||
|
||||
def test_native_poll_error_still_terminates_owned_root_and_records_force():
|
||||
api, events, state, *_ = native_api()
|
||||
wait = api.event.WaitForSingleObject
|
||||
def failing_poll(handle, timeout):
|
||||
if timeout == 0 and state['running']:
|
||||
raise OSError('native poll failed')
|
||||
return wait(handle, timeout)
|
||||
api.event.WaitForSingleObject = failing_poll
|
||||
process = api.create_process(('python.exe',), 'winsta0\\private', None, None)
|
||||
with pytest.raises(TaskCenterError, match='native poll failed'):
|
||||
process.close()
|
||||
assert state['running'] is False
|
||||
assert process.cleanup_record['forced_root_termination'] is True
|
||||
|
||||
|
||||
def test_failed_job_cleanup_retains_ownership_until_retry(monkeypatch):
|
||||
from dx_productivity.trial_task_center import isolated_desktop as module
|
||||
api, events, state, root, job = native_api()
|
||||
clock = [0.0]
|
||||
monkeypatch.setattr(module.time, 'monotonic', lambda: clock[0])
|
||||
monkeypatch.setattr(module.time, 'sleep', lambda seconds: clock.__setitem__(0, clock[0] + seconds))
|
||||
api.job.TerminateJobObject = lambda *_args: (_ for _ in ()).throw(OSError('job termination failed'))
|
||||
query = api.job.QueryInformationJobObject
|
||||
child_running = [True]
|
||||
api.job.QueryInformationJobObject = lambda handle, kind: (
|
||||
{'ActiveProcesses': int(state['running']) + int(child_running[0])} if kind == 1 else query(handle, kind))
|
||||
process = api.create_process(('python.exe',), 'winsta0\\private', None, None)
|
||||
with pytest.raises(TaskCenterError, match='descendants did not exit'):
|
||||
process.close()
|
||||
assert not job.closed and process.job is job
|
||||
child_running[0] = False
|
||||
process.close()
|
||||
assert job.closed
|
||||
|
||||
|
||||
@pytest.mark.parametrize('error_code', [87, 5])
|
||||
def test_native_descendant_open_error_only_ignores_already_exited_process(error_code):
|
||||
# pywintypes.error derives directly from Exception, rather than OSError.
|
||||
@@ -391,6 +484,30 @@ def test_native_descendant_open_error_only_ignores_already_exited_process(error_
|
||||
assert caught.value is error
|
||||
|
||||
|
||||
def test_forced_job_preserves_partial_current_descendant_snapshot_after_open_failure():
|
||||
api, events, state, *_ = native_api()
|
||||
api.job.JobObjectBasicProcessIdList = 3
|
||||
query = api.job.QueryInformationJobObject
|
||||
snapshot = [45]
|
||||
api.job.QueryInformationJobObject = lambda job, kind: list(snapshot) if kind == 3 else query(job, kind)
|
||||
def open_child(_access, _inherit, pid):
|
||||
if pid == 44:
|
||||
raise OSError(5, 'child access denied')
|
||||
return Handle('child-' + str(pid), events)
|
||||
api.open_process = open_child
|
||||
process = api.create_process(('python.exe',), 'winsta0\\private', None, None)
|
||||
# PID 45 was observed earlier but is no longer part of the active Job.
|
||||
process._remember_descendants()
|
||||
snapshot[:] = [42, 43, 44]
|
||||
with pytest.raises(TaskCenterError, match='child access denied'):
|
||||
process.close()
|
||||
assert state['running'] is False
|
||||
assert process.cleanup_record['forced_termination'] is True
|
||||
assert process.cleanup_record['forced_descendant_pids'] == [43]
|
||||
assert process.cleanup_record['descendant_pids'] == [43, 45]
|
||||
assert process.cleanup_record['job_handle_closed'] is True
|
||||
|
||||
|
||||
def test_unconfirmed_descendant_exit_retains_handle_for_cleanup_retry():
|
||||
api, events, state, *_ = native_api()
|
||||
process = api.create_process(('python.exe',), 'winsta0\\private', None, None)
|
||||
@@ -430,9 +547,37 @@ def test_native_private_job_kills_descendant_after_root_exit(parent_exits):
|
||||
if parent_exits:
|
||||
assert process.wait(timeout=5) == 0
|
||||
assert win32event.WaitForSingleObject(child_handle, 0) == 0
|
||||
assert process.cleanup_record['forced_termination'] is True
|
||||
assert process.cleanup_record['forced_root_termination'] is (not parent_exits)
|
||||
assert child_pid in process.cleanup_record['forced_descendant_pids']
|
||||
with pytest.raises(pywintypes.error):
|
||||
unexpected = win32service.OpenDesktop(name, 0, False, 1)
|
||||
unexpected.CloseDesktop()
|
||||
finally:
|
||||
if child_handle is not None:
|
||||
child_handle.Close()
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='native Windows descendant shutdown grace')
|
||||
def test_native_private_job_allows_descendant_to_finish_after_root_exit():
|
||||
import win32api
|
||||
import win32event
|
||||
import win32process
|
||||
|
||||
child_handle = None
|
||||
try:
|
||||
with PrivateDesktop('dx-test-' + uuid4().hex, enabled=True) as desktop:
|
||||
process = desktop.start_process((sys.executable, '-c',
|
||||
"import subprocess,sys; p=subprocess.Popen([sys.executable,'-c','import time;time.sleep(0.5)']); print(p.pid,flush=True)"),
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
child_pid = int(process.stdout.readline())
|
||||
child_handle = win32api.OpenProcess(0x100000 | 0x1000, False, child_pid)
|
||||
assert process.wait(timeout=5) == 0
|
||||
assert win32event.WaitForSingleObject(child_handle, 0) == 0
|
||||
assert win32process.GetExitCodeProcess(child_handle) == 0
|
||||
assert process.cleanup_record['forced_termination'] is False
|
||||
assert process.cleanup_record['forced_descendant_pids'] == []
|
||||
assert desktop.cleanup_record['desktop_confirmation']['released'] is True
|
||||
finally:
|
||||
if child_handle is not None:
|
||||
child_handle.Close()
|
||||
@@ -0,0 +1,75 @@
|
||||
from threading import Event
|
||||
|
||||
from PySide6.QtGui import QCloseEvent
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
|
||||
from test_ui_remediation import window
|
||||
from test_ui_batch_retry import open_project
|
||||
|
||||
|
||||
def test_pause_and_window_close_never_request_force(window, qtbot, tmp_path):
|
||||
open_project(window, qtbot, tmp_path)
|
||||
window._begin_run(window._task_id)
|
||||
worker = object()
|
||||
window._workers.add(worker)
|
||||
try:
|
||||
event = QCloseEvent()
|
||||
window.closeEvent(event)
|
||||
assert not event.isAccepted()
|
||||
assert window._batch_stop.is_set()
|
||||
assert not window._batch_stop.force_event.is_set()
|
||||
assert not window._closed
|
||||
finally:
|
||||
window._workers.discard(worker)
|
||||
window._close_pending = False
|
||||
window._finish_run()
|
||||
|
||||
|
||||
def test_force_requires_confirmation_and_keeps_window_for_reconciliation(window, qtbot, tmp_path, monkeypatch):
|
||||
open_project(window, qtbot, tmp_path)
|
||||
window._begin_run(window._task_id)
|
||||
control = window._batch_stop
|
||||
try:
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *args: QMessageBox.StandardButton.No)
|
||||
window._force_batch_stop()
|
||||
assert not control.is_set() and not control.force_event.is_set()
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *args: QMessageBox.StandardButton.Yes)
|
||||
window._close_pending = True
|
||||
window._force_batch_stop()
|
||||
assert control.is_set() and control.force_event.is_set()
|
||||
assert not window._close_pending
|
||||
finally:
|
||||
window._finish_run()
|
||||
|
||||
|
||||
def test_uncertain_wait_is_visible_in_execution_feedback(tmp_path):
|
||||
import json
|
||||
from dx_productivity.trial_task_center.execution_feedback import read_feedback
|
||||
from dx_productivity.trial_task_center.ui.execution_feedback import format_feedback
|
||||
root = tmp_path / 'quick-run'
|
||||
root.mkdir()
|
||||
(root / 'worker-progress.json').write_text(json.dumps({
|
||||
'stage': 'save_and_close', 'waiting_for_safe_completion': True, 'stage_seconds': {}}))
|
||||
feedback = read_feedback('task', 1, 1, '', tmp_path, 0)
|
||||
text = format_feedback(feedback, 'board', 400, True)
|
||||
assert '尚未确认' in text and '强制' in text
|
||||
|
||||
|
||||
def test_diagnostic_export_during_wait_does_not_finish_or_cancel_execution(window, qtbot, tmp_path, monkeypatch):
|
||||
from PySide6.QtWidgets import QFileDialog
|
||||
open_project(window, qtbot, tmp_path)
|
||||
window._begin_run(window._task_id)
|
||||
control = window._batch_stop
|
||||
owner = object()
|
||||
window._workers.add(owner)
|
||||
destination = tmp_path / 'support.zip'
|
||||
monkeypatch.setattr(QFileDialog, 'getSaveFileName', lambda *args: (str(destination), ''))
|
||||
try:
|
||||
window._export_diagnostics()
|
||||
qtbot.waitUntil(lambda: window._diagnostic_worker is None, timeout=5000)
|
||||
assert destination.is_file()
|
||||
assert owner in window._workers and window._batch_stop is control
|
||||
assert not control.is_set() and not control.force_event.is_set()
|
||||
finally:
|
||||
window._workers.discard(owner)
|
||||
window._finish_run()
|
||||
@@ -0,0 +1,343 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from threading import Event, Thread
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.worker_monitor import ProgressWatch, run_monitored_process
|
||||
|
||||
|
||||
def test_unsafe_save_timeout_waits_for_completion_and_recovers_on_progress():
|
||||
watch = ProgressWatch('token', 'job', 10, 0)
|
||||
assert watch.accept(b'DX_PROGRESS\ttoken\tjob\t1\tsave_and_close\t0\t1\t0\n', 0)
|
||||
assert watch.action(10) == 'request_stop'
|
||||
assert watch.action(20) == 'await_safe_completion'
|
||||
assert watch.snapshot(now=20)['waiting_for_safe_completion'] is True
|
||||
assert watch.action(200) != 'unresponsive'
|
||||
assert watch.accept(b'DX_PROGRESS\ttoken\tjob\t2\tverify_saved_project\t1\t1\t0\n', 201)
|
||||
assert watch.snapshot(now=201)['waiting_for_safe_completion'] is False
|
||||
|
||||
|
||||
def test_real_slow_save_is_not_killed_by_inactivity(tmp_path):
|
||||
script = tmp_path / 'save.py'
|
||||
script.write_text('''import sys,time,pathlib
|
||||
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
|
||||
while not (root/f'monitor-{token}.ready').exists():time.sleep(.01)
|
||||
print(f'DX_PROGRESS\\t{token}\\t{job}\\t1\\tsave_and_close\\t0\\t1\\t0',flush=True)
|
||||
time.sleep(1.5)
|
||||
(root/'saved.txt').write_text('saved and independently verified')
|
||||
''', encoding='utf-8')
|
||||
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
|
||||
result = run_monitored_process(command, .3)
|
||||
assert result.returncode == 0
|
||||
assert (tmp_path / 'saved.txt').read_text() == 'saved and independently verified'
|
||||
|
||||
|
||||
def test_readonly_native_wait_keeps_bounded_cancellation_without_force_ui(tmp_path):
|
||||
script = tmp_path / 'read.py'
|
||||
script.write_text('''import sys,time,pathlib
|
||||
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
|
||||
while not (root/f'monitor-{token}.ready').exists():time.sleep(.01)
|
||||
print(f'DX_PROGRESS\\t{token}\\t{job}\\t1\\tnative_snapshot_read\\t0\\t1\\t0',flush=True)
|
||||
time.sleep(1.5)
|
||||
''', encoding='utf-8')
|
||||
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
|
||||
with pytest.raises(subprocess.TimeoutExpired):
|
||||
run_monitored_process(command, .3, cooperative_abort=True)
|
||||
|
||||
|
||||
def test_explicit_force_stops_unsafe_worker_with_protection(tmp_path):
|
||||
script = tmp_path / 'save.py'
|
||||
script.write_text('''import sys,time,pathlib
|
||||
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
|
||||
while not (root/f'monitor-{token}.ready').exists():time.sleep(.01)
|
||||
print(f'DX_PROGRESS\\t{token}\\t{job}\\t1\\tsave_and_close\\t0\\t1\\t0',flush=True)
|
||||
(root/'started').touch()
|
||||
time.sleep(30)
|
||||
(root/'unexpected_completed').touch()
|
||||
''', encoding='utf-8')
|
||||
force = Event()
|
||||
def request():
|
||||
for _ in range(200):
|
||||
if (tmp_path / 'started').exists():
|
||||
force.set()
|
||||
return
|
||||
Event().wait(.01)
|
||||
requester = Thread(target=request)
|
||||
requester.start()
|
||||
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
|
||||
try:
|
||||
with pytest.raises(Exception, match='forced'):
|
||||
run_monitored_process(command, .3, force_event=force)
|
||||
assert (tmp_path / 'uncertain.flag').exists()
|
||||
assert not (tmp_path / 'unexpected_completed').exists()
|
||||
finally:
|
||||
requester.join(3)
|
||||
|
||||
|
||||
def test_abnormal_cad_shutdown_is_not_hidden_by_physical_release(tmp_path):
|
||||
from dx_productivity.trial_task_center.batch_supervisor import _finish_response
|
||||
from dx_productivity.trial_task_center.batch_resources import write_record
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.supervisor_protocol import encode, encode_error
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
root = tmp_path
|
||||
journal = {'operation': 'probe', 'batch_id': 'a' * 32, 'state': 'blocked'}
|
||||
write_record(root / 'batch-resources' / journal['batch_id'] / 'session.json', {
|
||||
'version': 1, 'session_id': 'a' * 32, 'kind': 'probe', 'state': 'released',
|
||||
'generation': 1, 'desktop': 'dx-' + 'b' * 32, 'processes': [], 'cad_pid': None,
|
||||
'cad_guid': None, 'checkpoints': {}, 'retries': {}, 'timings': [],
|
||||
'cad_shutdown': {'clean': False, 'cleanup_errors': [{'stage': 'orderly_shutdown', 'message': 'Quit timed out'}]}})
|
||||
response = {'business_succeeded': True, 'status': 'error', 'result': encode({'verified': True}),
|
||||
'error': encode_error(TaskCenterError('batch_resources_pending', 'Quit timed out'))}
|
||||
with pytest.raises(TaskCenterError) as caught:
|
||||
_finish_response(root, journal, response, configure_logging(root))
|
||||
assert caught.value.code == 'application_shutdown_failed'
|
||||
assert caught.value.completed_result == {'verified': True}
|
||||
assert journal['resource_recheck']['pending'] is False
|
||||
|
||||
|
||||
def test_force_cannot_terminate_before_interruption_evidence_is_durable(tmp_path, monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
from dx_productivity.trial_task_center import batch_supervisor as module
|
||||
calls = []
|
||||
process = SimpleNamespace(terminate=lambda: calls.append('terminate'))
|
||||
journal = {'operation': 'execute_task_queue', 'batch_id': 'a' * 32, 'attempt_id': 'b' * 32,
|
||||
'task_ids': ['task'], 'state': 'running'}
|
||||
monkeypatch.setattr(module, '_mark_interrupted', lambda *args: (_ for _ in ()).throw(PermissionError('denied')))
|
||||
with pytest.raises(PermissionError):
|
||||
module._force_owned_supervisor(tmp_path, journal, process)
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_force_already_performed_remains_forced_when_exit_diagnostics_fail(tmp_path):
|
||||
from types import SimpleNamespace
|
||||
from dx_productivity.trial_task_center.batch_supervisor import _force_owned_supervisor
|
||||
record = {}
|
||||
def terminate():
|
||||
record['forced_termination'] = True
|
||||
raise OSError('child enumeration failed after force')
|
||||
process = SimpleNamespace(terminate=terminate, cleanup_record=record)
|
||||
journal = {'operation': 'execute_task_queue', 'batch_id': 'a' * 32, 'attempt_id': 'b' * 32,
|
||||
'task_ids': ['task'], 'state': 'running'}
|
||||
_force_owned_supervisor(tmp_path, journal, process)
|
||||
saved = json.loads((tmp_path / 'batch-resources' / ('a' * 32) / 'supervisor.json').read_text(encoding='utf-8'))
|
||||
assert saved['stop_mode'] == 'forced'
|
||||
assert 'enumeration' in saved['force_cleanup_error']
|
||||
|
||||
|
||||
def test_interruption_targets_active_project_without_invalidating_previous_tasks(tmp_path):
|
||||
from dx_productivity.trial_task_center.batch_supervisor import _mark_interrupted
|
||||
from dx_productivity.trial_task_center.batch_resources import write_record
|
||||
batch = 'a' * 32
|
||||
write_record(tmp_path / 'batch-resources' / batch / 'session.json', {
|
||||
'version': 1, 'session_id': batch, 'kind': 'task_queue', 'state': 'ready',
|
||||
'generation': 1, 'desktop': 'dx-' + 'b' * 32, 'processes': [], 'cad_pid': 123,
|
||||
'cad_guid': 'owned', 'checkpoints': {}, 'retries': {}, 'timings': [], 'active_task': 'current'})
|
||||
journal = {'operation': 'execute_task_queue', 'batch_id': batch, 'attempt_id': 'c' * 32,
|
||||
'task_ids': ['previous', 'current'], 'state': 'running'}
|
||||
_mark_interrupted(tmp_path, journal, 'forced stop')
|
||||
assert (tmp_path / 'tasks/current/quick-run/uncertain.flag').exists()
|
||||
assert not (tmp_path / 'tasks/previous/quick-run/uncertain.flag').exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('interactive', [False, True])
|
||||
def test_supervisor_only_holds_for_resolution_when_caller_has_force_control(tmp_path, monkeypatch, interactive):
|
||||
import textwrap
|
||||
from dx_productivity.trial_task_center import batch_supervisor as module
|
||||
from dx_productivity.trial_task_center.stop_control import StopControl
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
bootstrap = textwrap.dedent('''
|
||||
import sys,json
|
||||
from pathlib import Path
|
||||
from dx_productivity.trial_task_center import batch_worker,batch_runtime
|
||||
from dx_productivity.trial_task_center.stop_control import StopControl
|
||||
original=batch_runtime.BatchCadRuntime
|
||||
def runtime(*args,**kwargs):
|
||||
result=original(*args,**kwargs)
|
||||
Path(sys.argv[1]).with_name('interactive-witness.json').write_text(json.dumps(isinstance(result.stop_event,StopControl)))
|
||||
return result
|
||||
batch_runtime.BatchCadRuntime=runtime
|
||||
batch_worker.run(Path(sys.argv[1]))
|
||||
''')
|
||||
monkeypatch.setattr(module, '_command', lambda request: (sys.executable, '-c', bootstrap, str(request)))
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
try:
|
||||
service = TaskCenterService(store, configure_logging(tmp_path))
|
||||
module.run_supervised(service, 'probe', {}, stop_event=StopControl() if interactive else Event())
|
||||
witness = next((tmp_path / 'batch-resources').glob('*/interactive-witness.json'))
|
||||
assert json.loads(witness.read_text()) is interactive
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
def test_uncertain_operation_keeps_owner_until_explicit_force(tmp_path):
|
||||
from dx_productivity.trial_task_center.stop_control import StopControl, wait_for_resolution
|
||||
control = StopControl()
|
||||
failures = []
|
||||
def owner():
|
||||
try:
|
||||
wait_for_resolution(control, tmp_path, 'save result unknown')
|
||||
except Exception as error:
|
||||
failures.append(error)
|
||||
thread = Thread(target=owner)
|
||||
thread.start()
|
||||
try:
|
||||
for _ in range(100):
|
||||
if (tmp_path / 'worker-progress.json').exists():
|
||||
break
|
||||
Event().wait(.01)
|
||||
control.set() # Ordinary stop never authorizes discarding a changed project.
|
||||
thread.join(.15)
|
||||
assert thread.is_alive()
|
||||
assert (tmp_path / 'uncertain.flag').exists()
|
||||
assert json.loads((tmp_path / 'worker-progress.json').read_text())['waiting_for_safe_completion']
|
||||
control.request_force()
|
||||
thread.join(3)
|
||||
assert not thread.is_alive()
|
||||
assert 'forced' in str(failures[0])
|
||||
finally:
|
||||
control.request_force()
|
||||
thread.join(3)
|
||||
|
||||
|
||||
def test_failed_protection_fsync_is_retried_before_force_is_allowed(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import stop_control as module
|
||||
control = module.StopControl()
|
||||
original = module.os.fsync
|
||||
attempts, failures = [], []
|
||||
def denied(fd):
|
||||
attempts.append(fd)
|
||||
raise OSError('evidence fsync denied')
|
||||
monkeypatch.setattr(module.os, 'fsync', denied)
|
||||
def owner():
|
||||
try:
|
||||
module.wait_for_resolution(control, tmp_path, 'save unknown')
|
||||
except Exception as error:
|
||||
failures.append(error)
|
||||
thread = Thread(target=owner)
|
||||
thread.start()
|
||||
try:
|
||||
for _ in range(100):
|
||||
if control.control_error:
|
||||
break
|
||||
Event().wait(.01)
|
||||
assert control.control_error
|
||||
control.request_force()
|
||||
thread.join(.25)
|
||||
assert thread.is_alive(), 'a file left by failed fsync must not authorize force'
|
||||
assert len(attempts) >= 2
|
||||
monkeypatch.setattr(module.os, 'fsync', original)
|
||||
control.request_force()
|
||||
thread.join(3)
|
||||
assert failures and 'forced' in str(failures[0])
|
||||
finally:
|
||||
monkeypatch.setattr(module.os, 'fsync', original)
|
||||
control.request_force()
|
||||
thread.join(3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('deny_first,transport_failure', [(False, False), (True, False), (False, True)])
|
||||
def test_real_supervisor_force_preserves_protection_and_never_replays(tmp_path, monkeypatch, deny_first, transport_failure):
|
||||
import os
|
||||
import textwrap
|
||||
import time
|
||||
import win32api
|
||||
import win32event
|
||||
from dx_productivity.trial_task_center import batch_supervisor as module
|
||||
from dx_productivity.trial_task_center.stop_control import StopControl
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
service = TaskCenterService(store, configure_logging(tmp_path), supervised=True)
|
||||
task = store.create_task('force fixture')
|
||||
evidence = service._project_task_service(task.task_id)._quick_run_preparer.data_root / 'quick-run'
|
||||
witness = evidence / 'started'
|
||||
bootstrap = textwrap.dedent('''
|
||||
import sys,os,time,json
|
||||
from pathlib import Path
|
||||
from dx_productivity.trial_task_center import batch_worker
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
def business(self, task_id, **kwargs):
|
||||
root=self._project_task_service(task_id)._quick_run_preparer.data_root/'quick-run'
|
||||
root.mkdir(parents=True,exist_ok=True)
|
||||
(root/'started').write_text(str(os.getpid()))
|
||||
request=json.loads(Path(sys.argv[1]).read_text(encoding='utf-8'))
|
||||
print(json.dumps({'version':1,'batch_id':request['batch_id'],'attempt_id':request['attempt_id'],
|
||||
'generation':1,'sequence':100,'type':'progress','payload':'fixture executing'}),flush=True)
|
||||
time.sleep(30)
|
||||
(root/'unexpected_completed').touch()
|
||||
TaskCenterService.execute_quick_run=business
|
||||
batch_worker.run(Path(sys.argv[1]))
|
||||
''')
|
||||
original_command = module._command
|
||||
monkeypatch.setattr(module, '_command', lambda request:
|
||||
(sys.executable, '-c', bootstrap, str(request))
|
||||
if json.loads(request.read_text())['operation'] == 'execute_quick_run' else original_command(request))
|
||||
original_mark = module._mark_interrupted
|
||||
denied = []
|
||||
def mark(*args):
|
||||
if deny_first and not denied:
|
||||
denied.append(True)
|
||||
raise PermissionError('force evidence denied once')
|
||||
return original_mark(*args)
|
||||
monkeypatch.setattr(module, '_mark_interrupted', mark)
|
||||
control = StopControl()
|
||||
driver_errors, survived = [], []
|
||||
def request():
|
||||
try:
|
||||
deadline = time.monotonic() + 15
|
||||
while not witness.exists() and time.monotonic() < deadline:
|
||||
time.sleep(.02)
|
||||
assert witness.exists()
|
||||
pid = int(witness.read_text())
|
||||
if transport_failure:
|
||||
while not control.control_error and time.monotonic() < deadline:
|
||||
time.sleep(.02)
|
||||
assert control.control_error
|
||||
handle = win32api.OpenProcess(0x100000, False, pid)
|
||||
try:
|
||||
survived.append(win32event.WaitForSingleObject(handle, 0) == 258)
|
||||
finally:
|
||||
handle.Close()
|
||||
control.request_force()
|
||||
if deny_first:
|
||||
while not control.control_error and time.monotonic() < deadline:
|
||||
time.sleep(.02)
|
||||
assert control.control_error
|
||||
handle = win32api.OpenProcess(0x100000, False, pid)
|
||||
try:
|
||||
survived.append(win32event.WaitForSingleObject(handle, 0) == 258)
|
||||
finally:
|
||||
handle.Close()
|
||||
control.request_force()
|
||||
except Exception as error:
|
||||
driver_errors.append(error)
|
||||
thread = Thread(target=request)
|
||||
thread.start()
|
||||
try:
|
||||
with pytest.raises(TaskCenterError) as caught:
|
||||
module.run_supervised(service, 'execute_quick_run', {'task_id': task.task_id}, stop_event=control,
|
||||
on_progress=(lambda _: (_ for _ in ()).throw(RuntimeError('UI feedback failed'))) if transport_failure else None)
|
||||
assert not driver_errors
|
||||
assert caught.value.code == 'user_forced_stop'
|
||||
assert (evidence / 'uncertain.flag').exists()
|
||||
marker = (evidence / 'uncertain.flag').read_bytes()
|
||||
assert not (evidence / 'unexpected_completed').exists()
|
||||
journals = [json.loads(p.read_text(encoding='utf-8')) for p in (tmp_path / 'batch-resources').glob('*/supervisor.json')]
|
||||
forced = next(r for r in journals if r['operation'] == 'execute_quick_run')
|
||||
assert forced['stop_mode'] == 'forced' and forced['business_uncertain'] is True
|
||||
assert service.cleanup_batch_resources() == ()
|
||||
assert (evidence / 'uncertain.flag').read_bytes() == marker
|
||||
assert not (evidence / 'unexpected_completed').exists()
|
||||
if deny_first or transport_failure:
|
||||
assert survived == [True]
|
||||
finally:
|
||||
thread.join(3)
|
||||
store.close()
|
||||
Reference in new issue
Block a user