feat(dsh): add durable supervision, scheduling and operations dock
This commit is contained in:
1 parent
f861a3d386
commit
736b582bc1
46 files changed
+4122
-93
No files matched your search
@@ -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)
|
||||
@@ -0,0 +1,134 @@
|
||||
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_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
|
||||
@@ -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'
|
||||
@@ -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)
|
||||
@@ -0,0 +1,155 @@
|
||||
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 True
|
||||
assert rows[0]['dispatchable'] is False # model-supplied auto_start never grants authority
|
||||
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_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'])
|
||||
@@ -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]
|
||||
Reference in new issue
Block a user