653 lines
31 KiB
Python
653 lines
31 KiB
Python
from pathlib import Path
|
|
from types import SimpleNamespace as NS
|
|
from threading import Event
|
|
import json
|
|
import zipfile
|
|
import pytest
|
|
|
|
from dx_productivity.dsh.incidents import IncidentRunner, decision, _bounded_details
|
|
|
|
|
|
class Service:
|
|
def __init__(self, *, interrupted=False, fixed=True):
|
|
self.calls = []
|
|
self.interrupted = interrupted
|
|
self.fixed = fixed
|
|
self.reserved = False
|
|
self.progress = NS(completed_items=0, total_items=1, saved_items=0, failed_items=1,
|
|
no_match_items=0, queue_complete=True, next_project_path=None)
|
|
|
|
def task_context(self, task_id):
|
|
return NS(task=NS(task_id=task_id, status=NS(value='running'), copy_part_number_to_value=False),
|
|
progress=self.progress, interrupted=self.interrupted, phase='retry', rules=(1,))
|
|
|
|
def execution_problem_overview(self, task_id):
|
|
return {'items': [{'auto_retries_remaining': int(not self.reserved and not self.interrupted)}]}
|
|
|
|
def reserve_problem_retry(self, task_id, *, source):
|
|
if self.reserved or self.interrupted:
|
|
return ()
|
|
self.reserved = True
|
|
return ('original-target',)
|
|
|
|
def prepare_failed_quick_run(self, task_id, *, operation_keys=None):
|
|
self.calls.append('prepare')
|
|
self.progress = NS(**(vars(self.progress) | {'next_project_path': Path('board.prj'),
|
|
'next_old_part_number': 'OLD', 'next_new_part_number': 'NEW', 'queue_complete': False}))
|
|
|
|
def execute_quick_run_queue(self, task_id, *, expected_item, stop_event):
|
|
self.calls.append('execute')
|
|
self.progress = NS(**(vars(self.progress) | {'queue_complete': True, 'failed_items': 0 if self.fixed else 1,
|
|
'completed_items': 1, 'saved_items': 1 if self.fixed else 0}))
|
|
return NS(paused=False, progress=self.progress)
|
|
|
|
|
|
def analyze(*args):
|
|
return {'reply': json.dumps({'summary': '已核对失败记录', 'action': 'retry_failed', 'unknowns': ['需执行后核验']}),
|
|
'session_id': 'native-session', 'transcript': [{'type': 'tool/result', 'name': 'dx_task_snapshot'}]}
|
|
|
|
|
|
def make_runner(tmp_path, service=None, analyzer=analyze, publisher=None):
|
|
def publish(record, archive):
|
|
assert archive.is_file()
|
|
return {'status': 'submitted', 'url': 'https://git.example/owner/repo/issues/1', 'attachment_status': 'uploaded'}
|
|
runner = IncidentRunner(tmp_path, service or Service(), analyzer, publisher or publish)
|
|
# These model/admission unit tests use a fake native executor. Keep its
|
|
# saved result, and explicitly supply the independent acceptance boundary
|
|
# rather than allowing saved counters alone to certify resolution.
|
|
from unittest.mock import patch
|
|
class IndependentAcceptance:
|
|
def __init__(self, root, run_id, stop):
|
|
self.root, self.stop, self.tasks, self.results = Path(root), stop, {}, {}
|
|
def __enter__(self):
|
|
return self
|
|
def before_task(self, child, task_id, *, existing_only=False):
|
|
assert existing_only, 'A repair must reuse its original baseline'
|
|
self.tasks[task_id] = {'plan': {'rows': []}}
|
|
def after_task(self, task_id, **options):
|
|
path = self.root / 'fixture-independent-acceptance.json'
|
|
status = 'verified' if not self.stop.is_set() and options['execution_state'] == 'completed' else 'cancelled'
|
|
self.results[task_id] = {'status': status, 'verified': status == 'verified', 'report_path': str(path)}
|
|
path.write_text(json.dumps(self.results[task_id]), encoding='utf-8')
|
|
def finish(self):
|
|
return self.results
|
|
def __exit__(self, *args):
|
|
pass
|
|
original = runner.run
|
|
def run_with_acceptance(*args, **kwargs):
|
|
with patch('dx_productivity.trial_task_center.netlist_verification.NetlistVerification', IndependentAcceptance):
|
|
return original(*args, **kwargs)
|
|
runner.run = run_with_acceptance
|
|
return runner
|
|
|
|
|
|
def test_verified_repair_runs_once_and_duplicate_does_not_repeat(tmp_path):
|
|
service = Service()
|
|
runner = make_runner(tmp_path, service)
|
|
first = runner.run('t', 'worker_error', 'failure', run_id='run1', execution_authorized=True)
|
|
assert first['status'] == 'resolved'
|
|
assert service.calls == ['prepare', 'execute']
|
|
second = make_runner(tmp_path, service).run('t', 'worker_error', 'failure', run_id='run1', execution_authorized=True)
|
|
assert second['incident_id'] == first['incident_id']
|
|
assert service.calls == ['prepare', 'execute']
|
|
assert first['verification']['failed_items'] == 0
|
|
assert first['gates']['failure_policy']['category'] == 'transient'
|
|
decisions = (tmp_path / 'dsh' / 'decisions.jsonl').read_text(encoding='utf8').splitlines()
|
|
assert decisions
|
|
assert json.loads(decisions[-1])['incident_id'] == first['incident_id']
|
|
|
|
|
|
def test_uncertain_results_never_replay_even_when_model_requests_retry(tmp_path):
|
|
service = Service(interrupted=True)
|
|
result = make_runner(tmp_path, service).run('t', 'worker_error', 'failure', execution_authorized=True)
|
|
assert not service.calls
|
|
assert result['status'] == 'escalated'
|
|
assert result['ticket']['status'] == 'submitted'
|
|
|
|
|
|
def test_failed_retry_is_not_reported_as_resolved_and_reflection_is_saved(tmp_path):
|
|
service = Service(fixed=False)
|
|
phases = []
|
|
def model(incident, snapshot, evidence, phase):
|
|
phases.append(phase)
|
|
return analyze()
|
|
result = make_runner(tmp_path, service, model).run('t', 'worker_error', 'failure', execution_authorized=True)
|
|
assert service.calls == ['prepare', 'execute']
|
|
assert phases == ['diagnose', 'reflect']
|
|
assert result['status'] == 'escalated'
|
|
assert (Path(result['evidence_dir']) / 'reflect.json').is_file()
|
|
|
|
|
|
def test_unknown_error_or_unapproved_run_never_executes(tmp_path):
|
|
for code, authorized in [('unknown_error', True), ('worker_error', False)]:
|
|
service = Service()
|
|
result = make_runner(tmp_path / code, service).run('t', code, 'failure', execution_authorized=authorized)
|
|
assert not service.calls
|
|
assert result['status'] == 'escalated'
|
|
|
|
|
|
def test_model_failure_and_git_failure_preserve_evidence_and_outbox(tmp_path):
|
|
def model(*args): raise TimeoutError('model timed out')
|
|
def publish(*args): raise OSError('network down')
|
|
result = make_runner(tmp_path, analyzer=model, publisher=publish).run('t', 'worker_error', 'failure')
|
|
assert result['status'] == 'pending_issue'
|
|
directory = Path(result['evidence_dir'])
|
|
assert (directory / 'issue.md').is_file()
|
|
assert (directory / 'evidence.zip').is_file()
|
|
manifest = json.loads((directory / 'manifest.json').read_text(encoding='utf8'))
|
|
assert manifest['sha256']
|
|
assert result['ticket']['status'] == 'failed'
|
|
|
|
|
|
def test_model_cannot_invent_actions_or_claim_resolution(tmp_path):
|
|
def model(*args): return {'reply': '{"summary":"solved","action":"shell","resolved":true}'}
|
|
service = Service()
|
|
result = make_runner(tmp_path, service, model).run('t', 'worker_error', 'failure', execution_authorized=True)
|
|
assert service.calls == ['prepare', 'execute']
|
|
assert result['status'] == 'resolved'
|
|
|
|
|
|
def test_stop_request_prevents_retry_and_sensitive_text_is_redacted(tmp_path):
|
|
stop = Event(); stop.set()
|
|
service = Service()
|
|
result = make_runner(tmp_path, service).run('t', 'worker_error',
|
|
'Authorization: Bearer exampleCredential123 sk-testSecretCredential123', execution_authorized=True, stop_event=stop)
|
|
assert not service.calls
|
|
with zipfile.ZipFile(Path(result['evidence_dir']) / 'evidence.zip') as archive:
|
|
text = b'\n'.join(archive.read(n) for n in archive.namelist())
|
|
assert b'exampleCredential123' not in text
|
|
assert b'sk-testSecretCredential123' not in text
|
|
|
|
|
|
def test_publish_pending_reuses_existing_incident_without_ai_or_execution(tmp_path):
|
|
result = make_runner(tmp_path, publisher=lambda *a: {'status': 'unavailable'}).run('t', 'unknown', 'failure')
|
|
assert result['status'] == 'pending_issue'
|
|
runner = make_runner(tmp_path, analyzer=lambda *a: (_ for _ in ()).throw(AssertionError('must not rediagnose')))
|
|
retried = runner.publish_pending(result['incident_id'])
|
|
assert retried['status'] == 'escalated'
|
|
|
|
|
|
def test_incomplete_persisted_attempt_is_not_reexecuted(tmp_path):
|
|
result = make_runner(tmp_path).run('t', 'worker_error', 'failure', run_id='run1')
|
|
path = Path(result['evidence_dir']) / 'incident.json'
|
|
row = json.loads(path.read_text(encoding='utf8')); row['status'] = 'retrying'
|
|
path.write_text(json.dumps(row), encoding='utf8')
|
|
service = Service()
|
|
same = make_runner(tmp_path, service).run('t', 'worker_error', 'failure', run_id='run1', execution_authorized=True)
|
|
assert not service.calls
|
|
assert same['status'] == 'pending_issue'
|
|
|
|
|
|
def test_native_human_readable_diagnosis_retains_validated_decision():
|
|
value = decision('## 结论\n建议按规则重试。\n\n```json\n{"action":"retry_failed"}\n```')
|
|
assert value['action'] == 'retry_failed'
|
|
assert '建议按规则重试' in value['summary']
|
|
|
|
|
|
def test_different_error_codes_share_one_retry_budget_for_original_run(tmp_path):
|
|
service = Service(fixed=False)
|
|
runner = make_runner(tmp_path, service)
|
|
first = runner.run('t', 'worker_error', 'first failure', execution_authorized=True, run_id='original')
|
|
assert first['attempts'] == 1
|
|
service.progress = NS(**(vars(service.progress) | {'queue_complete': True}))
|
|
second = runner.run('t', 'execution_failed', 'same run, different code', execution_authorized=True, run_id='original')
|
|
assert second['attempts'] == 0
|
|
assert service.calls == ['prepare', 'execute']
|
|
|
|
|
|
def test_model_explanation_cannot_retroactively_revoke_completed_safe_retry(tmp_path):
|
|
permission, stop = Event(), Event()
|
|
permission.set()
|
|
service = Service()
|
|
def model(*args):
|
|
permission.clear()
|
|
return analyze()
|
|
result = make_runner(tmp_path, service, model).run('t', 'worker_error', 'failure',
|
|
execution_authorized=True, stop_event=stop, execution_enabled=permission)
|
|
assert service.calls == ['prepare', 'execute']
|
|
assert not stop.is_set()
|
|
assert result['gates']['auto_intervention_enabled'] is True
|
|
assert (Path(result['evidence_dir']) / 'evidence.zip').is_file()
|
|
|
|
|
|
@pytest.mark.parametrize('model_result', ['unavailable', 'declines'])
|
|
def test_durable_retry_runs_before_unavailable_or_declining_model(tmp_path, model_result):
|
|
service = Service()
|
|
def model(*args):
|
|
assert service.calls == ['prepare', 'execute']
|
|
if model_result == 'unavailable':
|
|
raise TimeoutError('offline')
|
|
return {'reply': json.dumps({'summary': 'No model action', 'action': 'none'})}
|
|
result = make_runner(tmp_path, service, model).run('t', 'worker_error', 'failure',
|
|
execution_authorized=True)
|
|
assert result['status'] == 'resolved'
|
|
assert service.reserved and result['attempts'] == 1
|
|
|
|
|
|
def test_disabling_at_prepare_boundary_prevents_execution(tmp_path):
|
|
permission = Event()
|
|
permission.set()
|
|
service = Service()
|
|
prepare = service.prepare_failed_quick_run
|
|
def prepare_and_disable(task_id, **kwargs):
|
|
prepare(task_id, **kwargs)
|
|
permission.clear()
|
|
service.prepare_failed_quick_run = prepare_and_disable
|
|
result = make_runner(tmp_path, service).run('t', 'worker_error', 'failure',
|
|
execution_authorized=True, execution_enabled=permission)
|
|
assert service.calls == ['prepare']
|
|
assert result['status'] == 'escalated'
|
|
assert result['retry_error']['detail'] == 'retry_execution_gate_changed'
|
|
|
|
|
|
class ResourceService(Service):
|
|
def __init__(self, *, remains=False, error=False, reread_error=False):
|
|
super().__init__()
|
|
self.pending = [{'session_id': 'owned-session', 'state': 'blocked'}]
|
|
self.remains, self.error, self.reread_error = remains, error, reread_error
|
|
self.pending_reads = 0
|
|
|
|
def pending_batch_resources(self):
|
|
self.pending_reads += 1
|
|
if self.reread_error and self.calls:
|
|
raise OSError('resource evidence unavailable')
|
|
return tuple(self.pending)
|
|
|
|
def cleanup_batch_resources(self):
|
|
self.calls.append('cleanup')
|
|
if self.error:
|
|
raise OSError('release failed')
|
|
if not self.remains:
|
|
self.pending.clear()
|
|
return () # A claimed empty result must be verified independently.
|
|
|
|
|
|
def cleanup_model(*args):
|
|
return {'reply': json.dumps({'summary': '核验并释放自有资源', 'action': 'cleanup_resources'})}
|
|
|
|
|
|
def test_resource_cleanup_is_verified_without_cad_authorization_or_replay(tmp_path):
|
|
service = ResourceService()
|
|
snapshots = []
|
|
def model(incident, snapshot, evidence, phase):
|
|
snapshots.append(snapshot)
|
|
return cleanup_model()
|
|
runner = make_runner(tmp_path, service, model)
|
|
result = runner.run('t', 'batch_resources_pending', 'release pending', cleanup_allowed=True,
|
|
snapshot_override={'task_id': 't', 'status': 'blocked'})
|
|
assert result['status'] == 'resolved'
|
|
assert service.calls == ['cleanup']
|
|
assert service.pending_reads >= 2
|
|
assert result['attempts'] == 0
|
|
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'))
|
|
assert cleanup['returned_resources'] == []
|
|
assert cleanup['remaining_resources'] == []
|
|
audit = json.loads((tmp_path / 'dsh' / 'decisions.jsonl').read_text(encoding='utf8').splitlines()[-1])
|
|
assert audit['candidate_action'] == 'cleanup_resources'
|
|
runner.run('t', 'batch_resources_pending', 'release pending', cleanup_allowed=True)
|
|
assert service.calls == ['cleanup']
|
|
|
|
|
|
@pytest.mark.parametrize('remains,error,reread_error', [(True, False, False), (False, True, False), (False, False, True)])
|
|
def test_cleanup_missing_or_negative_verification_escalates_with_evidence(tmp_path, remains, error, reread_error):
|
|
service = ResourceService(remains=remains, error=error, reread_error=reread_error)
|
|
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 (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:
|
|
assert cleanup['remaining_resources'][0]['session_id'] == 'owned-session'
|
|
if error:
|
|
assert cleanup['error']['type'] == 'OSError'
|
|
if reread_error:
|
|
assert cleanup['verification_error']['type'] == 'OSError'
|
|
assert result['verification']['remaining_resources'] is None
|
|
assert (directory / 'reflect.json').is_file()
|
|
assert (directory / 'evidence.zip').is_file()
|
|
|
|
|
|
@pytest.mark.parametrize('code,allowed,action,disabled,stopped', [
|
|
('worker_error', True, 'cleanup_resources', False, False),
|
|
('batch_resources_pending', False, 'cleanup_resources', False, False),
|
|
('batch_resources_pending', True, 'none', False, False),
|
|
('batch_resources_pending', True, 'cleanup_resources', True, False),
|
|
('batch_resources_pending', True, 'cleanup_resources', False, True),
|
|
])
|
|
def test_cleanup_permission_code_model_and_current_controls_are_required(tmp_path, code, allowed, action, disabled, stopped):
|
|
service = ResourceService()
|
|
permission, stop = Event(), Event()
|
|
permission.set()
|
|
def model(*args):
|
|
if disabled:
|
|
permission.clear()
|
|
if stopped:
|
|
stop.set()
|
|
return {'reply': json.dumps({'summary': 'diagnosis', 'action': action})}
|
|
result = make_runner(tmp_path, service, model).run('t', code, 'failure', cleanup_allowed=allowed,
|
|
execution_enabled=permission, stop_event=stop)
|
|
assert not service.calls
|
|
assert result['status'] == 'escalated'
|
|
|
|
|
|
def test_cached_stall_snapshot_never_reads_live_context_and_preserves_bounded_redacted_trigger(tmp_path):
|
|
service = Service()
|
|
def forbidden(*args):
|
|
service.calls.append('task_context')
|
|
raise AssertionError('task_context must never be called for cached snapshots')
|
|
service.task_context = forbidden
|
|
seen = []
|
|
def model(incident, snapshot, evidence, phase):
|
|
seen.append((snapshot, evidence, phase))
|
|
return analyze()
|
|
trigger = {'operation': 'poll', 'reason': 'Authorization: Bearer exampleCredential123',
|
|
'detail': 'x' * 50000, 'samples': list(range(1000))}
|
|
cached = {'task_id': 't', 'status': 'running', 'progress': {'failed_items': 1}, 'task_name': 'cached task'}
|
|
result = make_runner(tmp_path, service, model).run('t', 'operation_stalled', 'no progress',
|
|
execution_authorized=True, trigger=trigger, snapshot_override=cached)
|
|
assert not service.calls
|
|
assert result['status'] == 'escalated'
|
|
assert [item[2] for item in seen] == ['diagnose', 'reflect']
|
|
assert all(item[0]['task_name'] == 'cached task' for item in seen)
|
|
assert all('trigger' in item[0] for item in seen)
|
|
assert all('exampleCredential123' not in item[1] for item in seen)
|
|
directory = Path(result['evidence_dir'])
|
|
payload = (directory / 'trigger.json').read_text(encoding='utf8')
|
|
assert len(payload) < 20000
|
|
assert 'exampleCredential123' not in payload
|
|
assert json.loads(payload)['operation'] == 'poll'
|
|
assert 'context_error' not in json.loads((directory / 'snapshot-after.json').read_text(encoding='utf8'))
|
|
|
|
|
|
def test_revoking_cleanup_permission_at_notification_boundary_prevents_mutation(tmp_path):
|
|
permission = Event()
|
|
permission.set()
|
|
service = ResourceService()
|
|
runner = make_runner(tmp_path, service, cleanup_model)
|
|
def notify(record):
|
|
if record.get('cleanup_attempts'):
|
|
permission.clear()
|
|
runner.notify = notify
|
|
result = runner.run('t', 'batch_resources_pending', 'pending', cleanup_allowed=True,
|
|
execution_enabled=permission)
|
|
assert service.calls == []
|
|
assert result['status'] == 'escalated'
|
|
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'
|
|
|
|
|
|
def test_cleanup_failure_with_unavailable_publisher_remains_in_outbox(tmp_path):
|
|
service = ResourceService(error=True)
|
|
result = make_runner(tmp_path, service, cleanup_model, publisher=lambda *args: {'status': 'unavailable'}).run(
|
|
't', 'batch_resources_pending', 'pending', cleanup_allowed=True)
|
|
assert result['status'] == 'pending_issue'
|
|
directory = Path(result['evidence_dir'])
|
|
assert (directory / 'issue.md').is_file()
|
|
with zipfile.ZipFile(directory / 'evidence.zip') as archive:
|
|
cleanup = json.loads(archive.read('cleanup.json'))
|
|
assert cleanup['error']['type'] == 'OSError'
|
|
assert cleanup['remaining_resources'][0]['session_id'] == 'owned-session'
|
|
|
|
|
|
@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'
|