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

This commit is contained in:
阿白叔 committed 2026-11-05 11:58:32 +08:00
1 parent de9cb2908d
commit 775bc23dc3
26 files changed
+1280 -119

No files matched your search

+259 -8
View File
@@ -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'