fix(dsh): address intervention cancellation and verification review
Core regression / Python 3.12 core, intervention UI and release configuration (push) Failing after 21s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python 3.12 core, intervention UI and release configuration (pull_request) Failing after 21s
Core regression / JavaScript syntax (pull_request) Successful in 3s
Core regression / Python 3.12 core, intervention UI and release configuration (push) Failing after 21s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python 3.12 core, intervention UI and release configuration (pull_request) Failing after 21s
Core regression / JavaScript syntax (pull_request) Successful in 3s
This commit is contained in:
1 parent
de9cb2908d
commit
775bc23dc3
26 files changed
+1280
-119
No files matched your search
+259
-8
@@ -228,7 +228,8 @@ def test_resource_cleanup_is_verified_without_cad_authorization_or_replay(tmp_pa
|
||||
assert service.calls == ['cleanup']
|
||||
assert service.pending_reads >= 2
|
||||
assert result['attempts'] == 0
|
||||
assert result['verification'] == {'resources_released': True, 'remaining_resources': []}
|
||||
assert result['verification'] == {'verification_status': 'complete', 'resources_released': True,
|
||||
'cleanup_performed': True, 'remaining_resources': []}
|
||||
assert snapshots[0]['intervention']['cleanup_allowed'] is True
|
||||
directory = Path(result['evidence_dir'])
|
||||
cleanup = json.loads((directory / 'cleanup.json').read_text(encoding='utf8'))
|
||||
@@ -246,7 +247,7 @@ def test_cleanup_missing_or_negative_verification_escalates_with_evidence(tmp_pa
|
||||
result = make_runner(tmp_path, service, cleanup_model).run('t', 'resource_cleanup_pending', 'release pending', cleanup_allowed=True)
|
||||
assert service.calls == ['cleanup']
|
||||
assert result['status'] == 'escalated'
|
||||
assert result['verification']['resources_released'] is False
|
||||
assert result['verification']['resources_released'] is (None if error or reread_error else False)
|
||||
directory = Path(result['evidence_dir'])
|
||||
cleanup = json.loads((directory / 'cleanup.json').read_text(encoding='utf8'))
|
||||
if remains or error:
|
||||
@@ -325,7 +326,7 @@ def test_revoking_cleanup_permission_at_notification_boundary_prevents_mutation(
|
||||
execution_enabled=permission)
|
||||
assert service.calls == []
|
||||
assert result['status'] == 'escalated'
|
||||
assert result['verification']['resources_released'] is False
|
||||
assert result['verification']['resources_released'] is None
|
||||
audit = json.loads((tmp_path / 'dsh' / 'decisions.jsonl').read_text(encoding='utf8').splitlines()[-1])
|
||||
assert audit['candidate_action'] == 'none'
|
||||
|
||||
@@ -343,8 +344,258 @@ def test_cleanup_failure_with_unavailable_publisher_remains_in_outbox(tmp_path):
|
||||
assert cleanup['remaining_resources'][0]['session_id'] == 'owned-session'
|
||||
|
||||
|
||||
def test_trigger_bound_holds_when_the_last_string_starts_near_the_budget_limit():
|
||||
for tail_length in range(400):
|
||||
trigger = {str(index): 'x' * 1000 for index in range(15)}
|
||||
trigger.update(tail='x' * tail_length, large='y' * 50000)
|
||||
assert len(json.dumps(_bounded_details(trigger))) < 20000
|
||||
@pytest.mark.parametrize('tail_length', [0, 395, 396, 399])
|
||||
def test_trigger_bound_holds_when_the_last_string_starts_near_the_budget_limit(tail_length):
|
||||
trigger = {str(index): 'x' * 1000 for index in range(15)}
|
||||
trigger.update(tail='x' * tail_length, large='y' * 50000)
|
||||
assert len(json.dumps(_bounded_details(trigger))) < 20000
|
||||
|
||||
|
||||
def test_cleanup_already_empty_is_observed_cleared_without_cleanup_credit_or_publication(tmp_path):
|
||||
service = ResourceService()
|
||||
service.pending.clear()
|
||||
result = make_runner(tmp_path, service, cleanup_model).run(
|
||||
't', 'batch_resources_pending', 'already clear', cleanup_allowed=True,
|
||||
snapshot_override={'status': 'blocked', 'task_id': 't'})
|
||||
assert result['status'] == 'observed_cleared'
|
||||
assert result['action'] == 'none'
|
||||
assert result['cleanup_attempts'] == 0
|
||||
assert service.calls == []
|
||||
assert result['ticket'] == {}
|
||||
assert result['verification'] == {'verification_status': 'observed_cleared',
|
||||
'resources_released': True, 'cleanup_performed': False, 'remaining_resources': []}
|
||||
audit = json.loads((tmp_path / 'dsh' / 'decisions.jsonl').read_text(encoding='utf8').splitlines()[-1])
|
||||
assert audit['candidate_action'] == 'none'
|
||||
assert audit['outcome'] == 'observed_cleared'
|
||||
|
||||
|
||||
def test_cleanup_first_read_failure_preserves_empty_reread_as_incomplete_unknown(tmp_path):
|
||||
service = ResourceService(reread_error=False)
|
||||
calls = [0]
|
||||
def first_read_fails():
|
||||
calls[0] += 1
|
||||
if calls[0] == 1:
|
||||
raise OSError('first read unavailable')
|
||||
return ()
|
||||
service.pending_batch_resources = first_read_fails
|
||||
result = make_runner(tmp_path, service, cleanup_model).run(
|
||||
't', 'batch_resources_pending', 'uncertain resources', cleanup_allowed=True,
|
||||
snapshot_override={'status': 'blocked', 'task_id': 't'})
|
||||
assert result['status'] == 'escalated'
|
||||
assert result['verification'] == {'verification_status': 'incomplete',
|
||||
'resources_released': None, 'cleanup_performed': False, 'remaining_resources': [],
|
||||
'remaining_resources_observed': True}
|
||||
cleanup = json.loads((Path(result['evidence_dir']) / 'cleanup.json').read_text(encoding='utf8'))
|
||||
assert cleanup['resources_before_error']['type'] == 'OSError'
|
||||
assert cleanup['remaining_resources'] == []
|
||||
assert cleanup['remaining_resources_observed'] is True
|
||||
|
||||
|
||||
def test_bounded_details_is_json_safe_utf8_bounded_and_preserves_snapshot_fields():
|
||||
from dx_productivity.dsh.incidents import _bounded_details
|
||||
value = {'progress': {'huge': 10 ** 5000}, 'status': 'running', 'task_id': 'task',
|
||||
'task_name': 'name', 'items': list(range(1000)), 'nan': float('nan'),
|
||||
'inf': float('inf'), 'cycle': None}
|
||||
value['cycle'] = value
|
||||
bounded = _bounded_details(value)
|
||||
encoded = json.dumps(bounded, ensure_ascii=False, allow_nan=False).encode('utf8')
|
||||
assert len(encoded) <= 16000
|
||||
assert bounded['task_id'] == 'task' and bounded['status'] == 'running'
|
||||
assert '__truncated__' in json.dumps(bounded, ensure_ascii=False)
|
||||
|
||||
|
||||
def test_cancel_event_stops_after_diagnosis_without_reflection_or_publication(tmp_path):
|
||||
cancel = Event()
|
||||
service = ResourceService()
|
||||
phases = []
|
||||
def model(*args):
|
||||
phases.append(args[-1])
|
||||
cancel.set()
|
||||
return cleanup_model()
|
||||
published = []
|
||||
result = make_runner(tmp_path, service, model, lambda *args: published.append(args)).run(
|
||||
't', 'operation_stalled', 'cancel me', cancel_event=cancel,
|
||||
snapshot_override={'status': 'running', 'task_id': 't'}, trigger={'operation': 'poll'})
|
||||
assert result['status'] == 'cancelled'
|
||||
assert phases == ['diagnose']
|
||||
assert not service.calls and not published
|
||||
assert result['human_takeover'] is True
|
||||
assert json.loads((tmp_path / 'dsh' / 'decisions.jsonl').read_text(encoding='utf8').splitlines()[-1])['human_takeover'] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize('payload', [
|
||||
{str(index): 10 ** 900 for index in range(100)},
|
||||
{'键' * 80 + str(index): ['中' * 1000] * 30 for index in range(60)},
|
||||
[{'nested': [{'message': '中' * 1000} for _ in range(30)]} for _ in range(30)],
|
||||
])
|
||||
def test_serialized_evidence_bound_counts_numbers_keys_unicode_and_containers(payload):
|
||||
bounded = _bounded_details(payload)
|
||||
assert len(json.dumps(bounded, ensure_ascii=False, allow_nan=False, indent=2).encode('utf8')) <= 16000
|
||||
assert len(json.dumps(bounded, ensure_ascii=True, allow_nan=False, indent=2).encode('utf8')) <= 16000
|
||||
if isinstance(bounded, dict):
|
||||
assert bounded['__truncated__'] is True
|
||||
else:
|
||||
assert bounded[-1] == {'__truncated__': True}
|
||||
|
||||
|
||||
def test_cached_snapshot_preserves_mandatory_fields_after_large_earlier_extras(tmp_path):
|
||||
service = Service()
|
||||
service.task_context = lambda *args: (_ for _ in ()).throw(AssertionError('live context forbidden'))
|
||||
cached = {str(index): '中' * 1000 for index in range(100)}
|
||||
cached.update(task_id='t', status='running', task_name='late task name')
|
||||
seen = []
|
||||
def model(incident, snapshot, evidence, phase):
|
||||
seen.append(snapshot)
|
||||
return {'reply': '{"summary":"diagnostic only","action":"none"}'}
|
||||
result = make_runner(tmp_path, service, model).run('t', 'operation_stalled', 'stalled', snapshot_override=cached)
|
||||
assert result['status'] == 'escalated'
|
||||
assert all(row['task_id'] == 't' and row['status'] == 'running' and row['task_name'] == 'late task name' for row in seen)
|
||||
|
||||
|
||||
def test_hostile_trigger_values_remain_readable_and_do_not_strand_collection(tmp_path):
|
||||
class Hostile:
|
||||
def __str__(self):
|
||||
raise RuntimeError('must not stringify arbitrary objects')
|
||||
trigger = {'huge': 10 ** 5000, 'hostile': Hostile(), 'float': float('nan'), 'cycle': []}
|
||||
trigger['cycle'].append(trigger)
|
||||
result = make_runner(tmp_path).run('t', 'operation_stalled', 'stalled', trigger=trigger,
|
||||
snapshot_override={'task_id': 't', 'status': 'running'})
|
||||
assert result['status'] == 'escalated'
|
||||
path = Path(result['evidence_dir'])
|
||||
payload = json.loads((path / 'trigger.json').read_text(encoding='utf8'))
|
||||
assert 'huge' in payload and 'hostile' in payload
|
||||
assert (path / 'diagnose.json').is_file()
|
||||
assert (path / 'issue.md').is_file()
|
||||
|
||||
|
||||
def test_trigger_preparation_error_is_diagnosed_instead_of_stranding_collection(tmp_path):
|
||||
class BrokenMapping(dict):
|
||||
def __iter__(self):
|
||||
raise RuntimeError('unreadable trigger mapping')
|
||||
result = make_runner(tmp_path).run('t', 'operation_stalled', 'stalled',
|
||||
trigger=BrokenMapping({'operation': 'poll'}), snapshot_override={'task_id': 't', 'status': 'running'})
|
||||
assert result['status'] == 'escalated'
|
||||
path = Path(result['evidence_dir'])
|
||||
assert json.loads((path / 'trigger.json').read_text(encoding='utf8')) == {'__preparation_error__': 'RuntimeError'}
|
||||
assert (path / 'diagnose.json').is_file() and (path / 'issue.md').is_file()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('terminal', ['observed_cleared', 'cancelled'])
|
||||
def test_observation_and_cancellation_remain_terminal_on_reopen(tmp_path, terminal):
|
||||
service = ResourceService()
|
||||
service.pending.clear()
|
||||
cancel = Event()
|
||||
if terminal == 'cancelled':
|
||||
cancel.set()
|
||||
runner = make_runner(tmp_path, service, cleanup_model)
|
||||
result = runner.run('t', 'batch_resources_pending', 'pending', cleanup_allowed=True, cancel_event=cancel)
|
||||
assert result['status'] == terminal
|
||||
resumed = runner.run('t', 'batch_resources_pending', 'reopened', cleanup_allowed=True)
|
||||
assert resumed['status'] == terminal
|
||||
assert not service.calls
|
||||
assert runner.publish_pending(result['incident_id'])['status'] == terminal
|
||||
|
||||
|
||||
@pytest.mark.parametrize('moment', ['before_diagnosis', 'notification', 'resource_read', 'reflection', 'before_publication'])
|
||||
def test_cancellation_bypasses_additional_models_and_remote_publication(tmp_path, moment):
|
||||
cancel, stop = Event(), Event()
|
||||
phases, publications = [], []
|
||||
service = ResourceService(remains=True)
|
||||
if moment == 'before_diagnosis':
|
||||
cancel.set()
|
||||
original_read = service.pending_batch_resources
|
||||
def read_and_cancel():
|
||||
pending = original_read()
|
||||
if moment == 'resource_read':
|
||||
cancel.set()
|
||||
return pending
|
||||
service.pending_batch_resources = read_and_cancel
|
||||
def model(*args):
|
||||
phases.append(args[-1])
|
||||
if moment == 'reflection' and args[-1] == 'reflect':
|
||||
cancel.set()
|
||||
return cleanup_model()
|
||||
runner = make_runner(tmp_path, service, model, lambda *args: publications.append(args))
|
||||
def notify(record):
|
||||
if (moment == 'notification' and record.get('cleanup_attempts') == 1
|
||||
or moment == 'before_publication' and record['status'] == 'pending_issue'):
|
||||
cancel.set()
|
||||
runner.notify = notify
|
||||
result = runner.run('t', 'batch_resources_pending', 'pending', cleanup_allowed=True,
|
||||
cancel_event=cancel, stop_event=stop, snapshot_override={'task_id': 't', 'status': 'blocked'})
|
||||
assert result['status'] == 'cancelled'
|
||||
assert not publications
|
||||
assert not stop.is_set()
|
||||
if moment in {'before_diagnosis', 'notification', 'resource_read'}:
|
||||
assert service.calls == []
|
||||
assert phases == ([] if moment == 'before_diagnosis' else ['diagnose'])
|
||||
else:
|
||||
assert service.calls == ['cleanup']
|
||||
assert phases == ['diagnose', 'reflect']
|
||||
with zipfile.ZipFile(Path(result['evidence_dir']) / 'evidence.zip') as archive:
|
||||
audit = json.loads(archive.read('report.json'))
|
||||
assert audit['status'] == 'cancelled'
|
||||
assert runner.publish_pending(result['incident_id'])['status'] == 'cancelled'
|
||||
|
||||
|
||||
def test_cancellation_after_cleanup_preserves_independent_verification_and_action(tmp_path):
|
||||
cancel, stop = Event(), Event()
|
||||
service = ResourceService()
|
||||
original = service.cleanup_batch_resources
|
||||
def clean_and_cancel():
|
||||
result = original()
|
||||
cancel.set()
|
||||
return result
|
||||
service.cleanup_batch_resources = clean_and_cancel
|
||||
published, phases = [], []
|
||||
def model(*args):
|
||||
phases.append(args[-1])
|
||||
return cleanup_model()
|
||||
result = make_runner(tmp_path, service, model, lambda *args: published.append(args)).run(
|
||||
't', 'batch_resources_pending', 'pending', cleanup_allowed=True,
|
||||
cancel_event=cancel, stop_event=stop, snapshot_override={'task_id': 't', 'status': 'blocked'})
|
||||
assert result['status'] == 'cancelled'
|
||||
assert result['verification']['resources_released'] is True
|
||||
assert result['verification']['cleanup_performed'] is True
|
||||
assert service.pending_reads == 2
|
||||
assert phases == ['diagnose'] and not published
|
||||
assert service.calls == ['cleanup'] and not stop.is_set()
|
||||
audit = json.loads((tmp_path / 'dsh' / 'decisions.jsonl').read_text(encoding='utf8').splitlines()[-1])
|
||||
assert audit['candidate_action'] == 'cleanup_resources' and audit['human_takeover'] is True
|
||||
|
||||
|
||||
def test_cancellation_after_admitted_cad_execution_preserves_verification(tmp_path):
|
||||
cancel, stop = Event(), Event()
|
||||
service = Service()
|
||||
execute = service.execute_quick_run_queue
|
||||
def execute_and_cancel(*args, **kwargs):
|
||||
result = execute(*args, **kwargs)
|
||||
cancel.set()
|
||||
return result
|
||||
service.execute_quick_run_queue = execute_and_cancel
|
||||
result = make_runner(tmp_path, service).run('t', 'worker_error', 'failure',
|
||||
execution_authorized=True, cancel_event=cancel, stop_event=stop)
|
||||
assert result['status'] == 'cancelled'
|
||||
assert service.calls == ['prepare', 'execute'] and not stop.is_set()
|
||||
assert result['verification']['queue_complete'] is True
|
||||
assert result['verification']['failed_items'] == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('code,action', [('batch_resources_pending', 'cleanup_resources'), ('worker_error', 'retry_failed')])
|
||||
def test_cancellation_during_durable_action_intent_prevents_mutation(tmp_path, monkeypatch, code, action):
|
||||
import dx_productivity.dsh.incidents as incidents
|
||||
cancel = Event()
|
||||
service = ResourceService()
|
||||
original = incidents.write_json
|
||||
def write_and_cancel(path, value):
|
||||
original(path, value)
|
||||
if path.name == 'incident.json' and value.get('action') == action:
|
||||
cancel.set()
|
||||
monkeypatch.setattr(incidents, 'write_json', write_and_cancel)
|
||||
model = cleanup_model if action == 'cleanup_resources' else analyze
|
||||
result = make_runner(tmp_path, service, model).run('t', code, 'pending', cleanup_allowed=True,
|
||||
execution_authorized=True, cancel_event=cancel)
|
||||
assert result['status'] == 'cancelled'
|
||||
assert service.calls == []
|
||||
audit = json.loads((tmp_path / 'dsh' / 'decisions.jsonl').read_text(encoding='utf8').splitlines()[-1])
|
||||
assert audit['candidate_action'] == 'none'
|
||||
@@ -12,6 +12,7 @@ def blockers(ui, monkeypatch):
|
||||
events = []
|
||||
spy = SimpleNamespace(
|
||||
watched={}, check_stalled=lambda: None,
|
||||
completed=lambda *args: None,
|
||||
report=lambda *args, **kwargs: events.append(('report', args, kwargs)),
|
||||
clear=lambda *args, **kwargs: events.append(('clear', args, kwargs)),
|
||||
watch=lambda *args, **kwargs: events.append(('watch', args, kwargs)),
|
||||
@@ -117,8 +118,11 @@ def test_operations_read_error_reports_on_ui_thread_and_clears_on_recovery(ui, b
|
||||
monkeypatch.setattr(ctl.schedules, 'events', lambda: (_ for _ in ()).throw(OSError('unreadable')))
|
||||
ctl.refresh()
|
||||
qtbot.waitUntil(lambda: ctl.worker is None)
|
||||
assert not reports(blockers)
|
||||
qtbot.waitUntil(lambda: bool(reports(blockers)), timeout=3000)
|
||||
event = next(row for row in reports(blockers) if row[1][2] == 'section_unavailable')
|
||||
assert event[1][4]['section'] == 'schedule_events'
|
||||
assert event[1][4]['consecutive_failures'] == 2
|
||||
assert event[2].get('read_only') is True
|
||||
monkeypatch.setattr(ctl.schedules, 'events', original)
|
||||
ctl.refresh()
|
||||
@@ -161,11 +165,15 @@ def test_bom_operational_report_and_progress_keep_import_owner_after_selection_c
|
||||
panel = ui.window.plan_panel
|
||||
owner = panel.task_id
|
||||
scope = panel._report_scope(owner)
|
||||
worker = object()
|
||||
monkeypatch.setattr(ui.window, '_operation_worker', worker, raising=False)
|
||||
monkeypatch.setattr(panel, '_dispatch', lambda *args, **kwargs: None)
|
||||
panel._dispatch_cancellable(lambda *args: None, lambda _: None, panel.import_bom_button, bom_scope=scope)
|
||||
ui.open(ui.tasks[1])
|
||||
panel._operation_phase(BomImportPhase.VALIDATING, 'Validating imported rows')
|
||||
assert ('progress', ('Validating imported rows',), {}) in blockers
|
||||
assert any(event[0] == 'progress' and event[1][0] == 'Validating imported rows'
|
||||
and (event[1][1] if len(event[1]) > 1 else event[2].get('worker')) is worker
|
||||
for event in blockers)
|
||||
error = TaskCenterError('bom_read_failed', 'Project inventory unavailable')
|
||||
error.bom_report = BomImportReport((BomRowResult(2, '', '', 'failed', 'inventory unavailable'),), ())
|
||||
panel.finish_operation(error=error)
|
||||
@@ -231,3 +239,37 @@ def test_creation_worker_failure_reports_and_success_clears_source(ui, blockers,
|
||||
qtbot.waitUntil(lambda: ctl.worker is None)
|
||||
assert ('clear', ('task-creation',), {}) in blockers
|
||||
assert not ui.calls
|
||||
|
||||
|
||||
def test_transient_background_section_failure_recovers_on_quick_reread_without_ai(ui, blockers, monkeypatch, qtbot):
|
||||
setup_view(ui, monkeypatch)
|
||||
ctl = ui.window._dsh_operations
|
||||
original = ctl.schedules.events
|
||||
calls = []
|
||||
def read():
|
||||
calls.append(True)
|
||||
if len(calls) == 1:
|
||||
raise OSError('temporary read sharing violation')
|
||||
return original()
|
||||
monkeypatch.setattr(ctl.schedules, 'events', read)
|
||||
ctl.refresh()
|
||||
qtbot.waitUntil(lambda: len(calls) >= 2 and ctl.worker is None, timeout=3000)
|
||||
assert not reports(blockers)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scope', ['whole_read', 'decision_audit'])
|
||||
def test_transient_background_read_failures_are_confirmed_by_actual_reads(ui, blockers, monkeypatch, qtbot, scope):
|
||||
setup_view(ui, monkeypatch)
|
||||
ctl = ui.window._dsh_operations
|
||||
owner, method = (ctl, '_read') if scope == 'whole_read' else (ctl.decisions, 'list')
|
||||
original = getattr(owner, method)
|
||||
calls = []
|
||||
def read(*args, **kwargs):
|
||||
calls.append(True)
|
||||
if len(calls) == 1:
|
||||
raise OSError('temporary read unavailable')
|
||||
return original(*args, **kwargs)
|
||||
monkeypatch.setattr(owner, method, read)
|
||||
ctl.refresh()
|
||||
qtbot.waitUntil(lambda: len(calls) >= 2 and ctl.worker is None, timeout=3000)
|
||||
assert not reports(blockers)
|
||||
@@ -66,7 +66,7 @@ def test_operation_progress_does_not_hide_stuck_query_and_recovery_starts_new_ep
|
||||
operation, query = object(), object()
|
||||
coordinator.watch(operation, '导入 BOM', 'task-1', 'bom', now=0)
|
||||
coordinator.watch(query, '读取资源', '', area, now=0)
|
||||
coordinator.progress('row 2', now=100)
|
||||
coordinator.progress('row 2', operation, now=100)
|
||||
coordinator.check_stalled(now=121)
|
||||
assert len(events) == 1 and events[0]['task_id'] == ''
|
||||
coordinator.progress('resource reply received', query, now=130)
|
||||
@@ -90,8 +90,9 @@ def test_resource_states_enter_ai_once_and_recover(ui):
|
||||
assert events[0]['cleanup_allowed'] is True
|
||||
window._resource_status.records = ()
|
||||
window._observe_dsh_resource_blockers()
|
||||
window._resource_status.error = OSError('resource query failed')
|
||||
window._observe_dsh_resource_blockers()
|
||||
window._resource_status._failed(OSError('resource query failed'))
|
||||
assert len(events) == 1
|
||||
window._resource_status._failed(OSError('resource query failed'))
|
||||
assert events[-1]['issue_code'] == 'resource_inspection_failed'
|
||||
assert len(events) == 2
|
||||
window._resource_status.error = None
|
||||
@@ -126,7 +127,8 @@ def test_ai_retry_healthy_resources_are_not_release_failures(ui, monkeypatch):
|
||||
window._dsh_blockers.enqueue = lambda **value: events.append(value) or True
|
||||
active = object()
|
||||
monkeypatch.setattr(window, '_dsh_automation', SimpleNamespace(worker=active, _owns_execution_lane=True,
|
||||
latest={'status': 'retrying'}, cancel_pending=lambda value: None))
|
||||
latest={'status': 'retrying'}, cancel_pending=lambda value: None,
|
||||
can_cancel=False, cancel=lambda: None))
|
||||
window._workers.add(active)
|
||||
window._resource_status.known = True
|
||||
window._resource_status.records = ({'state': 'ready', 'session_id': 'auto-owned-session'},)
|
||||
@@ -206,11 +208,67 @@ def test_resource_diagnosis_keeps_previous_cad_stop_intent(ui, monkeypatch, qtbo
|
||||
assert window._dsh_run_stop.is_set()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('complete_while_disabled', [False, True])
|
||||
def test_completed_blocker_restarts_only_after_explicit_switch_cycle(complete_while_disabled):
|
||||
events = []
|
||||
state = {'enabled': True}
|
||||
window = SimpleNamespace(auto_intervention_check=SimpleNamespace(isChecked=lambda: state['enabled']))
|
||||
coordinator = DshBlockerCoordinator(window, lambda **value: events.append(dict(value)) or True)
|
||||
coordinator.report('bom', 'task-1', 'bom_validation_failed', 'bad row')
|
||||
original_run = events[0]['run_id']
|
||||
if not complete_while_disabled:
|
||||
coordinator.completed(original_run)
|
||||
for _ in range(3):
|
||||
coordinator.report('bom', 'task-1', 'bom_validation_failed', 'bad row')
|
||||
coordinator.replay_pending()
|
||||
assert len(events) == 1
|
||||
state['enabled'] = False
|
||||
coordinator.set_enabled(False)
|
||||
if complete_while_disabled:
|
||||
coordinator.completed(original_run)
|
||||
state['enabled'] = True
|
||||
coordinator.set_enabled(True)
|
||||
assert len(events) == 2 and events[-1]['run_id'] != original_run
|
||||
coordinator.report('bom', 'task-1', 'bom_validation_failed', 'bad row')
|
||||
assert len(events) == 2
|
||||
|
||||
|
||||
def test_completed_while_disabled_restarts_once_but_healthy_clear_cancels():
|
||||
events, cancelled = [], []
|
||||
state = {'enabled': True}
|
||||
window = SimpleNamespace(auto_intervention_check=SimpleNamespace(isChecked=lambda: state['enabled']))
|
||||
coordinator = DshBlockerCoordinator(window, lambda **value: events.append(dict(value)) or True, cancelled.append)
|
||||
coordinator.report('resources', '', 'batch_resources_pending', 'held')
|
||||
run_id = events[0]['run_id']
|
||||
state['enabled'] = False
|
||||
coordinator.set_enabled(False)
|
||||
coordinator.completed(run_id)
|
||||
coordinator.clear('resources')
|
||||
state['enabled'] = True
|
||||
coordinator.set_enabled(True)
|
||||
assert len(events) == 1 and cancelled == [run_id]
|
||||
|
||||
|
||||
def test_progress_only_resets_actual_worker_even_in_same_area():
|
||||
events = []
|
||||
window = SimpleNamespace(auto_intervention_check=SimpleNamespace(isChecked=lambda: True))
|
||||
coordinator = DshBlockerCoordinator(window, lambda **value: events.append(dict(value)) or True)
|
||||
first, second = object(), object()
|
||||
coordinator.watch(first, 'first BOM', 'task-1', 'bom', now=0)
|
||||
coordinator.watch(second, 'second BOM', 'task-2', 'bom', now=0)
|
||||
coordinator.progress('row 2', first, now=100)
|
||||
coordinator.check_stalled(now=121)
|
||||
assert [event['task_id'] for event in events] == ['task-2']
|
||||
with pytest.raises(TypeError):
|
||||
coordinator.progress('unscoped progress', now=130)
|
||||
|
||||
|
||||
def test_global_resource_evidence_actions_work_with_a_task_selected(ui, monkeypatch):
|
||||
window = ui.window
|
||||
calls = []
|
||||
monkeypatch.setattr(window, '_dsh_view', SimpleNamespace(context={'revision': 'r'}, shutdown=lambda: None))
|
||||
monkeypatch.setattr(window, '_dsh_automation', SimpleNamespace(
|
||||
latest={'task_id': '', 'incident_id': 'a' * 24}, resubmit=lambda value: calls.append(value)))
|
||||
latest={'task_id': '', 'incident_id': 'a' * 24}, resubmit=lambda value: calls.append(value),
|
||||
can_cancel=False, cancel=lambda: None))
|
||||
window._handle_dsh_action({'task_id': window._task_id, 'revision': 'r', 'action': 'retry_issue'})
|
||||
assert calls == ['a' * 24]
|
||||
@@ -0,0 +1,141 @@
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import Qt, Signal
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from dx_productivity.trial_task_center.ui import dsh_automation as module
|
||||
from .test_dsh_native_menu import HarnessView
|
||||
|
||||
|
||||
class SlowHarness(HarnessView):
|
||||
diagnosis_event = Signal(object)
|
||||
|
||||
def __init__(self, parent):
|
||||
super().__init__(parent)
|
||||
self.requests, self.cancellations = [], []
|
||||
self.is_running = True
|
||||
|
||||
def request_diagnosis(self, request):
|
||||
self.requests.append(request)
|
||||
|
||||
def cancel_diagnosis(self, request_id):
|
||||
self.cancellations.append(request_id)
|
||||
|
||||
def shutdown(self):
|
||||
self.is_running = False
|
||||
self.stopped.emit()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def slow_diagnosis(ui, qtbot, monkeypatch):
|
||||
ui.settle()
|
||||
window = ui.window
|
||||
published = []
|
||||
monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows')
|
||||
monkeypatch.setattr(window, '_create_dsh_view', lambda: SlowHarness(window))
|
||||
monkeypatch.setattr(module, 'GitIssuePublisher', lambda path: lambda *args: published.append(args) or {'status': 'unavailable'})
|
||||
automation = module.DshAutomation(window)
|
||||
window._dsh_automation = automation
|
||||
|
||||
def start(*, read_only=True, cleanup=False):
|
||||
automation.enqueue('', 'batch_resources_pending' if cleanup else 'operation_stalled', 'controlled slow diagnosis',
|
||||
read_only=read_only, cleanup_allowed=cleanup, snapshot_override={'task_id': '', 'status': 'unknown'})
|
||||
automation._drain()
|
||||
qtbot.waitUntil(lambda: bool(window._dsh_view.requests), timeout=5000)
|
||||
return window._dsh_view
|
||||
|
||||
yield window, automation, published, start
|
||||
if automation.worker is not None:
|
||||
if hasattr(automation, 'cancel'):
|
||||
automation.cancel()
|
||||
else:
|
||||
for request_id in list(automation.waiters):
|
||||
automation._diagnosis_event({'request_id': request_id, 'status': 'failed', 'error': 'test_cleanup'})
|
||||
qtbot.waitUntil(lambda: automation.worker is None, timeout=5000)
|
||||
if not window._closed:
|
||||
ui.settle()
|
||||
|
||||
|
||||
def test_readonly_diagnosis_keeps_task_controls_usable_and_can_be_cancelled(slow_diagnosis, qtbot, ui):
|
||||
window, automation, published, start = slow_diagnosis
|
||||
view = start()
|
||||
assert automation.worker not in window._workers
|
||||
assert window.task_list.list.isEnabled()
|
||||
assert window.task_list.new_button.isEnabled()
|
||||
assert window.cancel_diagnosis_button.isVisible()
|
||||
qtbot.mouseClick(window.cancel_diagnosis_button, Qt.MouseButton.LeftButton)
|
||||
qtbot.waitUntil(lambda: automation.worker is None, timeout=5000)
|
||||
assert view.cancellations
|
||||
assert automation.latest['status'] == 'cancelled'
|
||||
assert not published
|
||||
assert not window.cancel_diagnosis_button.isVisible()
|
||||
ui.settle()
|
||||
|
||||
|
||||
def test_readonly_diagnosis_does_not_prevent_window_close(slow_diagnosis, qtbot):
|
||||
window, automation, published, start = slow_diagnosis
|
||||
start()
|
||||
window.close()
|
||||
qtbot.waitUntil(lambda: window._closed and automation.worker is None, timeout=5000)
|
||||
assert not window._close_pending
|
||||
assert not published
|
||||
|
||||
|
||||
def test_resource_diagnosis_has_no_cad_pause_or_force_controls(slow_diagnosis, qtbot, ui):
|
||||
window, automation, published, start = slow_diagnosis
|
||||
view = start(read_only=False, cleanup=True)
|
||||
assert automation.worker in window._workers
|
||||
assert window._batch_stop is None
|
||||
assert not window.run_panel.stop_queue_button.isVisible()
|
||||
assert not window.run_panel.force_stop_button.isVisible()
|
||||
qtbot.mouseClick(window.cancel_diagnosis_button, Qt.MouseButton.LeftButton)
|
||||
qtbot.waitUntil(lambda: automation.worker is None, timeout=5000)
|
||||
assert view.cancellations and not published
|
||||
ui.settle()
|
||||
|
||||
|
||||
def test_model_wait_is_limited_by_remaining_total_budget(slow_diagnosis, monkeypatch, ui):
|
||||
window, automation, _, _ = slow_diagnosis
|
||||
window._open_dsh()
|
||||
waits = []
|
||||
|
||||
class Complete:
|
||||
def wait(self, timeout):
|
||||
waits.append(timeout)
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(module, 'Event', Complete)
|
||||
monkeypatch.setattr(module, 'monotonic', lambda: 100.0)
|
||||
automation._analysis_deadline = 100.1
|
||||
with pytest.raises(TimeoutError):
|
||||
automation._analyze('a' * 24, {'task_id': ''}, 'evidence', 'reflect')
|
||||
assert 0 < waits[0] <= 0.1
|
||||
ui.settle()
|
||||
|
||||
|
||||
def test_native_cancel_removes_queued_request_and_sends_only_target_id():
|
||||
from dx_productivity.trial_task_center.ui.dsh_native import NativeHarnessView
|
||||
sent = []
|
||||
native = SimpleNamespace(_diagnosis_queue=[{'request_id': 'cancel'}, {'request_id': 'keep'}],
|
||||
_started=False, is_running=True, process=SimpleNamespace(write=sent.append))
|
||||
NativeHarnessView.cancel_diagnosis(native, 'cancel')
|
||||
assert native._diagnosis_queue == [{'request_id': 'keep'}]
|
||||
assert not sent
|
||||
native._started = True
|
||||
NativeHarnessView.cancel_diagnosis(native, 'active')
|
||||
assert json.loads(sent[0]) == {'type': 'diagnose_cancel', 'request_id': 'active'}
|
||||
|
||||
|
||||
def test_completed_incident_removes_embedded_cancel_action(slow_diagnosis, qtbot, ui):
|
||||
from dx_productivity.trial_task_center.ui.workers import ServiceWorker
|
||||
window, automation, _, _ = slow_diagnosis
|
||||
window._open_dsh()
|
||||
automation._current_identity = ('', 'operation_stalled', 'blocker-completed')
|
||||
automation._owns_execution_lane = False
|
||||
automation._start_worker(ServiceWorker(lambda: {'status': 'observed_cleared', 'task_id': ''}))
|
||||
qtbot.waitUntil(lambda: automation.worker is None)
|
||||
assert window._dsh_view.automation['can_cancel'] is False
|
||||
assert not window.cancel_diagnosis_button.isVisible()
|
||||
ui.settle()
|
||||
@@ -80,7 +80,7 @@ def test_cross_task_harness_action_never_reaches_task_service(ui, monkeypatch):
|
||||
def test_error_entry_queues_automatic_ai_without_running_synchronous_retry(ui, monkeypatch):
|
||||
window = ui.window
|
||||
events, retried = [], []
|
||||
window._dsh_automation = SimpleNamespace(enqueue=lambda *args, **kwargs: events.append((args, kwargs)) or True)
|
||||
window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *args, **kwargs: events.append((args, kwargs)) or True)
|
||||
window._dsh.action_handler = lambda proposal: retried.append(proposal)
|
||||
window._show_error(TaskCenterError('worker_error', 'controlled error'))
|
||||
assert len(events) == 1 and events[0][0][:2] == (window._task_id, 'worker_error')
|
||||
@@ -90,7 +90,7 @@ def test_error_entry_queues_automatic_ai_without_running_synchronous_retry(ui, m
|
||||
def test_failed_result_queues_ai_even_when_no_exception_is_raised(ui, monkeypatch):
|
||||
window = ui.window
|
||||
events = []
|
||||
window._dsh_automation = SimpleNamespace(enqueue=lambda *args, **kwargs: events.append((args, kwargs)) or True)
|
||||
window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *args, **kwargs: events.append((args, kwargs)) or True)
|
||||
monkeypatch.setattr(window, '_metadata_changed', lambda _: None)
|
||||
window._active_quick_run_task_id = window._task_id
|
||||
window._show_batch_result(SimpleNamespace(paused=False,
|
||||
@@ -101,7 +101,7 @@ def test_failed_result_queues_ai_even_when_no_exception_is_raised(ui, monkeypatc
|
||||
def test_cancelled_operation_does_not_start_ai(ui):
|
||||
window = ui.window
|
||||
events = []
|
||||
window._dsh_automation = SimpleNamespace(enqueue=lambda *args, **kwargs: events.append(args))
|
||||
window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *args, **kwargs: events.append(args))
|
||||
window._show_error(TaskCenterError('operation_cancelled', 'cancelled'))
|
||||
assert not events
|
||||
|
||||
@@ -129,7 +129,7 @@ def test_auto_intervention_toggle_persists_and_disabled_errors_do_not_enqueue(ui
|
||||
window = ui.window
|
||||
events = []
|
||||
assert window.auto_intervention_check.isChecked()
|
||||
window._dsh_automation = SimpleNamespace(enqueue=lambda *a, **kw: events.append(a),
|
||||
window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *a, **kw: events.append(a),
|
||||
set_enabled=lambda enabled: None)
|
||||
qtbot.mouseClick(window.auto_intervention_check, Qt.MouseButton.LeftButton)
|
||||
window._show_error(TaskCenterError('worker_error', 'disabled error'))
|
||||
@@ -166,7 +166,7 @@ def test_taskless_error_automatically_queues_diagnosis(ui):
|
||||
window._task_id = None
|
||||
window._dsh_run_id = 'previous-cad-run'
|
||||
events = []
|
||||
window._dsh_automation = SimpleNamespace(enqueue=lambda *a, **kw: events.append((a, kw)) or True)
|
||||
window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *a, **kw: events.append((a, kw)) or True)
|
||||
window._show_error(TaskCenterError('worker_error', 'taskless error'))
|
||||
assert len(events) == 1
|
||||
assert events[0][0][:2] == ('', 'worker_error')
|
||||
@@ -177,7 +177,7 @@ def test_taskless_error_automatically_queues_diagnosis(ui):
|
||||
|
||||
def test_native_startup_failure_never_enqueues_itself(ui):
|
||||
events = []
|
||||
ui.window._dsh_automation = SimpleNamespace(enqueue=lambda *a, **kw: events.append(a))
|
||||
ui.window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *a, **kw: events.append(a))
|
||||
ui.window._show_error(TaskCenterError('dsh_startup', 'native unavailable'))
|
||||
assert not events
|
||||
|
||||
@@ -242,7 +242,7 @@ def test_taskless_incident_actions_allow_outbox_and_evidence_but_reject_other_ta
|
||||
monkeypatch.setattr(window, '_task_id', None)
|
||||
monkeypatch.setattr(window, '_dsh_view', SimpleNamespace(context={'revision': 'r'}, shutdown=lambda: None))
|
||||
monkeypatch.setattr(window, '_dsh_automation', SimpleNamespace(
|
||||
latest={'task_id': '', 'incident_id': 'a' * 24}, resubmit=lambda value: calls.append(value)))
|
||||
can_cancel=False, cancel=lambda: None, latest={'task_id': '', 'incident_id': 'a' * 24}, resubmit=lambda value: calls.append(value)))
|
||||
monkeypatch.setattr(QDesktopServices, 'openUrl', lambda url: calls.append(url.toLocalFile()))
|
||||
window._handle_dsh_action({'task_id': '', 'revision': 'r', 'action': 'retry_issue'})
|
||||
window._handle_dsh_action({'task_id': '', 'revision': 'r', 'action': 'open_evidence'})
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
from threading import Event
|
||||
|
||||
from dx_productivity.trial_task_center.ui.queries import LatestQuery
|
||||
from dx_productivity.trial_task_center.ui.resource_status import ResourceStatus
|
||||
|
||||
|
||||
def test_active_workers_excludes_cancelled_old_selection_and_is_immutable(qtbot):
|
||||
query = LatestQuery()
|
||||
first_started, second_started, release = Event(), Event(), Event()
|
||||
def read(started):
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return ()
|
||||
try:
|
||||
query.request(lambda: read(first_started), lambda _: None, lambda _: None)
|
||||
qtbot.waitUntil(first_started.is_set)
|
||||
first = query.active_workers
|
||||
assert isinstance(first, tuple) and len(first) == 1
|
||||
query.request(lambda: read(second_started), lambda _: None, lambda _: None)
|
||||
qtbot.waitUntil(second_started.is_set)
|
||||
current = query.active_workers
|
||||
assert len(current) == 1 and current[0] is not first[0]
|
||||
query.invalidate()
|
||||
assert query.active_workers == () and len(first) == 1
|
||||
finally:
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda: not query.busy)
|
||||
query.close()
|
||||
|
||||
|
||||
def test_resource_failures_count_actual_callbacks_and_success_resets(qtbot):
|
||||
state = {'fail': True, 'calls': 0}
|
||||
def read():
|
||||
state['calls'] += 1
|
||||
if state['fail']:
|
||||
raise OSError('temporary local file failure')
|
||||
return ()
|
||||
status = ResourceStatus(read)
|
||||
try:
|
||||
assert status.consecutive_failures == 0
|
||||
status.refresh()
|
||||
qtbot.waitUntil(lambda: not status.busy)
|
||||
assert status.consecutive_failures == 1
|
||||
status.changed.emit()
|
||||
assert status.consecutive_failures == 1
|
||||
status.refresh()
|
||||
qtbot.waitUntil(lambda: not status.busy)
|
||||
assert status.consecutive_failures == 2
|
||||
state['fail'] = False
|
||||
status.refresh()
|
||||
qtbot.waitUntil(lambda: not status.busy)
|
||||
assert status.consecutive_failures == 0 and state['calls'] == 3
|
||||
finally:
|
||||
status.close()
|
||||
Reference in new issue
Block a user