Merge remote-tracking branch 'origin/main' into HEAD

This commit is contained in:
阿白叔 committed 2026-11-03 10:42:21 +08:00
commit e9454cf01f
104 files changed
+8458 -100

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
import pytest
def settings():
from dx_productivity.dsh.assistant_settings import load_settings, save_settings
return load_settings, save_settings
def test_settings_are_bounded_persistent_and_do_not_accept_credentials(tmp_path):
load, save = settings()
assert load(tmp_path)['response_timeout_seconds'] == 90
value = save(tmp_path, {'response_timeout_seconds': 120, 'model_context_limit': 12000})
assert load(tmp_path) == value
for invalid in [{'response_timeout_seconds': 1}, {'api_key': 'do-not-persist'}, {'model_context_limit': True}]:
with pytest.raises(ValueError):
save(tmp_path, invalid)
+67
View File
@@ -0,0 +1,67 @@
from pathlib import Path
from types import SimpleNamespace as NS
import pytest
from dx_productivity.dsh.cad_verification import CadVerificationAdapter
from test_run_journal import project_service, evidence
def service(tmp_path, *, probe=True, interrupted=False):
project = tmp_path / 'board.prj'; project.write_text('KEY FrontEndSnapshot "DxD"\n', encoding='utf8')
probe_path = tmp_path / 'probe.json'
if probe: probe_path.write_text('{"project":"board"}', encoding='utf8')
class Service:
def task_context(self, task_id):
return NS(task=NS(task_id=task_id, status=NS(value='ready')), project=NS(path=project, project_id='p1'),
progress=NS(saved_items=1, failed_items=0, no_match_items=0, queue_complete=True),
interrupted=interrupted, phase='complete')
def expected_probe_path(self, task_id, project_id=None): return probe_path
return Service(), project
def test_adapter_reports_real_project_and_probe_identity(tmp_path):
svc, project = service(tmp_path)
result = CadVerificationAdapter(svc).preflight(['task-1'])
assert result['status'] == 'ready' and result['mode'] == 'task_center_native'
assert result['projects'][0]['path'] == str(project)
assert result['projects'][0]['probe_available'] is True
assert result['evidence_refs']
def test_adapter_blocks_missing_probe_and_uncertain_result(tmp_path):
svc, _ = service(tmp_path, probe=False, interrupted=True)
result = CadVerificationAdapter(svc).preflight(['task-1'])
assert result['status'] == 'blocked'
assert 'probe_baseline_missing' in result['blockers']
after = CadVerificationAdapter(svc).after_run(['task-1'])
assert after['status'] == 'uncertain' and after['tasks'][0]['interrupted'] is True
def test_adapter_rejects_missing_task_without_inventing_counts(tmp_path):
svc, _ = service(tmp_path)
svc.task_context = lambda task_id: (_ for _ in ()).throw(KeyError(task_id))
result = CadVerificationAdapter(svc).preflight(['missing'])
assert result['status'] == 'blocked'
assert result['projects'][0]['component_count'] is None
@pytest.mark.parametrize('state,blocker', [('batch_failed', 'failed_items'), (None, 'queue_incomplete')])
def test_after_run_requires_successful_complete_evidence(project_service, state, blocker):
service, _, _, ids, _ = project_service
if state:
evidence(service, ids[0], state)
context = service.task_context(ids[0])
assert context.progress.failed_items == (1 if state else 0)
assert not context.interrupted
result = CadVerificationAdapter(service).after_run(ids[:1])
assert result['status'] == 'uncertain'
assert blocker in result['blockers']
def test_after_run_keeps_verified_no_match_distinct_from_saved(project_service):
service, _, _, ids, _ = project_service
evidence(service, ids[0])
result = CadVerificationAdapter(service).after_run(ids[:1])
assert result['status'] == 'ready' and result['blockers'] == []
assert result['tasks'][0]['saved_items'] == 0 and result['tasks'][0]['no_match_items'] == 1
+130
View File
@@ -0,0 +1,130 @@
import json
from concurrent.futures import ThreadPoolExecutor
from hashlib import sha256
import pytest
from dx_productivity.dsh.decision_log import DecisionLog
def _row(incident='a' * 24, outcome='pending_issue'):
return {'incident_id': incident, 'trigger': 'execution_failed', 'evidence_refs': ['dsh/incidents/x/gates.json'],
'gates': {'execution_authorized': True, 'retry_budget_available': False},
'candidate_action': 'none', 'authorized_scope': {'task_ids': ['task-1']}, 'outcome': outcome,
'human_takeover': False}
def test_decision_log_is_hash_linked_and_survives_restart(tmp_path):
store = DecisionLog(tmp_path)
first = store.append(_row())
second = DecisionLog(tmp_path).append(_row('b' * 24, 'resolved'))
assert first['sequence'] == 1
assert second['previous_hash'] == first['record_hash']
assert DecisionLog(tmp_path).verify()['valid'] is True
assert [row['sequence'] for row in DecisionLog(tmp_path).list()] == [1, 2]
def test_decision_log_detects_tampering_and_bounds_text(tmp_path):
store = DecisionLog(tmp_path)
store.append(_row())
path = tmp_path / 'dsh' / 'decisions.jsonl'
raw = path.read_text(encoding='utf8').replace('execution_failed', 'x' * 5000)
path.write_text(raw, encoding='utf8')
assert DecisionLog(tmp_path).verify()['valid'] is False
with pytest.raises(ValueError, match='incident_id'):
store.append(_row('bad'))
def _seal(record):
body = {key: value for key, value in record.items() if key != 'record_hash'}
payload = json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
return body | {'record_hash': sha256(payload.encode('utf8')).hexdigest()}
@pytest.fixture
def long_log(tmp_path):
# Seed a valid historical log without thousands of quadratic append calls.
path = tmp_path / 'dsh' / 'decisions.jsonl'
path.parent.mkdir()
previous = ''
with path.open('w', encoding='utf8') as stream:
for sequence in range(1, 2002):
last = _seal(_row() | {'sequence': sequence, 'at_utc': '2026-10-31T00:00:00+00:00',
'previous_hash': previous})
stream.write(json.dumps(last) + '\n')
previous = last['record_hash']
return DecisionLog(tmp_path), last
def test_append_after_2000_records_uses_actual_tail_and_verifies_entire_chain(long_log):
store, previous = long_log
result = store.append(_row('b' * 24))
assert result['sequence'] == 2002
assert result['previous_hash'] == previous['record_hash']
reopened = DecisionLog(store.path.parent.parent)
assert reopened.verify() == {'valid': True, 'checked': 2002, 'last_hash': result['record_hash']}
def test_verify_detects_tampering_past_2000_records(long_log):
store, last = long_log
lines = store.path.read_text(encoding='utf8').splitlines()
lines[-1] = json.dumps(last | {'outcome': 'resolved'})
store.path.write_text('\n'.join(lines) + '\n', encoding='utf8')
assert store.verify(sequence=2000)['valid'] is True
result = store.verify()
assert result['valid'] is False and result['checked'] == 2000
before = store.path.read_bytes()
with pytest.raises(ValueError, match='decision_log_corrupt'):
store.append(_row('b' * 24))
assert store.path.read_bytes() == before
def test_verify_rejects_duplicate_sequence_even_with_valid_hash_links(long_log):
store, last = long_log
duplicate = _seal(last | {'previous_hash': last['record_hash']})
with store.path.open('a', encoding='utf8') as stream:
stream.write(json.dumps(duplicate) + '\n')
result = store.verify()
assert result['valid'] is False and result['checked'] == 2001
@pytest.mark.parametrize('tail', ['{incomplete', '{"incident_id":', '[]\n', '\n'])
def test_corrupt_tail_is_reported_and_append_preserves_original_bytes(tmp_path, tail):
store = DecisionLog(tmp_path)
store.append(_row())
with store.path.open('a', encoding='utf8') as stream:
stream.write(tail)
before = store.path.read_bytes()
assert store.verify()['valid'] is False
with pytest.raises(ValueError, match='decision_log_corrupt'):
store.list()
with pytest.raises(ValueError, match='decision_log_corrupt'):
store.append(_row('b' * 24))
assert store.path.read_bytes() == before
def test_listing_remains_bounded_and_shows_recent_records(long_log):
store, _ = long_log
assert [row['sequence'] for row in store.list(limit=3)] == [1999, 2000, 2001]
assert len(store.list(limit=100000)) == 2000
def test_append_after_complete_json_without_newline_keeps_records_separate(tmp_path):
store = DecisionLog(tmp_path)
first = store.append(_row())
store.path.write_bytes(store.path.read_bytes().rstrip(b'\r\n'))
second = store.append(_row('b' * 24))
assert len(store.path.read_text(encoding='utf8').splitlines()) == 2
assert second['previous_hash'] == first['record_hash']
assert store.verify()['checked'] == 2 and store.verify()['valid'] is True
def test_concurrent_instances_append_one_ordered_chain(tmp_path):
def append(index):
return DecisionLog(tmp_path).append(_row(f'{index:024x}'))
with ThreadPoolExecutor(max_workers=4) as pool:
results = list(pool.map(append, range(20)))
assert sorted(row['sequence'] for row in results) == list(range(1, 21))
assert DecisionLog(tmp_path).verify()['valid'] is True
assert DecisionLog(tmp_path).verify()['checked'] == 20
+194
View File
@@ -0,0 +1,194 @@
"""Original queue recovery across a fatal receipt-write boundary."""
from pathlib import Path
import subprocess
from threading import Event
import pytest
from dx_productivity.dsh.execution_runs import execute_confirmed_run
from dx_productivity.dsh.run_journal import RunJournal
from dx_productivity.dsh.task_lifecycle import preflight
from test_run_journal import project_service
from test_run_journal import checkpoint, evidence
def _pause_then_fail_completed_checkpoint(project_service, monkeypatch, *, before_failure=None):
from dx_productivity.trial_task_center import task_queue
service, _, data, ids, _ = project_service
calls = []
stop = Event()
def worker(command, timeout):
queue, job = Path(command[3]), command[-1]
calls.append(next(key for key in ids if key in queue.parts))
with (queue / 'status.tsv').open('a', encoding='utf8') as stream:
stream.write(f'{job}\tno_match\tbatch_closed\tControlled verified no match\n')
if len(calls) == 1:
stop.set()
return subprocess.CompletedProcess(command, 0, '', '')
for task_id in ids:
preparer = service.for_project_task(task_id)._quick_run_preparer
preparer._process_runner = worker
preparer._cscript_resolver = lambda: Path('cscript.exe')
run_id = 'f' * 32
first = execute_confirmed_run(service, data, ids, preflight(service, ids), stop, run_id)
assert first['status'] == 'paused' and calls == ids[:1]
original = RunJournal(data).inspect(service, run_id)
save = task_queue._save
def fail_completed(path, state):
if state['entries'][ids[1]]['state'] == 'completed':
if before_failure:
before_failure(service, ids)
raise OSError('controlled completed checkpoint publication failure')
save(path, state)
with monkeypatch.context() as patch:
patch.setattr(task_queue, '_save', fail_completed)
with pytest.raises(OSError, match='checkpoint publication failure'):
execute_confirmed_run(service, data, ids, preflight(service, ids, allow_completed=True),
Event(), run_id, resume=original)
assert calls == ids[:2]
return run_id, first, calls
def test_resume_after_verified_progress_and_checkpoint_io_failure_runs_each_task_once(project_service, monkeypatch):
service, _, data, ids, _ = project_service
run_id, first, calls = _pause_then_fail_completed_checkpoint(project_service, monkeypatch)
restarted = RunJournal(data).inspect(service, run_id)
assert restarted['status'] == 'interrupted'
assert restarted['checkpoint_states'][ids[1]] == 'running'
assert restarted['resume_ready'], restarted['blockers']
result = restarted['result']
old_terminal = next(row for row in result['tasks'] if row['task_id'] == ids[0])
assert old_terminal == next(row for row in first['tasks'] if row['task_id'] == ids[0])
advanced = next(row for row in result['tasks'] if row['task_id'] == ids[1])
assert advanced['no_match_items'] == 1 and advanced['queue_complete'] is True
last = execute_confirmed_run(service, data, ids, preflight(service, ids, allow_completed=True),
Event(), run_id, resume=restarted)
assert last['status'] == 'completed' and last['queue_id'] == run_id
assert calls == ids
assert all(row['no_match_items'] == 1 and row['failed_items'] == 0 for row in last['tasks'])
@pytest.mark.parametrize('task_index', [0, 1, 2])
def test_soft_failure_snapshot_does_not_allow_evidence_changes_while_stopped(project_service, monkeypatch, task_index):
service, _, data, ids, _ = project_service
run_id, _, _ = _pause_then_fail_completed_checkpoint(project_service, monkeypatch)
if task_index == 2:
evidence(service, ids[task_index])
else:
root = service.for_project_task(ids[task_index])._quick_run_preparer.data_root / 'quick-run'
(root / 'status.tsv').write_text('job_id\tstate\tcode\tmessage\n', encoding='utf8')
restarted = RunJournal(data).inspect(service, run_id)
assert not restarted['resume_ready'] and 'evidence_changed' in restarted['blockers']
@pytest.mark.parametrize('fault', ['old_terminal', 'failed_result', 'uncertain_result'])
def test_checkpoint_failure_does_not_adopt_unsafe_evidence_as_new_baseline(project_service, monkeypatch, fault):
service, _, data, ids, _ = project_service
def corrupt(service, ids):
if fault == 'old_terminal':
root = service.for_project_task(ids[0])._quick_run_preparer.data_root / 'quick-run'
(root / 'status.tsv').write_text('job_id\tstate\tcode\tmessage\n', encoding='utf8')
else:
evidence(service, ids[1], 'batch_failed' if fault == 'failed_result' else 'batch_saved_unverified', '')
run_id, first, _ = _pause_then_fail_completed_checkpoint(project_service, monkeypatch, before_failure=corrupt)
restarted = RunJournal(data).inspect(service, run_id)
assert not restarted['resume_ready']
assert restarted['result']['tasks'] == first['tasks']
assert 'evidence_changed' in restarted['blockers']
def test_failed_exception_readback_keeps_original_error_and_baseline(project_service, monkeypatch):
service, _, data, _, _ = project_service
inspect = RunJournal.inspect
failing = False
def unavailable(self, *args, **kwargs):
if failing:
raise RuntimeError('controlled readback failure')
return inspect(self, *args, **kwargs)
def start_failing(_service, _ids):
nonlocal failing
failing = True
with monkeypatch.context() as patch:
patch.setattr(RunJournal, 'inspect', unavailable)
run_id, first, _ = _pause_then_fail_completed_checkpoint(project_service, monkeypatch,
before_failure=start_failing)
restarted = RunJournal(data).inspect(service, run_id)
assert restarted['result']['tasks'] == first['tasks']
assert restarted['result']['entries'] == first['entries']
assert not restarted['resume_ready'] and 'evidence_changed' in restarted['blockers']
def test_second_resume_after_fatal_exit_preserves_verified_progress_and_runs_each_task_once(project_service, monkeypatch):
service, _, data, ids, _ = project_service
calls = []
active = {'stop': Event(), 'pause': True}
def worker(command, timeout):
queue, job = Path(command[3]), command[-1]
calls.append(next(key for key in ids if key in queue.parts))
with (queue / 'status.tsv').open('a', encoding='utf8') as stream:
stream.write(f'{job}\tno_match\tbatch_closed\tControlled verified no match\n')
if active['pause']:
active['stop'].set()
return subprocess.CompletedProcess(command, 0, '', '')
for task_id in ids:
preparer = service.for_project_task(task_id)._quick_run_preparer
preparer._process_runner = worker
preparer._cscript_resolver = lambda: Path('cscript.exe')
run_id = 'd' * 32
first = execute_confirmed_run(service, data, ids, preflight(service, ids), active['stop'], run_id)
assert first['status'] == 'paused' and calls == ids[:1]
original = RunJournal(data).inspect(service, run_id)
active['stop'] = Event()
class FatalExit(BaseException):
pass
with monkeypatch.context() as patch:
def fatal_finish(*args, **kwargs):
raise FatalExit('exit after checkpoint, before final receipt')
patch.setattr(RunJournal, 'finish', fatal_finish)
with pytest.raises(FatalExit):
execute_confirmed_run(service, data, ids, preflight(service, ids, allow_completed=True),
active['stop'], run_id, resume=original)
assert calls == ids[:2]
restarted = RunJournal(data).inspect(service, run_id)
assert restarted['status'] == 'running' and restarted['resume_ready'], restarted['blockers']
assert restarted['remaining_task_ids'] == ids[2:]
active.update(stop=Event(), pause=False)
last = execute_confirmed_run(service, data, ids, preflight(service, ids, allow_completed=True),
active['stop'], run_id, resume=restarted)
assert last['status'] == 'completed' and last['queue_id'] == run_id
assert calls == ids
assert all(task['saved_items'] == 0 and task['no_match_items'] == 1 for task in last['tasks'])
def test_resume_soft_failure_retains_the_last_evidence_baseline(project_service, monkeypatch):
service, _, data, ids, hashes = project_service
journal = RunJournal(data)
run_id = 'e' * 32
journal.begin(run_id, ids, hashes)
checkpoint(data, run_id, ids, hashes)
prior = {'status': 'paused', 'tasks': [{'task_id': ids[0], 'saved_items': 0, 'failed_items': 0,
'no_match_items': 0, 'queue_complete': False, 'interrupted': False}],
'entries': [{'task_id': key, 'state': 'paused' if key == ids[0] else 'pending'} for key in ids]}
journal.finish(run_id, prior)
resume = journal.inspect(service, run_id)
def unavailable(*args, **kwargs):
raise OSError('controlled queue failure before progress')
monkeypatch.setattr('dx_productivity.dsh.execution_runs.execute_task_queue', unavailable)
with pytest.raises(OSError):
execute_confirmed_run(service, data, ids, preflight(service, ids), Event(), run_id, resume=resume)
result = journal.get(run_id)['result']
assert result['status'] == 'interrupted'
assert result['tasks'] == prior['tasks'] and result['entries'] == prior['entries']
evidence(service, ids[0])
inspected = journal.inspect(service, run_id)
assert inspected['diff']['evidence_baseline_available']
assert 'evidence_changed' in inspected['blockers']
+149
View File
@@ -0,0 +1,149 @@
import json
import pytest
from dx_productivity.dsh.experience import ExperienceStore
def incident(root, identity='a' * 24, *, verification=None, evidence=True, **values):
directory = root / 'dsh' / 'incidents' / identity
directory.mkdir(parents=True)
record = {'incident_id': identity, 'task_id': 'task-1', 'issue_code': 'worker_error',
'message': 'Authorization: Bearer sensitiveExample123', 'status': 'resolved',
'analyses': [{'reply': 'sk-sensitiveCredential123 repaired'}], **values}
(directory / 'incident.json').write_text(json.dumps(record), encoding='utf8')
if verification is not None:
(directory / 'verification.json').write_text(json.dumps(verification), encoding='utf8')
if evidence:
(directory / 'snapshot.json').write_text('{"task_id":"task-1"}', encoding='utf8')
return directory
GOOD = {'queue_complete': True, 'failed_items': 0, 'interrupted': False, 'paused': False,
'saved_items': 1, 'completed_items': 1}
def test_unchanged_refresh_does_not_rewrite_index_and_evidence_changes_invalidate(tmp_path):
import os
directory = incident(tmp_path, verification=GOOD)
store = ExperienceStore(tmp_path)
assert store.refresh()[0]['verified'] is True
index = tmp_path / 'dsh/experience/index.json'
os.utime(index, ns=(1000000000, 1000000000))
before = index.stat().st_mtime_ns
assert store.refresh()[0]['verified'] is True
assert index.stat().st_mtime_ns == before
(directory / 'verification.json').write_text(json.dumps(GOOD | {'failed_items': 1}), encoding='utf8')
assert store.refresh()[0]['verified'] is False
assert index.stat().st_mtime_ns != before
def test_verified_experience_requires_persisted_verification_and_evidence(tmp_path):
incident(tmp_path, verification=GOOD)
store = ExperienceStore(tmp_path)
rows = store.refresh()
assert rows[0]['verified'] is True
assert rows[0]['verification'] == GOOD
assert any(ref.endswith('/verification.json') for ref in rows[0]['evidence_refs'])
assert 'sensitive' not in json.dumps(rows)
assert ExperienceStore(tmp_path).search('worker_error') == rows
assert store.summary()['verified'] == 1
@pytest.mark.parametrize('changes', [{'failed_items': 1}, {'queue_complete': False},
{'interrupted': True}, {'paused': True}, {'failed_items': False}])
def test_unsuccessful_or_malformed_verification_is_not_verified(tmp_path, changes):
incident(tmp_path, verification=GOOD | changes)
assert ExperienceStore(tmp_path).refresh()[0]['verified'] is False
def test_model_claim_closed_ticket_inline_verification_and_missing_evidence_are_not_proof(tmp_path):
incident(tmp_path, 'a' * 24, verification=GOOD, evidence=False)
incident(tmp_path, 'b' * 24, verification=None, ticket={'state': 'closed'}, verification_claim=GOOD)
assert not any(row['verified'] for row in ExperienceStore(tmp_path).refresh())
def test_search_is_bounded_matches_context_and_skips_bad_local_records(tmp_path):
incident(tmp_path, issue_code='save_failed', message='resource lock busy', verification=GOOD)
incident(tmp_path, 'b' * 24, issue_code='other', message='different', verification=None)
directory = tmp_path / 'dsh' / 'incidents' / ('c' * 24)
directory.mkdir(); (directory / 'incident.json').write_text('broken', encoding='utf8')
store = ExperienceStore(tmp_path); store.refresh()
assert store.search('save_failed', limit=1)[0]['issue_code'] == 'save_failed'
assert store.search('resource lock')[0]['issue_code'] == 'save_failed'
assert store.search('unrelated') == []
assert store.search(limit=0) == []
assert store.summary()['total'] == 2
def test_index_preserves_portable_evidence_refs_and_rejects_mismatched_identity(tmp_path):
incident(tmp_path, verification=GOOD)
wrong = incident(tmp_path, 'b' * 24, verification=GOOD)
record = json.loads((wrong / 'incident.json').read_text(encoding='utf8'))
record['incident_id'] = 'c' * 24
(wrong / 'incident.json').write_text(json.dumps(record), encoding='utf8')
store = ExperienceStore(tmp_path)
rows = store.refresh()
assert len(rows) == 1
assert rows[0]['evidence_refs'][0].startswith('dsh/incidents/')
assert (tmp_path / 'dsh' / 'experience' / 'index.json').is_file()
def test_oversized_incident_and_verification_are_not_read_as_trusted_evidence(tmp_path):
directory = incident(tmp_path, verification=GOOD)
(directory / 'verification.json').write_text(json.dumps(GOOD | {'extra': 'x' * 100000}), encoding='utf8')
assert ExperienceStore(tmp_path).refresh()[0]['verified'] is False
(directory / 'incident.json').write_text('x' * 1000000, encoding='utf8')
assert ExperienceStore(tmp_path).refresh() == []
def test_reusable_diagnosis_attempt_and_outcome_are_bounded_scrubbed_data(tmp_path):
directory = incident(tmp_path, verification=GOOD, attempts=1,
analyses=[{'phase': 'analyzing', 'reply': '重读保存证据,确认锁已释放。' + 'x' * 2000,
'tool_calls': [{'execute': 'must not preserve'}]},
{'phase': 'reflecting', 'reply': '下一步:人工核对封装。 sk-sensitiveCredential123'},
{'phase': 'extra', 'reply': 'omitted'}],
retry_error={'type': 'TaskCenterError', 'code': 'native_busy', 'detail': 'Authorization: Bearer sensitiveExample123'},
retry_skipped='待人工核对')
(directory / 'actions.json').write_text(json.dumps({'attempts': 1, 'verification': GOOD,
'retry_error': {'type': 'TaskCenterError', 'code': 'native_busy', 'detail': '锁仍被占用'},
'retry_skipped': '保留现场', 'execute': 'must not preserve'}), encoding='utf8')
row = ExperienceStore(tmp_path).refresh()[0]
assert row['attempts'] == 1
assert len(row['analyses']) == 2
assert row['analyses'][0]['phase'] == 'analyzing' and len(row['analyses'][0]['reply']) <= 1500
assert '下一步' in row['analyses'][1]['reply']
assert row['retry_error']['code'] == 'native_busy' and row['retry_skipped'] == '待人工核对'
assert row['actions']['attempts'] == 1 and row['actions']['retry_skipped'] == '保留现场'
assert row['actions']['retry_error']['detail'] == '锁仍被占用'
assert row['outcome']['verified'] is True and row['outcome']['saved_items'] == 1
assert 'sensitive' not in json.dumps(row)
assert 'must not preserve' not in json.dumps(row)
def test_action_claim_does_not_verify_or_grant_execution_and_oversize_actions_are_ignored(tmp_path):
directory = incident(tmp_path, verification=None, attempts=True,
analyses=[{'phase': 'reflecting', 'reply': '已修复,可执行'}])
(directory / 'actions.json').write_text(json.dumps({'attempts': 99, 'verification': GOOD,
'execute': True, 'authorized': True}), encoding='utf8')
row = ExperienceStore(tmp_path).refresh()[0]
assert row['verified'] is row['outcome']['verified'] is False
assert row['attempts'] == 0 and row['actions']['attempts'] <= 1
assert 'execute' not in row['actions'] and 'authorized' not in row['actions']
(directory / 'actions.json').write_text(json.dumps({'retry_skipped': 'x' * 40000}), encoding='utf8')
assert ExperienceStore(tmp_path).refresh()[0]['actions'] == {}
def test_search_prioritizes_verified_then_exact_code_then_newest_and_searches_diagnosis(tmp_path):
incident(tmp_path, 'a' * 24, verification=None, issue_code='save_failed',
created_utc='2026-10-30T12:00:00Z', analyses=[{'phase': 'analyzing', 'reply': '对齐元件封装'}])
incident(tmp_path, 'b' * 24, verification=GOOD, issue_code='other', message='save_failed',
created_utc='2026-10-30T13:00:00Z')
incident(tmp_path, 'c' * 24, verification=GOOD, issue_code='save_failed',
created_utc='2026-10-29T12:00:00Z')
incident(tmp_path, 'd' * 24, verification=GOOD, issue_code='save_failed',
created_utc='2026-10-30T10:00:00Z')
store = ExperienceStore(tmp_path)
assert [row['incident_id'] for row in store.search('save_failed')] == [
'd' * 24, 'c' * 24, 'b' * 24, 'a' * 24]
assert store.search('对齐元件封装')[0]['incident_id'] == 'a' * 24
+14
View File
@@ -0,0 +1,14 @@
from dx_productivity.dsh.failure_policy import classify_failure
def test_failure_policy_allows_one_authorized_transient_retry():
value = classify_failure('worker_timeout', 'failed', authorized=True)
assert value == {'category': 'transient', 'retry_allowed': True, 'reason': '可重试的临时执行错误',
'backoff_seconds': 5, 'max_attempts': 1}
def test_failure_policy_blocks_uncertain_and_deterministic_errors():
assert classify_failure('quick_run_uncertain', 'uncertain', interrupted=True)['category'] == 'uncertain'
assert classify_failure('target_identity', 'failed', authorized=True)['retry_allowed'] is False
assert classify_failure('paused', 'paused', authorized=True)['category'] == 'paused'
assert classify_failure('new_error', 'failed')['category'] == 'observe'
+39
View File
@@ -0,0 +1,39 @@
import json
from pathlib import Path
from dx_productivity.dsh.health import HealthStore
class _Service:
pass
def test_health_snapshot_reports_unconfigured_provider_and_local_stores(tmp_path, monkeypatch):
monkeypatch.delenv('DSH_API_BASE', raising=False)
value = HealthStore(tmp_path).snapshot(_Service())
checks = {row['name']: row for row in value['checks']}
assert value['status'] == 'degraded'
assert checks['provider']['status'] == 'degraded'
assert checks['provider']['code'] == 'provider_unconfigured'
assert checks['stores']['status'] == 'ok'
def test_health_snapshot_marks_active_worker_and_static_issue_token(tmp_path, monkeypatch):
provider = tmp_path / 'dsh' / 'provider.json'
provider.parent.mkdir(parents=True)
provider.write_text(json.dumps({'base_url': 'https://example.test/v1', 'default_model': 'm'}), encoding='utf8')
monkeypatch.setattr('dx_productivity.dsh.health.load_bootstrap', lambda: {'token': 'secret', 'username': 'u', 'scopes': ['write:issue'], 'server': 'https://git.test', 'repository': 'o/r'})
value = HealthStore(tmp_path).snapshot(_Service(), execution='busy')
checks = {row['name']: row for row in value['checks']}
assert checks['execution']['status'] == 'degraded'
assert checks['execution']['code'] == 'worker_active'
assert checks['issue_credentials']['code'] == 'credential_rotation_required'
assert 'secret' not in json.dumps(value)
def test_health_snapshot_reports_stale_ticket_cache(tmp_path):
cache = tmp_path / 'dsh' / 'ticket-cache'
cache.mkdir(parents=True)
value = HealthStore(tmp_path).snapshot(_Service())
checks = {row['name']: row for row in value['checks']}
assert checks['tickets']['status'] == 'ok'
+159
View File
@@ -0,0 +1,159 @@
from dataclasses import replace
import json
import pytest
from dx_productivity.dsh.impact import execution_impact
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
from dx_productivity.trial_task_center.task_queue import _plan_hash
@pytest.fixture
def setup(tmp_path):
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
paths = []
for name in ('exact', 'mapping'):
path = tmp_path / name / 'board.prj'
path.parent.mkdir()
path.write_text('project fixture', encoding='utf-8')
paths.append(path)
tasks = []
for index, path in enumerate(paths):
task = store.create_task(path.parent.name)
project = store.sync_projects(task.task_id, path.parent, (path,))[0]
store.set_project_selected(project.project_id, True)
tasks.append(store.bind_project_task(task.task_id, project.project_id, f'g{index}', 0))
targets = tuple(ComponentTarget(paths[0], 'MAIN', '1', f'u{i}', f'R{i}', 'OLD', f'V{i}') for i in range(1, 4))
store.record_target_inventory(tasks[0].task_id, targets)
rows = (TargetPlanRow(targets[0], True, 'NEW', target_cell='CELL-X'),
TargetPlanRow(targets[1], True, 'NEW', True, 'CUSTOM', False),
TargetPlanRow(targets[2], False, 'NEW2'))
store.replace_target_plan(tasks[0].task_id, rows)
store.add_rule(tasks[1].task_id, 'M-OLD', 'M-NEW', target_cell='CELL-M')
store.add_rule(tasks[1].task_id, 'OFF', 'OFF-NEW', enabled=False)
store.set_copy_part_number_to_value(tasks[1].task_id, True)
yield service, store, tasks, paths
store.close()
def test_exact_target_plan_reports_saved_identities_policies_and_enabled_count(setup):
service, store, tasks, paths = setup
task_id = tasks[0].task_id
before = store._connection.total_changes
project_before = paths[0].read_bytes()
result = execution_impact(service, [task_id])
assert result['coverage'] == 'exact'
assert result['component_count'] == result['known_component_count'] == 2
assert result['enabled_scope'] == 2
assert result['total_rows'] == result['returned_rows'] == 3
first, custom, disabled = result['rows']
assert (first['sheet'], first['schematic_name'], first['refdes'], first['uid']) == ('1', 'MAIN', 'R1', 'u1')
assert first['project'].casefold() == str(paths[0]).casefold()
assert (first['old_part_number'], first['new_part_number']) == ('OLD', 'NEW')
assert first['old_value'] == 'V1'
assert first['value_policy'] == 'preserve'
assert first['proposed_value'] == 'V1'
assert first['target_cell'] == first['target_cell_policy'] == 'CELL-X'
assert first['nc_policy'] == 'sync'
assert custom['value_policy'] == 'custom' and custom['proposed_value'] == 'CUSTOM'
assert custom['nc_policy'] == 'preserve'
assert disabled['enabled'] is False and disabled['component_count'] == 0
assert result['plan_hashes'][task_id] == _plan_hash(service.for_project_task(task_id), task_id)
assert result['cad_connection_checked'] is False
assert store._connection.total_changes == before
assert paths[0].read_bytes() == project_before
json.dumps(result)
def test_mapping_mode_never_invents_component_count_or_matches(setup):
service, _, tasks, _ = setup
result = execution_impact(service, [tasks[1].task_id])
assert result['coverage'] == 'mapping_only'
assert result['component_count'] is None
assert result['known_component_count'] == 0
assert result['enabled_scope'] == 1
assert result['total_rows'] == 2
row = result['rows'][0]
assert row['component_count'] is None
assert row['mapping_scope'] == {'old_part_number': 'M-OLD', 'new_part_number': 'M-NEW'}
assert row['value_policy'] == 'part_label'
assert row['old_value'] is row['proposed_value'] is None
assert row['uid'] is row['refdes'] is row['sheet'] is None
assert row['target_cell_policy'] == 'CELL-M'
def test_copy_label_target_value_is_unknown_and_custom_override_stays_known(setup):
service, store, tasks, _ = setup
store.set_copy_part_number_to_value(tasks[0].task_id, True)
result = execution_impact(service, [tasks[0].task_id])
assert result['rows'][0]['value_policy'] == 'part_label'
assert result['rows'][0]['proposed_value'] is None
assert result['rows'][1]['value_policy'] == 'custom'
assert result['rows'][1]['proposed_value'] == 'CUSTOM'
def test_limit_applies_globally_but_hash_and_totals_cover_omitted_scope(setup):
service, store, tasks, _ = setup
ids = [task.task_id for task in tasks]
report = execution_impact(service, ids, limit=1)
assert report['coverage'] == 'mixed' and report['component_count'] is None
assert report['known_component_count'] == 2
assert report['enabled_scope'] == 3
assert report['truncated'] is True
assert report['total_rows'] == 5 and report['returned_rows'] == 1
assert report['omitted_row_count'] == 4
assert report['tasks'][1]['returned_rows'] == 0
assert report['tasks'][1]['omitted_row_count'] == 2
assert report['full_fingerprint'] == execution_impact(service, ids)['full_fingerprint']
assert report['fingerprint'] == execution_impact(service, ids)['fingerprint']
rows = store.list_target_plan(ids[0])
store.replace_target_plan(ids[0], rows[:2] + (replace(rows[2], new_part_number='CHANGED'),))
changed = execution_impact(service, ids, limit=1)
assert changed['rows'] == report['rows']
assert changed['full_fingerprint'] != report['full_fingerprint']
assert changed['plan_hashes'] != report['plan_hashes']
def test_empty_saved_target_plan_is_exact_zero_without_mapping_fallback(setup):
service, store, tasks, _ = setup
task_id = tasks[1].task_id
store.record_target_inventory(task_id, ())
result = execution_impact(service, [task_id])
assert result['coverage'] == 'exact'
assert result['component_count'] == 0 and result['rows'] == []
@pytest.mark.parametrize('task_ids', [(), [], 't1', ['t1', 't1'], [['x']], [None], [''], ['x' * 129], ['x'] * 21])
def test_invalid_scope_is_rejected_before_service_access(task_ids):
with pytest.raises(TaskCenterError) as caught:
execution_impact(object(), task_ids)
assert caught.value.code == 'assistant_task_scope'
@pytest.mark.parametrize('limit', [0, -1, True, 1.1, '1', 101, None])
def test_limit_is_strict_and_bounded_before_service_access(limit):
with pytest.raises(TaskCenterError) as caught:
execution_impact(object(), ['t1'], limit=limit)
assert caught.value.code == 'assistant_impact_limit'
def test_valid_unknown_task_id_retains_service_not_found_error(setup):
service, _, _, _ = setup
with pytest.raises(TaskCenterError) as caught:
execution_impact(service, ['missing'])
assert caught.value.code == 'unknown_task'
def test_saved_plan_hash_errors_are_not_replaced_with_synthetic_hashes(setup, monkeypatch):
service, _, tasks, _ = setup
def fail(_task_id):
raise TaskCenterError('controlled_read_error', 'cannot read frozen plan')
monkeypatch.setattr(service, 'for_project_task', fail)
with pytest.raises(TaskCenterError) as caught:
execution_impact(service, [tasks[0].task_id])
assert caught.value.code == 'controlled_read_error'
+4
View File
@@ -53,6 +53,10 @@ def test_verified_repair_runs_once_and_duplicate_does_not_repeat(tmp_path):
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):
+43
View File
@@ -0,0 +1,43 @@
import json
from dx_productivity.dsh.issue_broker import IssueBroker, IssueBrokerConfig
TARGET = {'server': 'https://git.test', 'repository': 'owner/repo'}
def test_broker_identifies_static_revocable_token_without_false_expiry(monkeypatch):
monkeypatch.setenv('DSH_BROKER_SECRET', 'server-secret')
config = IssueBrokerConfig.from_environment({**TARGET, 'token': 'git-issue-token', 'secret': 'server-secret'})
broker = IssueBroker(config)
value = broker.exchange({**TARGET, 'instance_id': 'machine-1', 'instance_proof': broker.proof('machine-1'),
'idempotency_key': 'event-1'})
assert value['token'] == 'git-issue-token'
assert value['credential_kind'] == 'revocable_static' and value['expires_utc'] is None
assert 'expires_in' not in value
assert value['repository'] == TARGET['repository']
def test_broker_rejects_wrong_target_and_reuses_idempotency(monkeypatch):
monkeypatch.setenv('DSH_BROKER_SECRET', 'server-secret')
config = IssueBrokerConfig.from_environment({**TARGET, 'token': 'git-issue-token', 'secret': 'server-secret'})
broker = IssueBroker(config)
payload = {'server': TARGET['server'], 'repository': TARGET['repository'], 'instance_id': 'machine-1',
'instance_proof': broker.proof('machine-1'), 'idempotency_key': 'event-1'}
first = broker.exchange(payload)
assert broker.exchange(payload) == first
try:
broker.exchange(payload | {'repository': 'other/repo'})
except ValueError as error:
assert str(error) == 'invalid_target'
else:
raise AssertionError('wrong target accepted')
def test_broker_cache_is_bounded_and_partitioned_by_instance():
config = IssueBrokerConfig.from_environment({**TARGET, 'token': 't', 'secret': 's', 'max_entries': 2})
broker = IssueBroker(config)
for index in range(5):
instance = f'machine-{index}'
broker.exchange({**TARGET, 'instance_id': instance, 'instance_proof': broker.proof(instance), 'idempotency_key': 'same'})
assert len(broker._issued) == 2
+57
View File
@@ -0,0 +1,57 @@
import json
from dx_productivity.dsh.issue_transport import IssueTransport
TARGET = {'server': 'https://git.test', 'repository': 'owner/repo'}
def test_transport_reports_revocable_static_broker_credential_without_caching_token(tmp_path, monkeypatch):
config = tmp_path / 'issue-config.json'
config.write_text(json.dumps({**TARGET, 'broker_url': 'https://broker.test/exchange', 'instance_id': 'machine-1', 'instance_proof': 'proof', 'idempotency_key': 'event-1'}), encoding='utf8')
monkeypatch.setattr('dx_productivity.dsh.issue_transport._post_broker', lambda *args, **kwargs: {**TARGET, 'token': 'static-broker-secret', 'credential_kind': 'revocable_static', 'expires_utc': None})
value = IssueTransport(config).credentials(TARGET)
assert value['source'] == 'broker'
assert value['headers']['Authorization'] == 'token static-broker-secret'
assert value['rotation_required'] is True
assert value['expires_utc'] is None and value['credential_kind'] == 'revocable_static'
cache = list(tmp_path.rglob('*'))
assert all('static-broker-secret' not in p.read_text(encoding='utf8', errors='ignore') for p in cache if p.is_file())
def test_transport_marks_bootstrap_fallback_for_rotation(tmp_path, monkeypatch):
config = tmp_path / 'issue-config.json'
config.write_text(json.dumps(TARGET), encoding='utf8')
monkeypatch.setattr('dx_productivity.dsh.issue_transport.load_bootstrap', lambda: {**TARGET, 'token': 'static-secret', 'username': 'u', 'scopes': ['write:issue']})
value = IssueTransport(config).credentials(TARGET)
assert value['source'] == 'prefilled_issue_token'
assert value['rotation_required'] is True
def test_transport_rejects_target_before_broker_or_credentials(tmp_path, monkeypatch):
config = tmp_path / 'issue-config.json'
config.write_text(json.dumps({**TARGET, 'broker_url': 'https://broker.test/exchange', 'instance_id': 'machine-1', 'instance_proof': 'proof', 'idempotency_key': 'event-1'}), encoding='utf8')
monkeypatch.setattr('dx_productivity.dsh.issue_transport._post_broker', lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('network called')))
value = IssueTransport(config).credentials({'server': 'https://evil.test', 'repository': 'owner/repo'})
assert value['source'] == 'invalid_target'
assert 'headers' not in value
def test_git_publisher_connection_prefers_broker_transport(tmp_path, monkeypatch):
from dx_productivity.dsh.git_issues import GitIssuePublisher
config = tmp_path / 'issue-config.json'
config.write_text(json.dumps({**TARGET, 'broker_url': 'https://broker.test/exchange', 'instance_id': 'machine-1', 'instance_proof': 'proof', 'idempotency_key': 'event-1'}), encoding='utf8')
monkeypatch.setattr('dx_productivity.dsh.issue_transport._post_broker', lambda *args, **kwargs: {**TARGET, 'token': 'broker-token', 'credential_kind': 'revocable_static', 'expires_utc': None})
_, headers, source = GitIssuePublisher(config).connection()
assert headers == {'Authorization': 'token broker-token'}
assert source == 'broker'
def test_transport_rejects_wrong_broker_response_target(tmp_path, monkeypatch):
config = tmp_path / 'issue-config.json'
config.write_text(json.dumps({**TARGET, 'broker_url': 'https://broker.test/exchange',
'instance_id': 'machine-1', 'instance_proof': 'proof', 'idempotency_key': 'event-1'}), encoding='utf8')
monkeypatch.setattr('dx_productivity.dsh.issue_transport._post_broker', lambda *args, **kwargs: {
**TARGET, 'repository': 'other/repo', 'token': 'private', 'credential_kind': 'revocable_static', 'expires_utc': None})
value = IssueTransport(config).credentials(TARGET)
assert 'headers' not in value and value['source'] == 'broker_unavailable'
+99
View File
@@ -0,0 +1,99 @@
from dx_productivity.dsh.resume_diff import resume_diff
from dx_productivity.dsh.run_journal import RunJournal
from test_run_journal import project_service, checkpoint, evidence
from dx_productivity.trial_task_center.task_queue import _plan_hash
from dx_productivity.trial_task_center.models import TaskStatus
import pytest
def test_real_service_plan_changes_are_reported(project_service):
service, _, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('a' * 32, ids, hashes)
checkpoint(data, 'a' * 32, ids, hashes)
rule = service.rules(ids[0])[0]
service.update_rule(rule.rule_id, old_part_number='OLD', new_part_number='DIFFERENT', enabled=True)
report = journal.inspect(service, 'a' * 32)
assert ids[0] in report['diff']['changed']
change = next(row for row in report['diff']['plan_changes'] if row['task_id'] == ids[0])
assert change['saved'] == hashes[ids[0]] and change['current'] != change['saved']
assert report['diff']['safe'] is False
def test_real_service_uses_original_checkpoint_remaining_scope(project_service):
service, _, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('a' * 32, ids, hashes)
checkpoint(data, 'a' * 32, ids, hashes)
report = journal.inspect(service, 'a' * 32)
assert report['diff']['safe'] is True
assert report['diff']['remaining'] == ids
assert report['diff']['completed'] == []
def test_evidence_counter_changes_since_receipt_are_visible(project_service):
service, _, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('a' * 32, ids, hashes)
checkpoint(data, 'a' * 32, ids, hashes)
journal.finish('a' * 32, {'status': 'paused', 'tasks': [{'task_id': ids[0], 'no_match_items': 0}]})
evidence(service, ids[0])
report = journal.inspect(service, 'a' * 32)
assert {'task_id': ids[0], 'field': 'no_match_items', 'saved': 0, 'current': 1} in report['diff']['evidence_changes']
assert 'evidence_changed' in report['diff']['blockers']
def test_missing_current_hash_cannot_be_silently_ignored(project_service):
service, _, _, ids, hashes = project_service
value = resume_diff(service, {'task_ids': ids, 'plan_hashes': {}, 'remaining_task_ids': ids,
'queue_available': True, 'resume_ready': True, 'tasks': []})
assert value['safe'] is False
assert value['changed'] == ids
def test_completed_checkpoint_requires_matching_current_evidence(project_service):
service, _, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('c' * 32, ids, hashes)
checkpoint(data, 'c' * 32, ids, hashes, {ids[0]: 'completed'})
report = journal.inspect(service, 'c' * 32)
assert not report['resume_ready']
assert 'checkpoint_evidence_mismatch' in report['blockers']
evidence(service, ids[0])
assert journal.inspect(service, 'c' * 32)['resume_ready']
@pytest.mark.parametrize('checkpoint_state', ['running', 'completed'])
def test_crash_during_resumed_run_accepts_verified_progress_but_not_old_terminal_changes(project_service, checkpoint_state):
service, store, data, ids, _ = project_service
hashes = {key: _plan_hash(service.for_project_task(key), key) for key in ids}
journal = RunJournal(data)
journal.begin('b' * 32, ids, hashes)
evidence(service, ids[0])
for state in (TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.COMPLETED):
store.set_task_status(ids[0], state)
checkpoint(data, 'b' * 32, ids, hashes, {ids[0]: 'completed', ids[1]: 'paused'})
baseline = []
for task_id in ids:
context = service.task_context(task_id)
baseline.append({'task_id': task_id, 'interrupted': context.interrupted,
**{key: getattr(context.progress, key) for key in
('saved_items', 'failed_items', 'no_match_items', 'queue_complete')}})
journal.finish('b' * 32, {'status': 'paused', 'tasks': baseline,
'entries': [{'task_id': key, 'state': 'completed' if key == ids[0] else 'paused' if key == ids[1] else 'pending'} for key in ids]})
assert journal.inspect(service, 'b' * 32)['resume_ready']
journal.resume('b' * 32)
evidence(service, ids[1])
for state in (TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.COMPLETED):
store.set_task_status(ids[1], state)
checkpoint(data, 'b' * 32, ids, hashes, {ids[0]: 'completed', ids[1]: checkpoint_state})
report = journal.inspect(service, 'b' * 32)
assert report['resume_ready'], report['blockers']
assert report['diff']['evidence_changes']
assert all(row['expected_progress'] for row in report['diff']['evidence_changes'])
# The run cannot rewrite or lose evidence for a task already terminal in
# the last durable receipt, even while later tasks legitimately advance.
root = service.for_project_task(ids[0])._quick_run_preparer.data_root / 'quick-run'
(root / 'status.tsv').write_text('job_id\tstate\tcode\tmessage\n', encoding='utf8')
changed = journal.inspect(service, 'b' * 32)
assert not changed['resume_ready'] and 'evidence_changed' in changed['blockers']
+161
View File
@@ -0,0 +1,161 @@
import json
from dataclasses import asdict
from pathlib import Path
import pytest
from dx_productivity.dsh.run_journal import RunJournal
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.models import TaskStatus
from dx_productivity.trial_task_center.task_queue import _plan_hash, TaskQueueResult, TaskQueueEntry
@pytest.fixture
def project_service(tmp_path):
root = tmp_path / 'projects'
for name in ('A', 'B', 'C'):
path = root / name / 'board.prj'
path.parent.mkdir(parents=True)
path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
data = tmp_path / 'data'
preparer = QuickRunPreparer(data, sheet_discoverer=lambda _path: (('MAIN', '1'),))
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(data), quick_run_preparer=preparer)
tasks = service.create_project_tasks(root)
service.add_rule(tasks[0].task_id, 'OLD', 'NEW')
ids = [task.task_id for task in tasks]
hashes = {key: _plan_hash(service.for_project_task(key), key) for key in ids}
yield service, store, data, ids, hashes
store.close()
def evidence(service, task_id, state='no_match', code='batch_closed'):
context = service.task_context(task_id)
root = service.for_project_task(task_id)._quick_run_preparer.data_root / 'quick-run'
root.mkdir(parents=True, exist_ok=True)
(root / 'command.tsv').write_text('task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode\n'
f'{task_id}\tjob\t{context.project.path}\tOLD\tNEW\tpreserve\t\t1\tpreserve\n', encoding='utf-8')
(root / 'status.tsv').write_text('job_id\tstate\tcode\tmessage\n'
f'job\t{state}\t{code}\tfixture evidence\n', encoding='utf-8')
def checkpoint(data, run_id, ids, hashes, states=None):
path = data / 'task-queues' / f'{run_id}.json'
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps({'version': 1, 'task_ids': ids, 'plan_hashes': hashes,
'entries': {key: {'state': (states or {}).get(key, 'pending'), 'message': ''} for key in ids}}))
def test_begin_is_durable_reserves_original_queue_and_rejects_rebinding(project_service):
service, store, data, ids, hashes = project_service
row = RunJournal(data).begin('a' * 32, ids, hashes)
assert row['queue_id'] == 'a' * 32 and row['task_ids'] == ids and row['status'] == 'running'
reopened = RunJournal(data)
assert reopened.get('a' * 32) == row
assert reopened.list_runs()[0] == row
assert reopened.begin('a' * 32, ids, hashes) == row
with pytest.raises(TaskCenterError):
reopened.begin('a' * 32, ids[::-1], hashes)
def test_finish_preserves_receipt_across_restart(project_service):
_, _, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('a' * 32, ids, hashes)
result = TaskQueueResult('a' * 32, (TaskQueueEntry(ids[0], 'completed'),), True, ids[1])
journal.finish('a' * 32, result)
row = RunJournal(data).get('a' * 32)
assert row['status'] == 'paused' and row['result'] == json.loads(json.dumps(asdict(result)))
assert row['finished_utc']
def test_failed_queue_receipt_does_not_claim_success(project_service):
_, _, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('a' * 32, ids, hashes)
result = TaskQueueResult('a' * 32, (TaskQueueEntry(ids[0], 'failed'),), False)
assert journal.finish('a' * 32, result)['status'] == 'failed'
def test_native_confirmed_resume_marks_running_and_retains_last_receipt(project_service):
_, _, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('a' * 32, ids, hashes)
result = TaskQueueResult('a' * 32, (TaskQueueEntry(ids[0], 'paused'),), True, ids[0])
prior = journal.finish('a' * 32, result)
row = journal.resume('a' * 32)
assert row['status'] == 'running' and row['finished_utc'] is None
assert row['result'] == prior['result'] and row['queue_id'] == 'a' * 32
journal.finish('a' * 32, TaskQueueResult('a' * 32, (TaskQueueEntry(ids[0], 'completed'),), False))
with pytest.raises(TaskCenterError):
journal.resume('a' * 32)
def test_inspect_reports_invalid_checkpoint_without_trusting_partial_content(project_service):
service, _, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('a' * 32, ids, hashes)
path = data / 'task-queues' / ('a' * 32 + '.json')
path.parent.mkdir(parents=True)
path.write_text(json.dumps({'version': 1, 'task_ids': ids[::-1]}))
result = journal.inspect(service, 'a' * 32)
assert not result['queue_available'] and not result['resume_ready']
assert result['blockers'] == ['queue_invalid']
def test_inspect_reads_real_counters_and_skips_completed_original_scope(project_service):
service, store, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('a' * 32, ids, hashes)
checkpoint(data, 'a' * 32, ids, hashes, {ids[0]: 'completed'})
evidence(service, ids[0])
store.set_task_status(ids[0], TaskStatus.READY)
store.set_task_status(ids[0], TaskStatus.RUNNING)
store.set_task_status(ids[0], TaskStatus.COMPLETED)
result = RunJournal(data).inspect(service, 'a' * 32)
assert result['queue_available'] and result['resume_ready']
assert result['task_ids'] == ids and result['remaining_task_ids'] == ids[1:]
assert result['counters']['no_match_items'] == 1
assert result['tasks'][0]['no_match_items'] == 1
assert not result['cad_execution_started']
def test_inspect_blocks_missing_checkpoint_stale_plan_and_uncertainty(project_service):
service, _, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('a' * 32, ids, hashes)
result = journal.inspect(service, 'a' * 32)
assert not result['queue_available'] and result['resume_ready']
evidence(service, ids[0])
assert 'queue_missing' in journal.inspect(service, 'a' * 32)['blockers']
evidence_root = service.for_project_task(ids[0])._quick_run_preparer.data_root / 'quick-run'
(evidence_root / 'command.tsv').unlink()
(evidence_root / 'status.tsv').unlink()
checkpoint(data, 'a' * 32, ids, hashes)
rule = service.rules(ids[1])[0]
service.update_rule(rule.rule_id, old_part_number='OLD', new_part_number='CHANGED', enabled=True)
evidence(service, ids[0], 'batch_saved_unverified', '')
result = journal.inspect(service, 'a' * 32)
assert not result['resume_ready']
assert 'plan_changed' in result['blockers'] and 'interrupted' in result['blockers']
def test_inspect_blocks_archived_unfinished_tasks(project_service):
service, _, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('a' * 32, ids, hashes)
checkpoint(data, 'a' * 32, ids, hashes)
service.delete_task(ids[0])
result = journal.inspect(service, 'a' * 32)
assert not result['resume_ready'] and 'preflight_blocked' in result['blockers']
@pytest.mark.parametrize('run_id,ids,hashes', [('../outside', ['a'], {'a': 'b' * 64}),
('a' * 32, ['a', 'a'], {'a': 'b' * 64}), ('a' * 32, ['a'], {'other': 'b' * 64})])
def test_begin_rejects_unsafe_or_inconsistent_scope(tmp_path, run_id, ids, hashes):
with pytest.raises(TaskCenterError):
RunJournal(tmp_path).begin(run_id, ids, hashes)
+86
View File
@@ -0,0 +1,86 @@
import hashlib
import json
import sqlite3
import pytest
from dx_productivity.dsh.scheduling import ScheduleStore
def populate(root, count=6):
store = ScheduleStore(root)
with store._connect() as db:
for index in range(count):
store._event(db, 'a' * 32, '2026-10-31T12:00:00Z', 'result', 'b' * 32,
{'status': 'completed', 'index': index})
return store
def test_archive_bounds_hot_events_without_losing_original_records(tmp_path):
store = populate(tmp_path)
before = store.events()
first = store.archive_events(keep=2, batch=2)
assert first['archived'] == 2
assert len(store.events()) == 4
store.archive_events(keep=2, batch=2)
summary = ScheduleStore(tmp_path).audit_status(keep=2)
assert summary['live_events'] == 2 and summary['archived_events'] == 4
archived = []
for path in sorted((tmp_path / 'dsh/schedule-audit').glob('*.jsonl')):
raw = path.read_bytes()
assert path.stem.endswith(hashlib.sha256(raw).hexdigest())
archived.extend(json.loads(line) for line in raw.splitlines())
assert sorted(archived + store.events(), key=lambda row: row['sequence']) == list(reversed(before))
assert store.archive_events(keep=2)['archived'] == 0
def test_failed_archive_export_never_deletes_audit_events(tmp_path, monkeypatch):
from dx_productivity.dsh import schedule_audit
store = populate(tmp_path)
before = store.events()
def unavailable(*args):
raise OSError('controlled export failure')
monkeypatch.setattr(schedule_audit, '_write_archive', unavailable)
with pytest.raises(OSError):
store.archive_events(keep=2)
assert store.events() == before
def test_database_failure_after_archive_is_safe_and_retryable(tmp_path):
store = populate(tmp_path)
before = store.events()
with sqlite3.connect(store.path) as db:
db.execute("CREATE TRIGGER reject_trim BEFORE DELETE ON schedule_events BEGIN SELECT RAISE(ABORT, 'controlled fault'); END")
with pytest.raises(sqlite3.IntegrityError):
store.archive_events(keep=2)
assert store.events() == before
files = list((tmp_path / 'dsh/schedule-audit').glob('*.jsonl'))
assert len(files) == 1
raw = files[0].read_bytes()
with sqlite3.connect(store.path) as db:
db.execute('DROP TRIGGER reject_trim')
store.archive_events(keep=2)
assert files[0].read_bytes() == raw
assert store.audit_status(keep=2)['archived_events'] == 4
@pytest.mark.parametrize('damage', ['missing', 'changed'])
def test_missing_or_changed_committed_archive_is_never_reported_healthy(tmp_path, damage):
store = populate(tmp_path)
store.audit_status(keep=2)
archive = next((tmp_path / 'dsh/schedule-audit').glob('*.jsonl'))
if damage == 'missing':
archive.unlink()
else:
archive.write_bytes(b'corrupted evidence\n')
with pytest.raises(OSError):
store.audit_status(keep=2)
def test_automatic_rotation_batches_overflow_instead_of_creating_one_file_per_event(tmp_path):
store = populate(tmp_path, count=3)
assert store.audit_status(keep=2)['archived_events'] == 0
with store._connect() as db:
store._event(db, 'a' * 32, '2026-10-31T12:00:00Z', 'result', None, {'status': 'completed'})
status = store.audit_status(keep=2)
assert status['live_events'] == 2 and status['archived_events'] == 2
+283
View File
@@ -0,0 +1,283 @@
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import pytest
from dx_productivity.dsh.scheduling import ScheduleStore
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.models import TaskStatus
from test_run_journal import project_service, evidence
NOW = datetime(2026, 10, 30, 12, tzinfo=timezone.utc)
def spec(ids, **extra):
return {'task_ids': ids, 'priority': 'normal', 'not_before': '2026-10-30T20:00:00+08:00', **extra}
def test_save_normalizes_utc_and_preserves_frozen_scope_across_restart(project_service):
_, _, data, ids, hashes = project_service
row = ScheduleStore(data).save(spec(ids), hashes)
assert row['not_before'] == '2026-10-30T12:00:00+00:00'
assert row['status'] == 'pending' and row['auto_start'] is False and row['idle_only'] is True
assert ScheduleStore(data).get(row['schedule_id']) == row
def test_preview_normalizes_native_draft_without_persisting_or_granting_authority(project_service):
_, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
result = schedules.preview(spec(ids, auto_start=True), hashes)
assert result == {'task_ids': ids, 'priority': 'normal', 'not_before': '2026-10-30T12:00:00+00:00',
'due_at': None, 'dependencies': [], 'auto_start': True, 'idle_only': True, 'title': ''}
assert schedules.list_schedules() == []
@pytest.mark.parametrize('extra', [{'confirmed': True}, {'priority': 'highest'}, {'not_before': '2026-10-30T12:00:00'},
{'auto_start': 'true'}, {'dependencies': ['../bad']}, {'task_ids': []}, {'title': '\x00bad'},
{'due_at': '2026-10-29T00:00:00Z'}])
def test_save_rejects_untrusted_or_invalid_specs(project_service, extra):
_, _, data, ids, hashes = project_service
with pytest.raises(TaskCenterError):
ScheduleStore(data).save(spec(ids, **extra), hashes)
def test_due_order_and_manual_confirmation_without_execution(project_service):
service, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
normal = schedules.save(spec(ids), hashes)
urgent = schedules.save(spec(ids, priority='urgent', auto_start=True), hashes)
rows = schedules.evaluate(service, now=NOW)
assert [row['schedule_id'] for row in rows] == [urgent['schedule_id'], normal['schedule_id']]
assert rows[0]['ready'] and rows[0]['requires_confirmation'] is False
assert rows[0]['dispatchable'] is True # save follows native future-run authorization
assert rows[0]['dispatch_authority'] == 'native_future_authorization'
assert rows[1]['requires_confirmation'] and not rows[1]['dispatchable']
assert not list(data.rglob('command.tsv'))
assert all('worker_busy' in row['blockers'] for row in schedules.evaluate(service, now=NOW, busy=True))
def test_dispatch_and_result_audit_are_durable_and_automatic_claim_needs_authority(project_service):
_, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
manual = schedules.save(spec(ids), hashes)
with pytest.raises(TaskCenterError, match='schedule_authority'):
schedules.claim(manual['schedule_id'], automatic=True, run_id='a' * 32)
assert schedules.get(manual['schedule_id'])['status'] == 'pending'
assert schedules.events() == []
row = schedules.save(spec(ids, auto_start=True), hashes)
schedules.claim(row['schedule_id'], automatic=True, run_id='b' * 32)
schedules.finish(row['schedule_id'], 'completed', run_id='b' * 32, receipt={'status': 'completed'})
events = ScheduleStore(data).events()
assert [e['event'] for e in reversed(events)] == ['dispatch', 'result']
assert events[1]['payload']['scope'] == {'task_ids': ids, 'plan_hashes': hashes}
assert events[1]['payload']['authority'] == 'native_future_authorization'
assert events[0]['payload']['receipt']['status'] == 'completed'
assert all(e['run_id'] == 'b' * 32 for e in events)
def test_audit_insert_failure_rolls_back_claim_before_execution(project_service):
import sqlite3
_, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
row = schedules.save(spec(ids, auto_start=True), hashes)
with sqlite3.connect(schedules.path) as db:
db.execute("CREATE TRIGGER reject_event BEFORE INSERT ON schedule_events BEGIN SELECT RAISE(ABORT, 'controlled audit fault'); END")
with pytest.raises(sqlite3.IntegrityError):
schedules.claim(row['schedule_id'], automatic=True, run_id='b' * 32)
assert ScheduleStore(data).get(row['schedule_id'])['status'] == 'pending'
def test_future_and_changed_plans_do_not_become_ready(project_service):
service, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
schedules.save(spec(ids, not_before='2026-10-31T12:00:00Z'), hashes)
assert 'not_due' in schedules.evaluate(service, now=NOW)[0]['blockers']
rule = service.rules(ids[0])[0]
service.update_rule(rule.rule_id, old_part_number='OLD', new_part_number='CHANGED', enabled=True)
assert 'plan_changed' in schedules.evaluate(service, now=NOW)[0]['blockers']
def test_preflight_blocks_missing_project_and_unreconciled_saved_result(project_service):
service, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
schedules.save(spec(ids), hashes)
evidence(service, ids[0], 'batch_saved_unverified', '')
row = schedules.evaluate(service, now=NOW)[0]
assert not row['ready'] and 'preflight_blocked' in row['blockers']
service.task_context(ids[1]).project.path.unlink()
assert not schedules.evaluate(service, now=NOW)[0]['ready']
def test_paused_task_requires_explicit_manual_resume(project_service):
service, store, data, ids, hashes = project_service
schedules = ScheduleStore(data)
schedules.save(spec(ids, auto_start=True), hashes)
store.set_task_status(ids[0], TaskStatus.READY)
store.set_task_status(ids[0], TaskStatus.RUNNING)
store.set_task_status(ids[0], TaskStatus.PAUSED)
row = schedules.evaluate(service, now=NOW)[0]
assert not row['ready'] and 'task_paused' in row['blockers']
def test_multiple_schedules_for_a_task_cannot_hide_dependency_cycle(project_service):
_, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
schedules.save(spec(ids[:1], dependencies=ids[1:2]), {ids[0]: hashes[ids[0]]})
schedules.save(spec(ids[:1], dependencies=[]), {ids[0]: hashes[ids[0]]})
with pytest.raises(TaskCenterError):
schedules.save(spec(ids[1:2], dependencies=ids[:1]), {ids[1]: hashes[ids[1]]})
def test_dependencies_require_real_completion_and_verified_evidence(project_service):
service, store, data, ids, hashes = project_service
schedules = ScheduleStore(data)
schedules.save(spec(ids[:1], dependencies=ids[1:2]), {ids[0]: hashes[ids[0]]})
assert 'dependency_incomplete' in schedules.evaluate(service, now=NOW)[0]['blockers']
store.set_task_status(ids[1], TaskStatus.READY)
store.set_task_status(ids[1], TaskStatus.RUNNING)
store.set_task_status(ids[1], TaskStatus.COMPLETED)
assert 'dependency_incomplete' in schedules.evaluate(service, now=NOW)[0]['blockers']
evidence(service, ids[1])
assert schedules.evaluate(service, now=NOW)[0]['ready']
evidence(service, ids[1], 'batch_saved_unverified', '')
assert 'dependency_incomplete' in schedules.evaluate(service, now=NOW)[0]['blockers']
def test_self_dependency_and_cross_schedule_cycles_are_rejected(project_service):
_, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
with pytest.raises(TaskCenterError):
schedules.save(spec(ids[:1], dependencies=ids[:1]), {ids[0]: hashes[ids[0]]})
schedules.save(spec(ids[:1], dependencies=ids[1:2]), {ids[0]: hashes[ids[0]]})
with pytest.raises(TaskCenterError):
schedules.save(spec(ids[1:2], dependencies=ids[:1]), {ids[1]: hashes[ids[1]]})
def test_claim_is_exclusive_and_never_replayed_after_restart(project_service):
service, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
row = schedules.save(spec(ids), hashes)
def claim(_):
try:
return ScheduleStore(data).claim(row['schedule_id'])
except TaskCenterError:
return None
with ThreadPoolExecutor(max_workers=4) as pool:
assert sum(value is not None for value in pool.map(claim, range(4))) == 1
reopened = ScheduleStore(data)
assert reopened.get(row['schedule_id'])['status'] == 'claimed'
assert 'already_claimed' in reopened.evaluate(service, now=NOW)[0]['blockers']
with pytest.raises(TaskCenterError):
reopened.claim(row['schedule_id'])
reopened.finish(row['schedule_id'], 'completed', run_id='a' * 32)
assert reopened.get(row['schedule_id'])['run_id'] == 'a' * 32
def test_cancel_is_durable_and_cannot_cancel_an_owned_claim(project_service):
_, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
row = schedules.save(spec(ids), hashes)
schedules.cancel(row['schedule_id'])
assert ScheduleStore(data).get(row['schedule_id'])['status'] == 'cancelled'
with pytest.raises(TaskCenterError):
schedules.claim(row['schedule_id'])
claimed = schedules.save(spec(ids), hashes)
schedules.claim(claimed['schedule_id'])
with pytest.raises(TaskCenterError):
schedules.cancel(claimed['schedule_id'])
@pytest.mark.parametrize('run_state', [None, 'running', 'completed', 'paused', 'failed'])
def test_reconcile_orphan_claim_preserves_original_run_and_never_replays(project_service, run_state):
from dx_productivity.dsh.run_journal import RunJournal
service, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
row = schedules.save(spec(ids, auto_start=True), hashes)
run_id = 'c' * 32
schedules.claim(row['schedule_id'], run_id=run_id, automatic=True)
journal = RunJournal(data)
if run_state:
journal.begin(run_id, ids, hashes, schedule_id=row['schedule_id'])
if run_state != 'running':
journal.finish(run_id, {'status': run_state, 'tasks': [], 'entries': []})
before = journal.get(run_id)
reopened = ScheduleStore(data)
result = reopened.reconcile_claim(service, row['schedule_id'])
expected = run_state if run_state in {'completed', 'failed'} else 'interrupted'
assert result['status'] == expected and result['run_id'] == run_id
assert journal.get(run_id) == before
assert result['result']['reconciled'] is True
assert reopened.events()[0]['event'] == 'result'
assert reopened.events()[0]['payload']['reconciled'] is True
assert not reopened.evaluate(service, now=NOW)[0]['dispatchable']
assert not list(data.rglob('command.tsv'))
def test_reconcile_refuses_active_owner_and_pending_resources(project_service, monkeypatch):
service, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
row = schedules.save(spec(ids), hashes)
schedules.claim(row['schedule_id'], run_id='d' * 32)
with schedules.execution_lease(row['schedule_id']):
with pytest.raises(TaskCenterError, match='schedule_busy'):
ScheduleStore(data).reconcile_claim(service, row['schedule_id'])
monkeypatch.setattr(service, 'pending_batch_resources', lambda: [object()])
with pytest.raises(TaskCenterError, match='schedule_busy'):
schedules.reconcile_claim(service, row['schedule_id'])
assert schedules.get(row['schedule_id'])['status'] == 'claimed'
assert len(schedules.events()) == 1
def test_reconcile_audit_failure_leaves_claim_unchanged(project_service):
import sqlite3
service, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
row = schedules.save(spec(ids), hashes)
schedules.claim(row['schedule_id'])
with sqlite3.connect(schedules.path) as db:
db.execute("CREATE TRIGGER reject_result BEFORE INSERT ON schedule_events BEGIN SELECT RAISE(ABORT, 'controlled fault'); END")
with pytest.raises(sqlite3.IntegrityError):
schedules.reconcile_claim(service, row['schedule_id'])
assert schedules.get(row['schedule_id'])['status'] == 'claimed'
def test_hard_process_exit_releases_schedule_lease_for_native_reconciliation(project_service):
import subprocess
import sys
from pathlib import Path
service, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
row = schedules.save(spec(ids, auto_start=True), hashes)
child = subprocess.run([sys.executable, '-c',
"import os,sys; sys.path.insert(0, 'src'); from dx_productivity.dsh.scheduling import ScheduleStore; "
"s=ScheduleStore(sys.argv[1]); lease=s.execution_lease(sys.argv[2]); lease.__enter__(); "
"s.claim(sys.argv[2],run_id='e'*32,automatic=True); os._exit(19)", str(data), row['schedule_id']],
cwd=Path(__file__).resolve().parents[2], capture_output=True, timeout=20)
assert child.returncode == 19, child.stderr.decode('utf8', 'replace')
assert ScheduleStore(data).get(row['schedule_id'])['status'] == 'claimed'
result = ScheduleStore(data).reconcile_claim(service, row['schedule_id'])
assert result['status'] == 'interrupted' and result['run_id'] == 'e' * 32
def test_active_claim_in_another_process_cannot_be_reconciled(project_service):
import subprocess
import sys
from pathlib import Path
service, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
row = schedules.save(spec(ids, auto_start=True), hashes)
child = subprocess.Popen([sys.executable, '-c',
"import sys; sys.path.insert(0,'src'); from dx_productivity.dsh.scheduling import ScheduleStore; "
"s=ScheduleStore(sys.argv[1]); lease=s.execution_lease(sys.argv[2]); lease.__enter__(); "
"s.claim(sys.argv[2],run_id='f'*32,automatic=True); print('ready',flush=True); "
"sys.stdin.buffer.read(1); lease.__exit__(None,None,None)", str(data), row['schedule_id']],
cwd=Path(__file__).resolve().parents[2], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
assert child.stdout.readline().strip() == b'ready'
with pytest.raises(TaskCenterError, match='schedule_busy'):
schedules.reconcile_claim(service, row['schedule_id'])
assert schedules.get(row['schedule_id'])['status'] == 'claimed'
finally:
child.communicate(input=b'q', timeout=10)
assert child.returncode == 0
+165
View File
@@ -0,0 +1,165 @@
import io
import json
import urllib.error
import pytest
from dx_productivity.dsh.ticket_tracking import TicketTracker
from dx_productivity.dsh.git_issues import GitIssuePublisher, NoRedirect
ID = 'a' * 24
SERVER = 'https://git.example'
REPO = 'owner/repo'
URL = SERVER + '/' + REPO + '/issues/7'
def setup_ticket(root, **ticket):
directory = root / 'dsh' / 'incidents' / ID
directory.mkdir(parents=True)
(directory / 'incident.json').write_text(json.dumps({'incident_id': ID,
'ticket': {'number': 7, 'url': URL, **ticket}}), encoding='utf8')
(root / 'dsh' / 'issue-config.json').write_text(json.dumps(
{'enabled': True, 'server': SERVER, 'repository': REPO}), encoding='utf8')
def remote(monkeypatch, *, issue=None, comments=None, failure=None):
requests = []
def connection(self):
return {'enabled': True, 'server': SERVER, 'repository': REPO}, {'Authorization': 'token test-secret'}, 'test'
monkeypatch.setattr(GitIssuePublisher, 'connection', connection)
class Opener:
def open(self, request, timeout):
requests.append(request)
if failure:
raise failure
value = comments if '/comments?' in request.full_url else issue
return io.BytesIO(json.dumps(value).encode())
def build(*handlers):
assert any(isinstance(handler, NoRedirect) for handler in handlers)
return Opener()
monkeypatch.setattr('dx_productivity.dsh.ticket_tracking.urllib.request.build_opener', build)
return requests
def good_issue(**changes):
return {'number': 7, 'html_url': URL, 'title': '[DSH:' + ID + '] worker_error',
'state': 'closed', 'updated_at': '2026-10-30T01:00:00Z', 'body': 'ignored', **changes}
def test_refresh_reads_fixed_bound_issue_and_comments_scrubs_and_persists(tmp_path, monkeypatch):
setup_ticket(tmp_path)
requests = remote(monkeypatch, issue=good_issue(), comments=[{'id': 1,
'body': 'Authorization: Bearer sensitiveExample123', 'created_at': '2026-10-30T02:00:00Z',
'user': {'login': 'reviewer'}}])
result = TicketTracker(tmp_path).refresh(ID)
assert result['state'] == 'closed'
assert result['status'] == 'synced'
assert result['last_sync_at']
assert result['locally_verified'] is False
assert 'sensitiveExample123' not in json.dumps(result)
assert all(request.get_method() == 'GET' for request in requests)
assert all(request.full_url.startswith(SERVER + '/api/v1/repos/' + REPO + '/issues/7') for request in requests)
assert len(requests) == 2
assert TicketTracker(tmp_path).list_tickets() == [result]
@pytest.mark.parametrize('ticket', [{'url': 'https://evil.example/owner/repo/issues/7'},
{'url': URL + '?redirect=bad'}, {'url': URL + '/extra'}, {'number': True}, {'number': 8},
{'url': 'https://git.example/other/repo/issues/7'}, {'url': 'https://user:pass@git.example/owner/repo/issues/7'}])
def test_invalid_local_ticket_cannot_access_credentials_or_network(tmp_path, monkeypatch, ticket):
setup_ticket(tmp_path, **ticket)
def forbidden(*args):
pytest.fail('invalid ticket attempted credentials or network')
monkeypatch.setattr(GitIssuePublisher, 'connection', forbidden)
monkeypatch.setattr('urllib.request.build_opener', forbidden)
result = TicketTracker(tmp_path).refresh(ID)
assert result['status'] == 'unavailable'
assert result['error'] == 'invalid_ticket_target'
def test_remote_identity_must_match_before_comment_read_or_state_cache(tmp_path, monkeypatch):
setup_ticket(tmp_path)
requests = remote(monkeypatch, issue=good_issue(title='[DSH:other] unrelated'), comments=[])
result = TicketTracker(tmp_path).refresh(ID)
assert result['status'] == 'unavailable'
assert result['error'] == 'ticket_identity_mismatch'
assert 'state' not in result
assert len(requests) == 1
def test_network_failure_preserves_last_good_state_and_date(tmp_path, monkeypatch):
setup_ticket(tmp_path)
remote(monkeypatch, issue=good_issue(), comments=[])
first = TicketTracker(tmp_path).refresh(ID)
remote(monkeypatch, failure=urllib.error.URLError('token super-secret'))
failed = TicketTracker(tmp_path).refresh(ID)
assert failed['state'] == first['state']
assert failed['last_sync_at'] == first['last_sync_at']
assert failed['status'] == 'unavailable'
assert failed['error'] == 'URLError'
assert 'super-secret' not in json.dumps(failed)
assert failed['last_attempt_at']
assert TicketTracker(tmp_path).list_tickets() == [failed]
def test_disabled_or_missing_credentials_do_not_make_network_request(tmp_path, monkeypatch):
setup_ticket(tmp_path)
monkeypatch.setattr(GitIssuePublisher, 'connection', lambda self: (
{'enabled': True, 'server': SERVER, 'repository': REPO}, {}, 'git_not_installed'))
result = TicketTracker(tmp_path).refresh(ID)
assert result['status'] == 'unavailable'
assert result['error'] == 'git_not_installed'
listed = TicketTracker(tmp_path).list_tickets()[0]
assert listed['number'] == 7
assert listed['url'] == URL
assert listed['last_sync_at'] is None
def test_invalid_incident_id_cannot_traverse(tmp_path):
with pytest.raises(ValueError, match='invalid_incident_id'):
TicketTracker(tmp_path).refresh('../escape')
def test_recent_comments_use_bounded_last_page(tmp_path, monkeypatch):
setup_ticket(tmp_path)
requests = remote(monkeypatch, issue=good_issue(comments=51), comments=[
{'id': n, 'body': 'comment'} for n in range(40, 51)])
result = TicketTracker(tmp_path).refresh(ID)
assert 'page=3' in requests[-1].full_url
assert len(result['comments']) <= 20
def test_connection_target_change_never_sends_credentials(tmp_path, monkeypatch):
setup_ticket(tmp_path)
requests = remote(monkeypatch, issue=good_issue(), comments=[])
monkeypatch.setattr(GitIssuePublisher, 'connection', lambda self: (
{'enabled': True, 'server': 'https://evil.example', 'repository': REPO},
{'Authorization': 'token test-secret'}, 'test'))
assert TicketTracker(tmp_path).refresh(ID)['error'] == 'invalid_ticket_target'
assert not requests
def test_list_discovers_bound_existing_ticket_without_network_or_credentials(tmp_path, monkeypatch):
setup_ticket(tmp_path)
def forbidden(*args):
pytest.fail('listing cannot access credentials or network')
monkeypatch.setattr(GitIssuePublisher, 'connection', forbidden)
monkeypatch.setattr('urllib.request.build_opener', forbidden)
rows = TicketTracker(tmp_path).list_tickets()
assert len(rows) == 1
assert rows[0] == {'incident_id': ID, 'number': 7, 'url': URL,
'status': 'not_synced', 'last_sync_at': None, 'locally_verified': False}
def test_list_omits_untrusted_local_ticket_and_uses_cached_good_result(tmp_path, monkeypatch):
setup_ticket(tmp_path)
remote(monkeypatch, issue=good_issue(), comments=[])
tracker = TicketTracker(tmp_path)
cached = tracker.refresh(ID)
assert tracker.list_tickets() == [cached]
directory = tmp_path / 'dsh' / 'incidents' / ('b' * 24)
directory.mkdir()
(directory / 'incident.json').write_text(json.dumps({'incident_id': 'b' * 24,
'ticket': {'number': 7, 'url': 'https://evil.example/owner/repo/issues/7'}}), encoding='utf8')
assert tracker.list_tickets() == [cached]
@@ -0,0 +1,40 @@
from pathlib import Path
import importlib.util
_MODULE = Path(__file__).resolve().parents[2] / 'packaging' / 'dsh_runtime_staging.py'
_SPEC = importlib.util.spec_from_file_location('dsh_runtime_staging', _MODULE)
_LOADED = importlib.util.module_from_spec(_SPEC)
assert _SPEC and _SPEC.loader
_SPEC.loader.exec_module(_LOADED)
stage_node_modules = _LOADED.stage_node_modules
def _package(root: Path, name: str, *, os=None, cpu=None, files=()):
path = root / name
path.mkdir(parents=True)
manifest = {'name': name, 'version': '1.0.0'}
if os is not None:
manifest['os'] = os
if cpu is not None:
manifest['cpu'] = cpu
import json
(path / 'package.json').write_text(json.dumps(manifest), encoding='utf8')
for relative, content in files:
target = path / relative
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content, encoding='utf8')
def test_stage_dsh_runtime_keeps_windows_runtime_and_prunes_other_platforms(tmp_path):
source = tmp_path / 'node_modules'
(source / '@deepseek-ai' / 'dsh').mkdir(parents=True)
(source / '@deepseek-ai' / 'dsh' / 'package.json').write_text('{}', encoding='utf8')
_package(source, 'win-addon', os=['win32'], cpu=['x64'], files=[('index.js', 'ok')])
_package(source, 'linux-addon', os=['linux'], files=[('index.js', 'drop')])
_package(source, 'docs-only', files=[('index.js', 'ok'), ('README.md', 'drop'), ('source.ts', 'drop')])
staged = stage_node_modules(source, tmp_path / 'staged')
assert (staged / 'win-addon' / 'index.js').read_text(encoding='utf8') == 'ok'
assert not (staged / 'linux-addon').exists()
assert (staged / 'docs-only' / 'index.js').is_file()
assert not (staged / 'docs-only' / 'README.md').exists()
assert not (staged / 'docs-only' / 'source.ts').exists()
@@ -0,0 +1,36 @@
"""Catch missing runtime assets and mismatched version identity before release."""
import ast
from pathlib import Path
import tomllib
ROOT = Path(__file__).resolve().parents[2]
def test_release_version_matches_python_and_windows_resources():
namespace = {}
exec((ROOT / 'src/dx_productivity/trial_task_center/version.py').read_text(), namespace)
version = namespace['VERSION']
assert tomllib.loads((ROOT / 'pyproject.toml').read_text())['project']['version'] == version
info = (ROOT / 'packaging/windows-version-info.txt').read_text()
assert f"StringStruct('ProductVersion', '{version}')" in info
parts = tuple(int(n) for n in version.split('.')) + (0,)
assert f'filevers={parts}' in info and f'prodvers={parts}' in info
def test_release_spec_includes_all_assets_and_complete_runtime():
tree = ast.parse((ROOT / 'packaging/DxPartReplace.spec').read_text())
constants = {node.value for node in ast.walk(tree) if isinstance(node, ast.Constant) and isinstance(node.value, str)}
assert 'src/dx_productivity/trial_task_center/assets' in constants
assert not any(isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
and node.func.id == 'stage_node_modules' for node in ast.walk(tree))
assert {'dsh-runtime/node_modules', 'dsh-runtime/task-plugin',
'issue-bootstrap.json', 'PySide6.QtWebEngineCore',
'PySide6.QtWebEngineWidgets'} <= constants
analysis = next(node for node in ast.walk(tree) if isinstance(node, ast.Call)
and isinstance(node.func, ast.Name) and node.func.id == 'Analysis')
options = {arg.arg: ast.literal_eval(arg.value) for arg in analysis.keywords
if arg.arg in {'hiddenimports', 'excludes'}}
web_dependencies = {'PySide6.QtWebChannel', 'PySide6.QtQml', 'PySide6.QtQuick',
'PySide6.QtOpenGL', 'PySide6.QtOpenGLWidgets'}
assert web_dependencies <= set(options['hiddenimports'])
assert web_dependencies.isdisjoint(options['excludes'])
+2 -1
View File
@@ -36,7 +36,8 @@ def ui(qtbot, tmp_path):
def settle():
qtbot.waitUntil(lambda:not window._workers and not window._task_query.busy
and not window._context_query.busy and not window._feedback_query.busy
and not window._log_presenter.query.busy and not window._resource_status.busy,timeout=5000)
and not window._log_presenter.query.busy and not window._resource_status.busy
and not window._dsh_operations.worker,timeout=5000)
def open_task(task):
window.open_task(task.task_id)
qtbot.waitUntil(lambda:not window._context_query.busy and not window._loading,timeout=5000)
+18
View File
@@ -8,6 +8,8 @@ class HarnessView(QWidget):
action_requested = Signal(object)
task_creation_requested = Signal(object)
task_creation_cancelled = Signal(object)
lifecycle_requested = Signal(object)
lifecycle_cancelled = Signal(object)
stopped = Signal()
def __init__(self, parent):
@@ -15,12 +17,16 @@ class HarnessView(QWidget):
self.starts = 0
self.binds = []
self.creation = {}
self.lifecycle = {}
self.operations = {}
self.lifecycle_results = []
self.results = []
def start(self):
self.starts += 1
def bind(self, snapshot, **kwargs):
self.operations = kwargs.get('operations', {})
self.binds.append(snapshot)
self.context = {'task_id': snapshot.task_id, 'revision': 'rev'}
@@ -30,6 +36,9 @@ class HarnessView(QWidget):
def complete_task_creation(self, value):
self.results.append(value)
def complete_lifecycle(self, value):
self.lifecycle_results.append(value)
def test_direct_navigation_opens_harness_and_returns_without_losing_task(ui, monkeypatch, qtbot):
window = ui.window
@@ -49,6 +58,15 @@ def test_direct_navigation_opens_harness_and_returns_without_losing_task(ui, mon
assert window._dsh_view.starts == 1
def test_dsh_navigation_surfaces_lazy_startup_failure(ui, monkeypatch, qtbot):
window = ui.window
def fail(_self):
raise RuntimeError('controlled missing WebEngine')
monkeypatch.setattr(type(window), '_create_dsh_view', fail)
qtbot.mouseClick(window.dsh_navigation, Qt.MouseButton.LeftButton)
assert 'DSH助手启动失败' in window.run_panel.operator_band.text()
def test_cross_task_harness_action_never_reaches_task_service(ui, monkeypatch):
window = ui.window
monkeypatch.setattr(type(window), '_create_dsh_view', lambda self: HarnessView(self), raising=False)
+435
View File
@@ -0,0 +1,435 @@
import json
import pytest
from PySide6.QtCore import Qt
def setup_view(ui, monkeypatch):
from .test_dsh_native_menu import HarnessView
monkeypatch.setattr(type(ui.window), '_create_dsh_view', lambda self: HarnessView(self))
ui.window._open_dsh()
return ui.window._dsh_view
@pytest.mark.parametrize('missing', [False, True])
def test_terminal_history_sums_persisted_counts_and_preserves_unknown(ui, monkeypatch, qtbot, missing):
from dx_productivity.dsh.task_lifecycle import preflight
view = setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
ids = [task.task_id for task in ui.tasks]
ctl.runs.begin('e' * 32, ids, preflight(ui.service, ids)['plan_hashes'])
tasks = [{'task_id': ids[0], 'saved_items': 2, 'failed_items': 0, 'no_match_items': 1},
{'task_id': ids[1], 'saved_items': None if missing else 3, 'failed_items': 1, 'no_match_items': 0}]
ctl.runs.finish('e' * 32, {'status': 'failed', 'tasks': tasks})
ctl.refresh()
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
row = view.operations['runs'][0]
assert row['counters'] == {'saved_items': None if missing else 5, 'failed_items': 1, 'no_match_items': 1}
assert row['tasks'] == tasks
def test_orphan_schedule_reconciliation_waits_for_native_confirmation(ui, monkeypatch, qtbot):
from dx_productivity.dsh.task_lifecycle import preflight
from PySide6.QtWidgets import QDialogButtonBox
view = setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
ids = [ui.tasks[0].task_id]
row = ctl.schedules.save({'task_ids': ids, 'not_before': '2026-10-30T12:00:00Z'}, preflight(ui.service, ids)['plan_hashes'])
ctl.schedules.claim(row['schedule_id'], run_id='9' * 32)
for key, accept in [('1', False), ('2', True)]:
ctl.request({'request_id': key * 32, 'spec': {'operation': 'reconcile_schedule', 'schedule_id': row['schedule_id']}})
qtbot.waitUntil(lambda: ctl.dialog is not None, timeout=5000)
assert ctl.schedules.get(row['schedule_id'])['status'] == 'claimed'
button = QDialogButtonBox.StandardButton.Ok if accept else QDialogButtonBox.StandardButton.Cancel
qtbot.mouseClick(ctl.dialog.buttons.button(button), Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: len(view.lifecycle_results) == int(key), timeout=5000)
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
assert ctl.schedules.get(row['schedule_id'])['status'] == ('interrupted' if accept else 'claimed')
assert view.lifecycle_results[-1]['status'] == 'schedule_reconciled'
assert view.operations['schedule_events'][0]['payload']['reconciled'] is True
assert not ui.calls
def test_missing_schedule_archive_degrades_its_section_without_hiding_history(ui, monkeypatch, qtbot):
view = setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
with ctl.schedules._connect() as db:
for _ in range(4):
ctl.schedules._event(db, 'a' * 32, '2026-10-31T12:00:00Z', 'result', None, {'status': 'completed'})
ctl.schedules.archive_events(keep=2)
next((ui.data / 'dsh/schedule-audit').glob('*.jsonl')).unlink()
ctl.refresh()
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
assert view.operations['schedule_audit']['status'] == 'unavailable'
assert view.operations['section_errors'] == [{'section': 'schedule_audit', 'code': 'section_unavailable'}]
assert view.operations['health']['status'] == 'degraded'
assert len(view.operations['schedule_events']) == 2
assert isinstance(view.operations['runs'], list)
def test_live_snapshot_reports_running_and_pause_request_without_claiming_paused(ui, monkeypatch):
view = setup_view(ui, monkeypatch)
window = ui.window
window._begin_run(ui.tasks[0].task_id)
window._bind_dsh_context()
assert view.binds[-1].status == 'running'
window._pause_queue()
window._bind_dsh_context()
assert view.binds[-1].status == 'running'
assert view.operations['live_run']['pause_requested']
window._finish_run()
assert not view.operations['live_run']['active']
def test_execution_health_follows_real_window_run_state(ui, monkeypatch, qtbot):
view = setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
ctl.refresh()
qtbot.waitUntil(lambda: ctl.worker is None)
ui.window._begin_run(ui.tasks[0].task_id)
ui.window._bind_dsh_context()
check = next(row for row in view.operations['health']['checks'] if row['name'] == 'execution')
assert check['code'] == 'execution_running'
ui.window._finish_run()
check = next(row for row in view.operations['health']['checks'] if row['name'] == 'execution')
assert check['code'] == 'idle'
def test_receipt_enrichment_failure_does_not_erase_executor_result(ui, monkeypatch):
from threading import Event
from dx_productivity.dsh import task_lifecycle as api
from dx_productivity.dsh.execution_runs import execute_confirmed_run
from dx_productivity.dsh.run_journal import RunJournal
original = RunJournal.finish
calls = []
def fail_enrichment(self, run_id, receipt):
calls.append(run_id)
if len(calls) > 1:
raise OSError('controlled enrichment persistence failure')
return original(self, run_id, receipt)
monkeypatch.setattr(RunJournal, 'finish', fail_enrichment)
ids = [ui.tasks[0].task_id]
receipt = execute_confirmed_run(ui.service, ui.data, ids, api.preflight(ui.service, ids), Event(), 'f' * 32)
assert receipt['status'] == 'completed'
assert receipt['reporting_errors'][0]['code'] == 'receipt_enrichment_unavailable'
assert RunJournal(ui.data).get('f' * 32)['result']['entries'][0]['state'] == 'completed'
def test_live_owner_and_saved_counts_do_not_follow_selected_task(ui, monkeypatch, qtbot):
from dx_productivity.dsh.live_state import read_live_run
from dx_productivity.trial_task_center.execution_feedback import ExecutionFeedback
feedback = ExecutionFeedback(ui.tasks[0].task_id, stage='save_and_close', stage_seconds=3)
value = read_live_run(ui.service, feedback, elapsed=10, pause_requested=True,
run_id='a' * 32, task_ids=[ui.tasks[0].task_id])
assert value['task_id'] == ui.tasks[0].task_id and value['name'] == ui.tasks[0].name
assert value['stage'] == 'save_and_close' and value['elapsed_seconds'] == 10
assert value['saved_items'] == 0 and value['active'] and value['pause_requested']
assert value['component_count_known'] is False
def test_last_execution_receipt_survives_later_catalog_reads(ui, monkeypatch, qtbot):
view = setup_view(ui, monkeypatch)
controller = ui.window._dsh_lifecycle
controller.request_id = 'b' * 32
controller._respond('b' * 32, status='completed', queue_id='c' * 32,
tasks=[{'task_id': ui.tasks[0].task_id, 'saved_items': 0, 'failed_items': 0, 'no_match_items': 2}])
controller.request({'request_id': 'd' * 32, 'capability': 'catalog', 'spec': {}})
qtbot.waitUntil(lambda: controller.worker is None)
assert view.operations['last_execution']['queue_id'] == 'c' * 32
assert view.operations['last_execution']['tasks'][0]['no_match_items'] == 2
def test_history_read_busy_state_is_published_and_rejection_is_visible(ui, monkeypatch, qtbot):
from threading import Event
view=setup_view(ui,monkeypatch); operations=ui.window._dsh_operations
started,release=Event(),Event()
def read():
started.set();assert release.wait(5);return {}
operations._work(read,lambda _:None,reserve_lane=False)
try:
qtbot.waitUntil(started.is_set)
ui.window._bind_dsh_context()
assert view.operations['busy'] is True
ui.window._dsh_lifecycle.request({'request_id':'b'*32,'capability':'execute',
'spec':{'operation':'start','task_ids':[ui.tasks[0].task_id]}})
assert view.lifecycle_results[-1]['status']=='busy'
assert view.operations['activity']['message']
assert not ui.calls
finally:
release.set()
qtbot.waitUntil(lambda: operations.worker is None)
assert view.operations['busy'] is False
def test_operations_context_publishes_health_and_decision_timeline(ui, monkeypatch, qtbot):
view = setup_view(ui, monkeypatch)
controller = ui.window._dsh_operations
controller.decisions.append({'incident_id': 'a' * 24, 'trigger': 'worker_error',
'evidence_refs': [], 'gates': {}, 'candidate_action': 'none',
'authorized_scope': {}, 'outcome': 'pending_issue'})
controller.refresh()
qtbot.waitUntil(lambda: controller.worker is None, timeout=5000)
assert 'health' in view.operations and isinstance(view.operations['health']['checks'], list)
assert view.operations['decisions'][0]['incident_id'] == 'a' * 24
def corrupt_decision_log(controller, damage):
row = controller.decisions.append({'incident_id': 'a' * 24, 'trigger': 'worker_error',
'gates': {}, 'candidate_action': 'none', 'authorized_scope': {}, 'outcome': 'pending_issue'})
with controller.decisions.path.open('a', encoding='utf8') as stream:
stream.write(json.dumps(row) + '\n' if damage == 'duplicate' else '{"sequence":')
return controller.decisions.path.read_bytes()
@pytest.mark.parametrize('operation', ['refresh', 'history', 'health', 'decisions', 'tickets'])
@pytest.mark.parametrize('damage', ['duplicate', 'partial'])
def test_corrupt_audit_is_isolated_from_aggregate_reads(ui, monkeypatch, qtbot, operation, damage):
from dx_productivity.dsh import task_lifecycle as api
view = setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
ids = [ui.tasks[0].task_id]
report = api.preflight(ui.service, ids)
ctl.runs.begin('a' * 32, ids, report['plan_hashes'])
incident = ui.data / 'dsh' / 'incidents' / ('b' * 24)
incident.mkdir(parents=True)
(incident / 'incident.json').write_text(json.dumps({'incident_id': 'b' * 24,
'ticket': {'number': 8, 'url': 'https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/issues/8'}}), encoding='utf8')
before = corrupt_decision_log(ctl, damage)
# A failed refresh must clear previously displayed decision rows only.
ctl.cache['decisions'] = [{'sequence': 99, 'incident_id': 'c' * 24}]
ctl.request({'request_id': 'b' * 32, 'spec': {'operation': operation}})
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
result = view.lifecycle_results[-1]
assert result['status'] == 'read'
assert result['runs'][0]['run_id'] == 'a' * 32
assert result['tickets'][0]['number'] == 8
assert result['health']['checks']
assert result['decisions'] == []
assert result['decision_audit']['status'] == 'corrupt'
assert result['decision_audit']['code'] == 'audit_log_corrupt'
assert result['decision_audit']['checked'] == 1
assert any(row['name'] == 'decision_audit' and row['status'] == 'degraded' for row in result['health']['checks'])
assert view.operations['activity']['status'] == 'read'
assert view.operations['decision_audit']['status'] == 'corrupt'
assert ctl.decisions.path.read_bytes() == before
assert ctl.decisions.verify()['valid'] is False
with pytest.raises(ValueError, match='decision_log_corrupt'):
ctl.decisions.append({'incident_id': 'd' * 24})
assert not ui.calls
def test_tick_retains_authorized_schedule_dispatch_when_audit_is_corrupt(ui, monkeypatch, qtbot):
from datetime import datetime, timedelta, timezone
from dx_productivity.dsh import task_lifecycle as api
view = setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
ids = [ui.tasks[0].task_id]
report = api.preflight(ui.service, ids)
schedule = ctl.schedules.save({'task_ids': ids, 'not_before': (datetime.now(timezone.utc) - timedelta(minutes=1)).isoformat(),
'auto_start': True}, report['plan_hashes'])
before = corrupt_decision_log(ctl, 'duplicate')
dispatched = []
monkeypatch.setattr(ctl, '_dispatch', lambda row, **options: dispatched.append((row, options)))
ctl.tick()
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
qtbot.waitUntil(lambda: bool(dispatched), timeout=5000)
assert view.operations['decision_audit']['status'] == 'corrupt'
assert view.operations['health']['checks']
assert ctl.cache['schedules'][0]['ready'] is True
assert dispatched[0][0]['schedule_id'] == schedule['schedule_id']
assert dispatched[0][1]['automatic'] is True
assert ctl.decisions.path.read_bytes() == before
assert not ui.calls
def test_audit_read_error_does_not_hide_health_or_leak_error_text(ui, monkeypatch, qtbot):
view = setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
def unavailable(*_args):
raise OSError('Authorization: Bearer private-test-value')
monkeypatch.setattr(ctl.decisions, 'list', unavailable)
ctl.refresh()
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
assert view.operations['decision_audit']['status'] == 'unavailable'
assert view.operations['health']['checks']
assert 'private-test-value' not in json.dumps(view.operations)
@pytest.mark.parametrize('section', ['experiences', 'schedule_events', 'schedule_audit'])
def test_independent_section_failure_keeps_schedules_and_health_visible(ui, monkeypatch, qtbot, section):
view = setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
def unavailable(*_args, **_kwargs):
raise OSError('Authorization: Bearer private-test-value')
target, method = (ctl.experiences, 'refresh') if section == 'experiences' else (
ctl.schedules, 'events' if section == 'schedule_events' else 'audit_status')
monkeypatch.setattr(target, method, unavailable)
ctl.refresh()
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
assert view.operations['section_errors'] == [{'section': section, 'code': 'section_unavailable'}]
assert view.operations['health']['status'] == 'degraded'
assert isinstance(view.operations['schedules'], list)
assert 'private-test-value' not in json.dumps(view.operations)
def test_stopping_generation_does_not_request_pause_of_confirmed_task(ui, monkeypatch):
view = setup_view(ui, monkeypatch); ctl=ui.window._dsh_lifecycle
task_id=ui.tasks[0].task_id; ui.window._begin_run(task_id)
ctl.request_id='9'*32; ctl.active_ids=(task_id,)
ctl.cancel({'request_id':'9'*32,'reason':'conversation_cancelled'})
assert not ui.window._batch_stop.is_set()
assert ctl.request_id=='9'*32
ctl.active_ids=(); ctl.request_id=None; ui.window._finish_run()
def test_native_batch_can_be_paused_using_published_full_scope(ui, monkeypatch):
view=setup_view(ui,monkeypatch); ctl=ui.window._dsh_lifecycle
ids=[task.task_id for task in ui.tasks]
ui.window._begin_run(ids[0]);ui.window._dsh_live_run['task_ids']=ids
ctl.request({'request_id':'a'*32,'capability':'execute','spec':{'operation':'pause','task_ids':ids}})
assert view.lifecycle_results[-1]['status']=='pause_requested' and ui.window._batch_stop.is_set()
ui.window._finish_run()
def test_scheduled_run_requires_native_confirmation_and_executes_once(ui, monkeypatch, qtbot):
from datetime import datetime, timezone, timedelta
from PySide6.QtWidgets import QDialogButtonBox
view = setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
ctl.request({'request_id': '1' * 32, 'spec': {'operation': 'schedule',
'task_ids': [ui.tasks[0].task_id], 'not_before': (datetime.now(timezone.utc)-timedelta(seconds=1)).isoformat(),
'priority': 'high', 'auto_start': True}})
qtbot.waitUntil(lambda: ctl.dialog is not None, timeout=5000)
assert 'OLD' in ctl.dialog.preview.toPlainText() and 'NEW' in ctl.dialog.preview.toPlainText()
assert '器件数量未知' in ctl.dialog.preview.toPlainText()
assert not ui.calls and not ctl.schedules.list_schedules()
qtbot.mouseClick(ctl.dialog.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: ctl.worker is None and bool(ctl.schedules.list_schedules()), timeout=5000)
ctl.tick()
qtbot.waitUntil(lambda: bool(ui.calls), timeout=10000)
qtbot.waitUntil(lambda: ctl.schedules.list_schedules()[0]['status'] == 'completed', timeout=10000)
ctl.tick(); ui.settle()
assert len(ui.calls) == 1
assert view.operations['last_execution']['tasks'][0]['no_match_items'] == 1
events = ctl.schedules.events()
assert [row['event'] for row in events] == ['result', 'dispatch']
assert events[1]['payload']['automatic'] is True
assert events[0]['payload']['receipt']['tasks'][0]['no_match_items'] == 1
def test_ops_impact_and_history_are_read_only_and_native_cancel_does_not_schedule(ui, monkeypatch, qtbot):
from PySide6.QtWidgets import QDialogButtonBox
view = setup_view(ui, monkeypatch); ctl = ui.window._dsh_operations
ctl.request({'request_id': '2' * 32, 'spec': {'operation': 'impact', 'task_ids': [ui.tasks[0].task_id]}})
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
assert view.operations['impact']['component_count'] is None and not ui.calls
ctl.request({'request_id': '3' * 32, 'spec': {'operation': 'schedule_dialog', 'task_ids': [ui.tasks[0].task_id]}})
qtbot.waitUntil(lambda: ctl.dialog is not None, timeout=5000)
qtbot.mouseClick(ctl.dialog.buttons.button(QDialogButtonBox.StandardButton.Cancel), Qt.MouseButton.LeftButton)
assert not ctl.schedules.list_schedules() and not ui.calls
def test_confirmed_execution_writes_reserved_checkpoint_and_persistent_run_receipt(ui, monkeypatch, qtbot):
from PySide6.QtWidgets import QDialogButtonBox
view = setup_view(ui, monkeypatch); ctl = ui.window._dsh_lifecycle
ctl.request({'request_id': '4' * 32, 'capability': 'execute',
'spec': {'operation': 'start', 'task_ids': [ui.tasks[0].task_id]}})
qtbot.waitUntil(lambda: ctl.dialog is not None, timeout=5000)
assert '器件数量未知' in ctl.dialog.preview.toPlainText()
qtbot.mouseClick(ctl.dialog.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: bool(view.lifecycle_results), timeout=10000)
result = view.lifecycle_results[-1]
assert result['queue_id'] == result['run_id']
from dx_productivity.dsh.run_journal import RunJournal
journal = RunJournal(ui.data)
assert journal.get(result['run_id'])['result']['tasks'][0]['no_match_items'] == 1
assert (ui.data / 'task-queues' / (result['run_id']+'.json')).is_file()
ui.settle()
def test_completed_queue_outcome_survives_unavailable_post_run_context(ui, monkeypatch):
from threading import Event
from dx_productivity.dsh import task_lifecycle as api
from dx_productivity.dsh.execution_runs import execute_confirmed_run
from dx_productivity.dsh.run_journal import RunJournal
ids = [ui.tasks[0].task_id]; report = api.preflight(ui.service, ids)
original = ui.service.task_context
def lost_context(*args, **kwargs):
if ui.calls:
raise OSError('controlled receipt read failure')
return original(*args, **kwargs)
monkeypatch.setattr(ui.service, 'task_context', lost_context)
receipt = execute_confirmed_run(ui.service, ui.data, ids, report, Event(), '5' * 32)
assert receipt['status'] == 'completed' and receipt['entries'][0]['state'] == 'completed'
assert receipt['tasks'][0]['no_match_items'] is None and receipt['reporting_errors']
assert RunJournal(ui.data).get('5' * 32)['result']['entries'][0]['state'] == 'completed'
assert len(ui.calls) == 1
def test_schedule_claim_journal_failure_is_retained_as_interrupted_without_execution(ui, monkeypatch):
import pytest
from datetime import datetime, timezone, timedelta
from threading import Event
from dx_productivity.dsh import task_lifecycle as api
from dx_productivity.dsh.execution_runs import execute_confirmed_run
from dx_productivity.dsh.run_journal import RunJournal
from dx_productivity.dsh.scheduling import ScheduleStore
ids = [ui.tasks[0].task_id]; report = api.preflight(ui.service, ids)
schedules = ScheduleStore(ui.data)
row = schedules.save({'task_ids': ids, 'not_before': (datetime.now(timezone.utc)-timedelta(seconds=1)).isoformat(),
'auto_start': True}, report['plan_hashes'])
def failed_begin(*_args, **_kwargs):
raise OSError('controlled journal failure')
monkeypatch.setattr(RunJournal, 'begin', failed_begin)
with pytest.raises(OSError):
execute_confirmed_run(ui.service, ui.data, ids, report, Event(), '6' * 32, schedule=row)
actual = schedules.get(row['schedule_id'])
assert actual['status'] == 'interrupted' and actual['run_id'] == '6' * 32
assert not ui.calls
def test_saved_target_cell_survives_context_read_and_impact_preview(ui):
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
from dx_productivity.dsh.impact import execution_impact
task_id = ui.tasks[0].task_id
project = ui.service.projects(task_id)[0]
row = TargetPlanRow(ComponentTarget(project.path, 'MAIN', '1', 'uid-one', 'R1', 'OLD', 'Original'),
enabled=True, new_part_number='NEW', target_cell='QFN')
ui.store.record_target_inventory(task_id, [row.target])
ui.service.replace_target_plan(task_id, [row])
assert ui.service.task_context(task_id).targets[0].target_cell == 'QFN'
report = execution_impact(ui.service, [task_id])
assert report['component_count'] == 1 and report['rows'][0]['target_cell'] == 'QFN'
def test_resume_original_queue_after_controller_restart_skips_completed_step(ui, monkeypatch, qtbot):
from threading import Event
from PySide6.QtWidgets import QDialogButtonBox
from dx_productivity.dsh import task_lifecycle as api
from dx_productivity.dsh.execution_runs import execute_confirmed_run
from dx_productivity.dsh.run_journal import RunJournal
task_id = ui.tasks[0].task_id
ui.service.add_rule(task_id, 'SECOND', 'TARGET')
ids=[task_id]; report=api.preflight(ui.service, ids)
stop=Event()
child = ui.service.for_project_task(task_id)
original = child._quick_run_preparer._process_runner
def pausing(command, timeout):
result = original(command, timeout)
stop.set()
return result
child._quick_run_preparer._process_runner = pausing
first=execute_confirmed_run(ui.service, ui.data, ids, report, stop, '7'*32)
assert first['status']=='paused' and len(ui.calls)==1
child._quick_run_preparer._process_runner = original
view = setup_view(ui, monkeypatch)
ui.window._dsh_lifecycle.request({'request_id':'8'*32,'capability':'execute',
'spec':{'operation':'resume','run_id':'7'*32}})
qtbot.waitUntil(lambda: ui.window._dsh_lifecycle.dialog is not None,timeout=5000)
assert '77777777' in ui.window._dsh_lifecycle.dialog.preview.toPlainText()
qtbot.mouseClick(ui.window._dsh_lifecycle.dialog.buttons.button(QDialogButtonBox.StandardButton.Ok),Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: bool(view.lifecycle_results),timeout=15000)
assert view.lifecycle_results[-1]['run_id']=='7'*32
assert view.lifecycle_results[-1]['status']=='completed' and len(ui.calls)==2
assert RunJournal(ui.data).get('7'*32)['status']=='completed'
ui.settle()
+214
View File
@@ -0,0 +1,214 @@
import pytest
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QDialogButtonBox
from dx_productivity.trial_task_center.errors import TaskCenterError
def lifecycle():
from dx_productivity.dsh import task_lifecycle
return task_lifecycle
def test_catalog_and_preflight_use_real_tasks_and_do_not_execute(ui):
api = lifecycle()
catalog = api.catalog(ui.service)
assert {t['task_id'] for t in catalog['tasks']} == {t.task_id for t in ui.tasks}
report = api.preflight(ui.service, [ui.tasks[0].task_id])
assert report['ready'] and report['tasks'][0]['enabled_rules'] == 1
assert report['cad_connection_checked'] is False
assert not ui.calls
detail = api.catalog(ui.service, ui.tasks[0].task_id)['detail']
assert detail['rules'][0]['old_part_number'] == 'OLD'
assert detail['rules'][0]['new_part_number'] == 'NEW'
ui.service.delete_task(ui.tasks[0].task_id)
report = api.preflight(ui.service, [ui.tasks[0].task_id])
assert not report['ready'] and report['tasks'][0]['blockers']
def test_confirmed_rule_change_previews_batch_and_commits_once(ui):
api = lifecycle()
spec = {'operation': 'update', 'task_id': ui.tasks[0].task_id,
'patch': {'name': 'Renamed', 'rules': [{'old_part_number': 'OLD', 'new_part_number': 'NEXT'}]}}
plan = api.preview(ui.service, spec)
assert {t['task_id'] for t in plan['affected_tasks']} == {t.task_id for t in ui.tasks}
assert ui.store.list_rules(ui.tasks[0].task_id)[0].new_part_number == 'NEW'
result = api.apply_confirmed(ui.service, 'a' * 32, plan)
assert result['status'] == 'updated'
assert ui.store.get_task(ui.tasks[0].task_id).name == 'Renamed'
for task in ui.tasks:
assert ui.store.list_rules(task.task_id)[0].new_part_number == 'NEXT'
assert api.apply_confirmed(ui.service, 'a' * 32, plan)['replayed']
from dx_productivity.trial_task_center.store import TaskStore
reopened = TaskStore(ui.store.path)
try:
assert reopened.assistant_operation_receipt('a' * 32)['result'] == result
finally:
reopened.close()
assert not ui.calls
def test_preview_includes_derived_cell_reset_and_custom_value_enable(ui):
api = lifecycle()
rule = ui.store.list_rules(ui.tasks[0].task_id)[0]
ui.service.update_rule(rule.rule_id, old_part_number='OLD', new_part_number='NEW', enabled=True, target_cell='QFN')
plan = api.preview(ui.service, {'operation': 'update', 'task_id': ui.tasks[0].task_id,
'patch': {'rules': [{'old_part_number': 'OLD', 'new_part_number': 'NEXT', 'custom_value': 'Explicit value'}]}})
changes = {row['field']: row for row in plan['changes']}
assert changes['OLD.target_cell']['before'] == 'QFN' and changes['OLD.target_cell']['after'] == ''
assert changes['OLD.custom_value_enabled']['after'] is True
api.apply_confirmed(ui.service, '9' * 32, plan)
actual = ui.store.list_rules(ui.tasks[0].task_id)[0]
assert actual.target_cell == '' and actual.custom_value_enabled
def test_stale_preview_rejects_all_changes_and_invalid_patch_is_not_applied(ui):
api = lifecycle()
plan = api.preview(ui.service, {'operation': 'update', 'task_id': ui.tasks[0].task_id,
'patch': {'name': 'Unapplied'}})
ui.service.update_task(ui.tasks[0].task_id, name='Changed elsewhere', note='')
with pytest.raises(TaskCenterError, match='assistant_stale'):
api.apply_confirmed(ui.service, 'b' * 32, plan)
assert ui.store.get_task(ui.tasks[0].task_id).name == 'Changed elsewhere'
with pytest.raises(TaskCenterError):
api.preview(ui.service, {'operation': 'update', 'task_id': ui.tasks[0].task_id,
'patch': {'confirmed': True}})
def test_archive_keeps_evidence_and_preflight_detects_missing_project(ui):
api = lifecycle()
task_id = ui.tasks[0].task_id
plan = api.preview(ui.service, {'operation': 'archive', 'task_id': task_id})
assert api.apply_confirmed(ui.service, 'c' * 32, plan)['status'] == 'archived'
assert ui.store.get_task(task_id).status.value == 'deleted'
assert ui.store.list_rules(task_id)
ui.service.restore_task(task_id)
ui.store.list_projects(task_id)[0].path.unlink()
assert not api.preflight(ui.service, [task_id])['ready']
def controller(ui, monkeypatch):
from .test_dsh_native_menu import HarnessView
monkeypatch.setattr(type(ui.window), '_create_dsh_view', lambda self: HarnessView(self))
ui.window._open_dsh()
return ui.window._dsh_lifecycle, ui.window._dsh_view
def request(ui, operation, **values):
return {'request_id': 'd' * 32, 'capability': 'manage',
'spec': {'operation': operation, 'task_id': ui.tasks[0].task_id, **values}}
def test_dialog_cancel_and_stale_confirm_do_not_modify(ui, monkeypatch, qtbot):
ctl, view = controller(ui, monkeypatch)
ctl.request(request(ui, 'update', patch={'name': 'Never'}))
qtbot.waitUntil(lambda: ctl.dialog is not None, timeout=5000)
qtbot.mouseClick(ctl.dialog.buttons.button(QDialogButtonBox.StandardButton.Cancel), Qt.MouseButton.LeftButton)
assert view.lifecycle_results[-1]['status'] == 'cancelled'
assert ui.service.get_task(ui.tasks[0].task_id).name != 'Never'
ui.settle()
def test_dialog_executes_existing_queue_and_reports_real_no_match(ui, monkeypatch, qtbot):
ctl, view = controller(ui, monkeypatch)
ctl.request({'request_id': 'e' * 32, 'capability': 'execute',
'spec': {'operation': 'start', 'task_ids': [ui.tasks[0].task_id]}})
qtbot.waitUntil(lambda: ctl.dialog is not None, timeout=5000)
assert not ui.calls
qtbot.mouseClick(ctl.dialog.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: bool(view.lifecycle_results), timeout=15000)
result = view.lifecycle_results[-1]
assert result['status'] == 'completed' and result['tasks'][0]['no_match_items'] == 1
assert result['tasks'][0]['saved_items'] == 0 and ui.calls
ui.settle()
def test_cancel_during_preview_read_never_opens_later_dialog(ui, monkeypatch, qtbot):
ctl, view = controller(ui, monkeypatch)
value = request(ui, 'update', patch={'name': 'Never'})
ctl.request(value)
ctl.cancel({'request_id': value['request_id']})
ui.settle()
assert ctl.dialog is None
assert view.lifecycle_results[-1]['status'] == 'cancelled'
def test_abort_during_confirmed_commit_retains_actual_mutation_receipt(ui, monkeypatch, qtbot):
from threading import Event
ctl, view = controller(ui, monkeypatch)
api = lifecycle(); original = api.apply_confirmed
entered, release = Event(), Event()
def delayed(*args):
entered.set()
assert release.wait(5)
return original(*args)
monkeypatch.setattr(api, 'apply_confirmed', delayed)
value = request(ui, 'update', patch={'name': 'Committed truthfully'})
ctl.request(value)
qtbot.waitUntil(lambda: ctl.dialog is not None, timeout=5000)
qtbot.mouseClick(ctl.dialog.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton)
try:
qtbot.waitUntil(entered.is_set, timeout=5000)
ctl.cancel({'request_id': value['request_id']})
assert not view.lifecycle_results
finally:
release.set()
qtbot.waitUntil(lambda: bool(view.lifecycle_results), timeout=5000)
assert view.lifecycle_results[-1]['status'] == 'updated'
assert ui.service.get_task(ui.tasks[0].task_id).name == 'Committed truthfully'
assert ui.store.assistant_operation_receipt(value['request_id'])['result']['status'] == 'updated'
ui.settle()
def test_stale_native_preview_rejects_confirmation(ui, monkeypatch, qtbot):
ctl, view = controller(ui, monkeypatch)
ctl.request(request(ui, 'update', patch={'name': 'Never'}))
qtbot.waitUntil(lambda: ctl.dialog is not None and ctl.worker is None, timeout=5000)
ui.service.update_task(ui.tasks[0].task_id, name='External edit', note='')
qtbot.mouseClick(ctl.dialog.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: bool(view.lifecycle_results), timeout=5000)
assert view.lifecycle_results[-1]['code'] == 'assistant_stale'
assert ui.service.get_task(ui.tasks[0].task_id).name == 'External edit'
ui.settle()
def test_copy_opens_native_new_scope_dialog_and_returns_actual_ids(ui, monkeypatch, qtbot, tmp_path):
ctl, view = controller(ui, monkeypatch)
ui.service.update_rule(ui.store.list_rules(ui.tasks[0].task_id)[0].rule_id,
old_part_number='OLD', new_part_number='NEW', enabled=False)
root = tmp_path / 'new-scope'; root.mkdir()
project = root / 'new.prj'
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
ctl.request(request(ui, 'copy'))
creation = ui.window._dsh_task_creation
qtbot.waitUntil(lambda: creation.dialog is not None, timeout=5000)
dialog = creation.dialog
assert not dialog.spec['rules'][0]['enabled']
qtbot.keyClicks(dialog.directory, str(root))
qtbot.mouseClick(dialog.scan, Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: dialog._worker is None and dialog.projects.count() == 1, timeout=5000)
qtbot.mouseClick(dialog.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: bool(view.lifecycle_results), timeout=5000)
result = view.lifecycle_results[-1]
assert result['created_count'] == 1
assert not ui.store.list_rules(result['task_ids'][0])[0].enabled
assert result['task_ids'][0] not in {t.task_id for t in ui.tasks}
assert not ui.calls
ui.settle()
def test_pause_uses_active_stop_control_and_refuses_other_scope(ui, monkeypatch):
from dx_productivity.trial_task_center.stop_control import StopControl
ctl, view = controller(ui, monkeypatch)
owner = ui.tasks[0].task_id
ui.window._active_quick_run_task_id = owner
ui.window._batch_stop = StopControl()
ctl.request({'request_id': '1' * 32, 'capability': 'execute',
'spec': {'operation': 'pause', 'task_ids': [ui.tasks[1].task_id]}})
assert not ui.window._batch_stop.is_set()
assert view.lifecycle_results[-1]['status'] == 'rejected'
ctl.request({'request_id': '2' * 32, 'capability': 'execute',
'spec': {'operation': 'pause', 'task_ids': [owner]}})
assert ui.window._batch_stop.is_set() and not ui.window._batch_stop.force_event.is_set()
assert view.lifecycle_results[-1]['status'] == 'pause_requested'
ui.window._finish_run()
+34 -1
View File
@@ -10,6 +10,14 @@ from PySide6.QtCore import Signal
from PySide6.QtWidgets import QMessageBox,QWidget
def test_project_plan_discard_is_safe_after_qt_reclaims_report_control(ui, qtbot):
"""Fixture cleanup must tolerate a child control reclaimed during window teardown."""
import shiboken6
report_toggle = ui.window.plan_panel.report_toggle
shiboken6.delete(report_toggle)
ui.window.plan_panel.discard_all()
@pytest.mark.parametrize('scope',['single','batch'])
@pytest.mark.parametrize('stop_kind',['none','pause','force','pause_then_reauthorize'])
def test_last_failed_item_keeps_stop_intent_in_automatic_diagnosis(ui,qtbot,monkeypatch,scope,stop_kind):
@@ -48,7 +56,10 @@ def test_last_failed_item_keeps_stop_intent_in_automatic_diagnosis(ui,qtbot,monk
assert len(outcomes)==1
# This is the review's edge: the queue is exhausted, so paused is False
# even though the original control may carry a stop/force request.
assert outcomes[0].paused is False
# DSH persists a receipt for single runs and returns (queue, receipt) for
# grouped runs. Observe the real result without replacing its executor.
result = outcomes[0][0] if isinstance(outcomes[0], tuple) else outcomes[0]
assert (result['paused'] if isinstance(result, dict) else result.paused) is False
qtbot.waitUntil(lambda:automation.worker is None and
automation.latest.get('status')in {'resolved','pending_issue','escalated'},timeout=10000)
ui.settle()
@@ -82,6 +93,8 @@ class ProtocolSignals(QWidget):
diagnosis_event=Signal(object)
task_creation_cancelled=Signal(object)
action_requested=Signal(object)
lifecycle_requested=Signal(object)
lifecycle_cancelled=Signal(object)
def protocol_state(qtbot):
@@ -93,12 +106,32 @@ def protocol_state(qtbot):
task_creation_requested=sink.task_creation_requested,diagnosis_event=sink.diagnosis_event,
ready=sink.ready,
task_creation_cancelled=sink.task_creation_cancelled,action_requested=sink.action_requested,
lifecycle_requested=sink.lifecycle_requested,lifecycle_cancelled=sink.lifecycle_cancelled,
context={'task_id':'t','revision':'rev'},last_error='')
state._reset_output=lambda:NativeHarnessView._reset_output(state)
state._reset_output()
return state,chunks
@pytest.mark.parametrize('prefix,signal', [('DX_DSH_LIFECYCLE_REQUEST', 'lifecycle_requested'),
('DX_DSH_LIFECYCLE_CANCEL', 'lifecycle_cancelled')])
def test_lifecycle_protocol_survives_invalid_lines_and_split_utf8(qtbot, prefix, signal):
from dx_productivity.trial_task_center.ui.dsh_native import NativeHarnessView
state,chunks=protocol_state(qtbot)
received=[]
getattr(state,signal).connect(received.append)
payload={'request_id':'b'*32,'spec':{'operation':'reconcile_schedule','title':'核对排期🔧'}}
invalid=(prefix+' {invalid private-diagnostic\n'+prefix+' []\n').encode('utf8')
valid=(prefix+' '+json.dumps(payload,ensure_ascii=False)+'\n').encode('utf8')
split=valid.index('核'.encode('utf8'))+1
chunks.extend([invalid+valid[:split],valid[split:]])
NativeHarnessView._stdout(state)
assert not received
NativeHarnessView._stdout(state)
assert received==[payload]
assert 'private-diagnostic' not in state.last_error
@pytest.mark.parametrize('stop_kind',['none','pause','force'])
def test_worker_exception_handoff_keeps_original_run_control(ui,qtbot,monkeypatch,stop_kind):
from dx_productivity.trial_task_center.errors import TaskCenterError
@@ -9,6 +9,21 @@ from PySide6.QtCore import Qt
from PySide6.QtGui import QCloseEvent
@pytest.mark.parametrize('entry', ['current', 'batch'])
def test_native_preflight_error_is_visible_and_does_not_start_execution(ui, monkeypatch, entry):
from dx_productivity.trial_task_center.errors import TaskCenterError
def failed(*args, **kwargs):
raise TaskCenterError('assistant_stale', '受控预检异常,请重新核对。')
monkeypatch.setattr('dx_productivity.dsh.task_lifecycle.preflight', failed)
window = ui.window
if entry == 'current':
window._prepare_quick_run()
else:
window._execute_project_tasks()
assert '受控预检异常' in window.run_panel.operator_band.text()
assert not ui.calls and not window._dsh_authorized_tasks
@pytest.mark.parametrize('accept',[False,True])
def test_current_task_executes_only_after_confirmation_and_no_match_is_completed(ui,accept):
w=ui.window;confirmations=[]
@@ -21,6 +36,9 @@ def test_current_task_executes_only_after_confirmation_and_no_match_is_completed
if accept:
assert ui.service.quick_run_progress(ui.tasks[0].task_id).no_match_items==1
assert w.run_panel.new_round_button.isEnabled()
from dx_productivity.dsh.run_journal import RunJournal
rows=RunJournal(ui.data).list_runs()
assert len(rows)==1 and rows[0]['result']['tasks'][0]['no_match_items']==1
def test_batch_execute_button_tracks_remaining_tasks(ui):
@@ -58,6 +76,18 @@ def test_mapping_enable_uses_model_and_persists_without_row_widgets(ui):
assert not w.run_panel.quick_run_button.isEnabled()
def test_native_batch_records_complete_order_and_actual_results(ui):
from dx_productivity.dsh.run_journal import RunJournal
window=ui.window
window._quick_run_confirmer=lambda *args:True
window._execute_project_tasks();ui.settle()
rows=RunJournal(ui.data).list_runs()
assert len(ui.calls)==2 and len(rows)==1
assert rows[0]['task_ids']==[task.task_id for task in ui.tasks]
assert rows[0]['status']=='completed'
assert all(task['saved_items']==0 and task['no_match_items']==1 for task in rows[0]['result']['tasks'])
def test_regular_mutation_locks_navigation_until_completion(ui,qtbot):
w=ui.window;started,release=Event(),Event();received=[]
def work():
+7
View File
@@ -63,6 +63,13 @@ def test_tasks_execute_in_confirmed_order_and_finished_queue_does_not_repeat(tmp
assert len(service.calls) == 4
def test_changed_confirmed_plan_is_rejected_before_any_executor(tmp_path):
service = Service(tmp_path)
with pytest.raises(TaskCenterError, match='assistant_stale'):
execute_task_queue(service, ('A',), stop_event=Event(), expected_plan_hashes={'A': 'stale'})
assert not service.calls
def test_safe_failure_is_reported_and_next_task_runs(tmp_path):
service = Service(tmp_path, {'A': TaskCenterError('quick_run_preflight', 'target absent')})
result = execute_task_queue(service, ('A', 'B'), stop_event=Event())
+19 -4
View File
@@ -5,7 +5,7 @@ from threading import Event
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.task_queue import execute_task_queue
from dx_productivity.trial_task_center.task_queue import execute_task_queue, _plan_hash
from test_task_queue import Service as QueueService
from test_ui_remediation import window
@@ -31,6 +31,8 @@ def test_retry_preparation_rebuilds_batch_only_after_success(window, qtbot, tmp_
queue = QueueService(tmp_path / 'queue', {a: 'failed', b: lambda stop: stop.set()})
original = execute_task_queue(queue, (a, b), stop_event=Event())
assert [entry.state for entry in original.entries] == ['failed', 'paused']
original_path = queue._logging.root / 'task-queues' / (original.queue_id + '.json')
original_bytes = original_path.read_bytes()
window._project_queues[group] = (original.queue_id, (a, b))
window._context = replace(window._context, phase='retry')
window._update_gates()
@@ -47,10 +49,23 @@ def test_retry_preparation_rebuilds_batch_only_after_success(window, qtbot, tmp_
assert group not in window._project_queues
queue.outcomes.clear()
window._quick_run_confirmer = lambda *args: True
monkeypatch.setattr('dx_productivity.trial_task_center.task_queue.execute_task_queue',
lambda service, ids, **kwargs: execute_task_queue(queue, ids, **kwargs))
def execute_fixture(service, ids, **kwargs):
# The native batch now carries frozen real-service plan hashes. Verify
# that scope before adapting hashes to this executor's synthetic paths.
if kwargs.get('expected_plan_hashes') is not None:
assert kwargs['expected_plan_hashes'] == {
task_id: _plan_hash(service.for_project_task(task_id), task_id) for task_id in ids}
kwargs['expected_plan_hashes'] = {
task_id: _plan_hash(queue.for_project_task(task_id), task_id) for task_id in ids}
return execute_task_queue(queue, ids, **kwargs)
monkeypatch.setattr('dx_productivity.trial_task_center.task_queue.execute_task_queue', execute_fixture)
window.task_list.queue_button.click()
qtbot.waitUntil(lambda: not window._workers and not window._loading and not window._context_query.busy)
assert [task_id for event, task_id in queue.calls if event == 'start'] == [a, b, a, b]
assert [task_id for event, task_id in queue.calls if event == 'start'] == [a, b, a, b], window.run_panel.operator_band.text()
assert original_path.read_bytes() == original_bytes
from dx_productivity.dsh.run_journal import RunJournal
runs = RunJournal(window.service.layout_settings_path.parent).list_runs()
assert len(runs) == 1 and runs[0]['run_id'] != original.queue_id
assert runs[0]['task_ids'] == [a, b]