fix(dsh): isolate damaged decision audit from operations refresh
This commit is contained in:
1 parent
a99f84b25e
commit
cd66d63f4f
7 files changed
+149
-5
No files matched your search
@@ -29,17 +29,20 @@ window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{
|
||||
h('div',{style:{whiteSpace:'pre-wrap',color:'var(--dsw-alias-label-secondary)',lineHeight:1.8}},text));
|
||||
const health=data?.operations?.health;
|
||||
const decisions=data?.operations?.decisions||[];
|
||||
const audit=data?.operations?.decision_audit;
|
||||
const auditUnavailable=audit&&['corrupt','unavailable'].includes(audit.status);
|
||||
const healthText=health?.checks?.map(row=>`${row.name}: ${row.status} · ${row.message}`).join('\n')||'正在读取运行健康…';
|
||||
return h('div',{'data-testid':'dx-task-overview'},
|
||||
section('当前任务',data?(data.task_name||data.task_id||'尚未选择任务'):'读取中…'),
|
||||
h('section',{'data-testid':'dx-health-summary',style:{marginBottom:24}},
|
||||
h('h3',{style:{fontSize:14,fontWeight:500,marginBottom:10}},'运行健康 · '+(health?.status||'读取中')),
|
||||
h('div',{style:{whiteSpace:'pre-wrap',color:'var(--dsw-alias-label-secondary)',lineHeight:1.8}},healthText),
|
||||
h('button',{type:'button',onClick:()=>perform({operation:'health'}),style:{...buttonStyle,marginTop:8}},'重新检查健康状态')),
|
||||
h('button',{'data-testid':'dx-health-refresh',type:'button',onClick:()=>perform({operation:'health'}),style:{...buttonStyle,marginTop:8}},'重新检查健康状态')),
|
||||
h('section',{'data-testid':'dx-decision-timeline',style:{marginBottom:24}},
|
||||
h('h3',{style:{fontSize:14,fontWeight:500,marginBottom:10}},'自动处理决策记录'),
|
||||
decisions.length?decisions.slice(0,5).map(row=>h('p',{key:row.record_hash,style:{fontSize:12,lineHeight:1.7,margin:'6px 0'}},`#${row.sequence} · ${row.trigger} · ${row.outcome} · ${row.human_takeover?'人工接管':'自动策略'}`)):h('p',{style:{fontSize:12,color:'var(--dsw-alias-label-secondary)'}},'暂无自动处理记录。'),
|
||||
h('button',{type:'button',onClick:()=>perform({operation:'decisions'}),style:{...buttonStyle,marginTop:8}},'刷新决策记录')),
|
||||
auditUnavailable?h('p',{'data-testid':'dx-decision-audit-error',role:'status',style:{fontSize:12,lineHeight:1.7}},audit.message):
|
||||
decisions.length?decisions.slice(0,5).map(row=>h('p',{key:row.record_hash,style:{fontSize:12,lineHeight:1.7,margin:'6px 0'}},`#${row.sequence} · ${row.trigger} · ${row.outcome} · ${row.human_takeover?'人工接管':'自动策略'}`)):h('p',{style:{fontSize:12,color:'var(--dsw-alias-label-secondary)'}},'暂无自动处理记录。'),
|
||||
h('button',{'data-testid':'dx-decisions-refresh',type:'button',onClick:()=>perform({operation:'decisions'}),style:{...buttonStyle,marginTop:8}},'刷新决策记录')),
|
||||
data?.lifecycle?.request_id&&h('section',{'data-testid':'dx-task-lifecycle',style:{marginBottom:24}},
|
||||
h('h3',{style:{fontSize:14,fontWeight:500}},data.lifecycle.title||'对话任务操作'),
|
||||
h('p',{'data-testid':'dx-lifecycle-status'},({checking:'正在核对真实任务',awaiting_confirmation:'请核对原生确认窗口',
|
||||
|
||||
@@ -33,6 +33,7 @@ export function compactResult(value){
|
||||
if(result.tickets)result.tickets=result.tickets.slice(0,5).map(ticket);
|
||||
if(result.ticket)result.ticket=ticket(result.ticket);
|
||||
if(result.health)result.health=health(result.health);
|
||||
if(result.decision_audit)result.decision_audit=fields(result.decision_audit,['status','code','checked','message']);
|
||||
if(result.decisions)result.decisions=result.decisions.slice(0,10).map(decision);
|
||||
return JSON.parse(JSON.stringify(result));
|
||||
}
|
||||
@@ -40,7 +41,8 @@ export function modelSnapshot(value){
|
||||
const result=fields(value,['task_id','revision','task_name','status','progress','rules_count','issue','issue_code','events','action_result']);
|
||||
const ops=value.operations||{};
|
||||
result.operations=compactResult({busy:ops.busy===true,live_run:ops.live_run,last_execution:ops.last_execution,
|
||||
runs:ops.runs||[],schedules:ops.schedules||[],experiences:ops.experiences||[],tickets:ops.tickets||[],health:ops.health,decisions:ops.decisions||[]});
|
||||
runs:ops.runs||[],schedules:ops.schedules||[],experiences:ops.experiences||[],tickets:ops.tickets||[],health:ops.health,
|
||||
decision_audit:ops.decision_audit,decisions:ops.decisions||[]});
|
||||
if(value.automation?.incident_id)result.automation=fields(value.automation,['incident_id','task_id','issue_code','status','attempts','verification']);
|
||||
if(value.lifecycle?.status)result.lifecycle=fields(value.lifecycle,['request_id','status','task_ids','run_id']);
|
||||
return result;
|
||||
|
||||
@@ -75,6 +75,7 @@ class DshOperationsController(QObject):
|
||||
self.request_id = None
|
||||
self.results = {}
|
||||
self.cache = {'runs': [], 'schedules': [], 'experiences': [], 'tickets': [], 'decisions': [],
|
||||
'decision_audit': {'status': 'unknown'},
|
||||
'health': {'status': 'degraded', 'checks': []}, 'activity': {}}
|
||||
self.timer = QTimer(self)
|
||||
self.timer.setInterval(15000)
|
||||
@@ -149,6 +150,22 @@ class DshOperationsController(QObject):
|
||||
self.window._update_gates()
|
||||
QThreadPool.globalInstance().start(worker)
|
||||
|
||||
def _read_decisions(self):
|
||||
# A corrupt audit chain must fail closed for append/verification without
|
||||
# making independent history, tickets, health or scheduling unreadable.
|
||||
try:
|
||||
rows = self.decisions.list(20)
|
||||
except ValueError as error:
|
||||
return [], {'status': 'corrupt', 'code': 'audit_log_corrupt',
|
||||
'checked': getattr(error, 'checked', 0),
|
||||
'message': '审计日志损坏,原文件已保留;请导出证据并人工核对。'}
|
||||
except OSError:
|
||||
return [], {'status': 'unavailable', 'code': 'audit_log_unavailable',
|
||||
'message': '审计日志暂不可读,请检查访问权限并保留原文件。'}
|
||||
return rows, {'status': 'ok', 'code': 'audit_log_verified',
|
||||
'checked': rows[-1]['sequence'] if rows else 0,
|
||||
'message': '审计日志完整性校验通过。'}
|
||||
|
||||
def _read(self, *, synchronize_tickets=False):
|
||||
service = self.window.service
|
||||
runs = []
|
||||
@@ -165,9 +182,15 @@ class DshOperationsController(QObject):
|
||||
if candidates:
|
||||
self.tickets.refresh(candidates[0]['incident_id'])
|
||||
tickets = self.tickets.list_tickets()
|
||||
decisions, audit = self._read_decisions()
|
||||
health = self.health.snapshot(service)
|
||||
health['checks'].append({'name': 'decision_audit', 'status': 'ok' if audit['status'] == 'ok' else 'degraded',
|
||||
'code': audit['code'], 'message': audit['message']})
|
||||
if audit['status'] != 'ok' and health['status'] == 'ok':
|
||||
health['status'] = 'degraded'
|
||||
return {'runs': runs, 'schedules': self.schedules.evaluate(service),
|
||||
'experiences': self.experiences.refresh()[:20], 'tickets': tickets[:20],
|
||||
'health': self.health.snapshot(service), 'decisions': self.decisions.list(20)}
|
||||
'health': health, 'decisions': decisions, 'decision_audit': audit}
|
||||
|
||||
def refresh(self, *, synchronize_tickets=False):
|
||||
if self.window._closed or self.window._workers or self.busy or self._other_dialog():
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import Qt
|
||||
|
||||
|
||||
@@ -80,6 +83,88 @@ def test_operations_context_publishes_health_and_decision_timeline(ui, monkeypat
|
||||
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)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
@@ -213,11 +213,22 @@ def main():
|
||||
parser.add_argument('--phase', choices=('initial', 'resume'))
|
||||
parser.add_argument('--data', type=Path)
|
||||
parser.add_argument('--ticket-incident', type=Path, help='Existing incident directory to copy for read-only ticket synchronization')
|
||||
parser.add_argument('--audit-fault', choices=('duplicate', 'partial'),
|
||||
help='Inject a corrupt audit fixture; independent operations must remain available')
|
||||
args = parser.parse_args()
|
||||
if args.phase: return phase(args)
|
||||
output = args.output.resolve() / time.strftime('%Y%m%d-%H%M%S')
|
||||
output.mkdir(parents=True)
|
||||
data = output / 'data'; (data / 'dsh').mkdir(parents=True)
|
||||
if args.audit_fault:
|
||||
from dx_productivity.dsh.decision_log import DecisionLog
|
||||
audit = DecisionLog(data)
|
||||
row = audit.append({'incident_id': 'c' * 24, 'trigger': 'audit_fault_fixture',
|
||||
'candidate_action': 'none', 'outcome': 'pending_issue'})
|
||||
with audit.path.open('a', encoding='utf8') as stream:
|
||||
stream.write(json.dumps(row) + '\n' if args.audit_fault == 'duplicate' else '{"sequence":')
|
||||
write(output / 'audit-fault.json', {'kind': args.audit_fault,
|
||||
'sha256': hashlib.sha256(audit.path.read_bytes()).hexdigest()})
|
||||
if not args.provider_config: parser.error('--provider-config is required for the real provider acceptance')
|
||||
for name in ('provider.json', 'provider-key.dpapi'):
|
||||
shutil.copy2(args.provider_config / name, data / 'dsh' / name)
|
||||
@@ -244,8 +255,12 @@ def main():
|
||||
assert len(calls) == 3 and len({(row['queue'], row['job']) for row in calls}) == 3, calls
|
||||
audit = data / 'dsh/harness-home/task-tool-audit.jsonl'
|
||||
phases = [json.loads((output / f'{name}-desktop.json').read_text(encoding='utf8')) for name in ('initial', 'resume')]
|
||||
if args.audit_fault:
|
||||
original = json.loads((output / 'audit-fault.json').read_text(encoding='utf8'))
|
||||
assert hashlib.sha256((data / 'dsh/decisions.jsonl').read_bytes()).hexdigest() == original['sha256']
|
||||
write(output / 'report.json', {'status': 'passed', 'processes': 2, 'calls': calls,
|
||||
'realCadStarted': False, 'remoteIssuesCreated': False, 'sourceFixtureHashesUnchanged': True,
|
||||
'auditFault': args.audit_fault, 'auditFaultPreserved': True if args.audit_fault else None,
|
||||
'cleanShutdowns': [value['cleanShutdown'] for value in phases],
|
||||
'modelToolCalls': [json.loads(line) for line in audit.read_text(encoding='utf8').splitlines()] if audit.is_file() else [],
|
||||
'data': str(data)})
|
||||
|
||||
@@ -18,4 +18,10 @@ assert.equal(snapshot.task_id,'owner');
|
||||
assert.equal(JSON.stringify(snapshot),JSON.stringify(JSON.parse(JSON.stringify(snapshot))));
|
||||
assert.ok(Object.values(modelSnapshot({task_id:'empty',revision:'r'}).operations).every(v=>v!==undefined));
|
||||
assert.ok(JSON.stringify(snapshot).length<12000);
|
||||
const auditSnapshot=modelSnapshot({task_id:'owner',revision:'r',operations:{decisions:[],
|
||||
decision_audit:{status:'corrupt',code:'audit_log_corrupt',checked:2001,message:'审计日志损坏,原文件已保留。',raw_error:'private diagnostic'}}});
|
||||
assert.equal(auditSnapshot.operations.decision_audit.status,'corrupt');
|
||||
assert.equal(auditSnapshot.operations.decision_audit.code,'audit_log_corrupt');
|
||||
assert.equal(auditSnapshot.operations.decision_audit.checked,2001);
|
||||
assert.equal(auditSnapshot.operations.decision_audit.raw_error,undefined);
|
||||
console.log(JSON.stringify({status:'passed',committedIdsPreserved:true,impactRowsBounded:true,snapshotBounded:true}));
|
||||
@@ -58,6 +58,16 @@ async function input(id,text){
|
||||
}
|
||||
try{
|
||||
await wait(()=>c.evaluate(`!!document.querySelector('[contenteditable="true"]')&&!!${element('dx-operations-tab-running')}`),'composer and operations dock',180000);
|
||||
const auditFault=await readFile(path.join(output,'audit-fault.json'),'utf8').then(JSON.parse).catch(()=>null);
|
||||
if(auditFault){
|
||||
await tab('overview');
|
||||
await click('dx-health-refresh');
|
||||
await wait(async()=>{const d=await context();return d.operations?.decision_audit?.status==='corrupt'&&d.operations?.health?.checks?.length>0&&!d.operations?.busy;},'independent health survives audit corruption');
|
||||
await click('dx-decisions-refresh');
|
||||
await wait(()=>c.evaluate(`!!${element('dx-decision-audit-error')}&&${element('dx-decision-audit-error')}.textContent.includes('原文件已保留')`),'explicit audit error banner');
|
||||
await c.screenshot(path.join(output,phase+'-audit-isolation.png'));
|
||||
report.checks.push('corrupt audit remains explicit while native health and independent operations refresh successfully');
|
||||
}
|
||||
if(phase==='initial'){
|
||||
await send('只读检查当前 Board-A 任务的执行影响、已有执行历史和本地异常经验。说明匹配器件数量是否已知,暂时不要执行或修改任务。');
|
||||
await wait(async()=>(await context()).operations?.impact?.task_ids?.includes(manifest.tasks['Board-A'])||(await context()).operations?.impact?.coverage==='mapping_only','real-model impact response');await idle();
|
||||
|
||||
Reference in new issue
Block a user