fix(dsh): align recovery, scheduling audit and credential guarantees

This commit is contained in:
阿白叔 committed 2026-10-31 14:16:27 +08:00
1 parent e565f67b46
commit 9552f1eb95
32 files changed
+514 -135

No files matched your search

+15
View File
@@ -23,6 +23,21 @@ GOOD = {'queue_complete': True, 'failed_items': 0, 'interrupted': False, 'paused
'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)
+2 -5
View File
@@ -5,7 +5,7 @@ from dx_productivity.dsh.health import HealthStore
class _Service:
_workers = set()
pass
def test_health_snapshot_reports_unconfigured_provider_and_local_stores(tmp_path, monkeypatch):
@@ -19,14 +19,11 @@ def test_health_snapshot_reports_unconfigured_provider_and_local_stores(tmp_path
def test_health_snapshot_marks_active_worker_and_static_issue_token(tmp_path, monkeypatch):
class Busy(_Service):
_workers = {object()}
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(Busy())
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'
+13 -2
View File
@@ -6,13 +6,15 @@ from dx_productivity.dsh.issue_broker import IssueBroker, IssueBrokerConfig
TARGET = {'server': 'https://git.test', 'repository': 'owner/repo'}
def test_broker_exchange_issues_short_lived_fixed_target_token(monkeypatch):
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' and 30 <= value['expires_in'] <= 3600
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']
@@ -30,3 +32,12 @@ def test_broker_rejects_wrong_target_and_reuses_idempotency(monkeypatch):
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
+18 -7
View File
@@ -6,16 +6,17 @@ from dx_productivity.dsh.issue_transport import IssueTransport
TARGET = {'server': 'https://git.test', 'repository': 'owner/repo'}
def test_transport_uses_short_lived_broker_credential_without_caching_token(tmp_path, monkeypatch):
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: {'token': 'short-secret', 'expires_in': 120})
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 short-secret'
assert value['rotation_required'] is False
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('short-secret' not in p.read_text(encoding='utf8', errors='ignore') for p in cache if p.is_file())
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):
@@ -40,7 +41,17 @@ 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: {'token': 'ephemeral', 'expires_in': 60})
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 ephemeral'}
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'
+38 -22
View File
@@ -1,32 +1,48 @@
from types import SimpleNamespace as NS
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
class Service:
def __init__(self, contexts, hashes=None): self.contexts, self.current_plan_hashes = contexts, hashes or {'t1': 'h1', 't2': 'h2'}
def task_context(self, task_id): return self.contexts[task_id]
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 context(status='ready', interrupted=False):
return NS(task=NS(status=NS(value=status), name='Board'), progress=NS(queue_complete=status == 'completed',
saved_items=1 if status == 'completed' else 0, failed_items=0, no_match_items=0), interrupted=interrupted)
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 inspected():
return {'run_id': 'a' * 32, 'task_ids': ['t1', 't2'], 'remaining_task_ids': ['t2'],
'plan_hashes': {'t1': 'h1', 't2': 'h2'}, 'queue_available': True, 'resume_ready': True,
'blockers': [], 'tasks': [{'task_id': 't1', 'status': 'completed'}, {'task_id': 't2', 'status': 'ready'}]}
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_resume_diff_is_safe_for_unchanged_frozen_scope():
value = resume_diff(Service({'t1': context('completed'), 't2': context()}), inspected())
assert value['safe'] is True and value['completed'] == ['t1'] and value['remaining'] == ['t2']
assert value['changed'] == []
def test_resume_diff_blocks_plan_change_and_uncertainty():
row = inspected()
value = resume_diff(Service({'t1': context('completed', interrupted=True), 't2': context()}, {'t1': 'changed', 't2': 'h2'}), row)
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 'plan_changed' in value['blockers'] and 'interrupted' in value['blockers']
assert value['changed'] == ids
+35 -2
View File
@@ -49,12 +49,45 @@ def test_due_order_and_manual_confirmation_without_execution(project_service):
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 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)
+54
View File
@@ -25,6 +25,40 @@ def test_live_snapshot_reports_running_and_pause_request_without_claiming_paused
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
@@ -165,6 +199,22 @@ def test_audit_read_error_does_not_hide_health_or_leak_error_text(ui, monkeypatc
assert 'private-test-value' not in json.dumps(view.operations)
@pytest.mark.parametrize('section', ['experiences', 'schedule_events'])
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')
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)
@@ -204,6 +254,10 @@ def test_scheduled_run_requires_native_confirmation_and_executes_once(ui, monkey
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):
@@ -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=[]