feat(dsh): intervene on blocking states and verify resource recovery
Core regression / Python core and release configuration (push) Successful in 18s
Core regression / JavaScript syntax (push) Successful in 2s
Core regression / Python core and release configuration (pull_request) Successful in 16s
Core regression / JavaScript syntax (pull_request) Successful in 3s

This commit is contained in:
阿白叔 committed 2026-11-04 23:39:33 +08:00
1 parent 389fc917b9
commit de9cb2908d
21 files changed
+1557 -46

No files matched your search

+249
View File
@@ -0,0 +1,249 @@
"""Real desktop/model acceptance for BOM validation and resource intervention."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
import sys
import time
from types import SimpleNamespace
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / 'src'))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--provider-config', type=Path, required=True)
parser.add_argument('--output', type=Path, default=REPO / 'build/dsh-blocker-desktop-acceptance')
parser.add_argument('--port', type=int, default=9238)
args = parser.parse_args()
output = args.output.resolve() / time.strftime('%Y%m%d-%H%M%S')
output.mkdir(parents=True)
data = output / 'data'
from accept_dsh_desktop import copy_provider_configuration
copy_provider_configuration(args.provider_config, data / 'dsh')
(data / 'dsh/issue-config.json').write_text(json.dumps({'enabled': False, 'acceptance': True}), encoding='utf8')
project = output / 'fixtures/Board-A/board.prj'
project.parent.mkdir(parents=True)
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='utf8')
project_hash = hashlib.sha256(project.read_bytes()).hexdigest()
workbook_path = output / 'fixtures/invalid-bom.xlsx'
from openpyxl import Workbook
workbook = Workbook()
workbook.active.append(['invalid_required_headers'])
workbook.active.append(['controlled invalid BOM row'])
workbook.save(workbook_path)
workbook.close()
os.environ.pop('QT_QPA_PLATFORM', None)
os.environ['QTWEBENGINE_REMOTE_DEBUGGING'] = f'127.0.0.1:{args.port}'
from PySide6.QtCore import QTimer, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QFileDialog, QDialogButtonBox, QLineEdit
QApplication.setAttribute(Qt.ApplicationAttribute.AA_DontUseNativeDialogs)
from dx_productivity.dsh import health
# This isolated acceptance never reads machine issue-reporting credentials.
health.load_bootstrap = lambda: None
from dx_productivity.trial_task_center import application
from dx_productivity.trial_task_center.bom_import_report import inspect_batch
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
report = {'status': 'running', 'driver': 'real QApplication/QTest and native live model',
'output': str(output), 'checks': [], 'incidents': []}
state = {'phase': 'select', 'deadline': time.monotonic() + 540,
'resources_pending': False, 'cleanup_calls': 0, 'empty_reads_after_cleanup': 0,
'cad_reads': 0, 'parser_calls': 0, 'completed': {}}
resource = {'state': 'blocked', 'outcome': 'completed_resources_pending',
'resource_id': 'owned-acceptance-fixture', 'backend': 'controlled-memory-fixture',
'message': 'Owned acceptance resource requires resource-only cleanup; no CAD handle or OS process exists.'}
def save_report():
(output / 'desktop-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf8')
def build_window(service):
def resources():
if state['resources_pending']:
return (dict(resource),)
if state['cleanup_calls']:
state['empty_reads_after_cleanup'] += 1
return ()
def cleanup():
state['cleanup_calls'] += 1
state['resources_pending'] = False
# Deliberately stale return: resolution must come from an independent read.
return (dict(resource),)
def no_cad(*args, **kwargs):
state['cad_reads'] += 1
raise AssertionError('Unexpected CAD access in desktop acceptance')
def inspect(task_id, path, **options):
state['parser_calls'] += 1
return inspect_batch(service, task_id, path,
runtime=SimpleNamespace(bind_logs=lambda *args: None), **options)
service.pending_batch_resources = resources
service.cleanup_batch_resources = cleanup
service.inspect_bom_batch = inspect
service.collect_target_inventory = no_cad
service.collect_target_inventory_for_bom = no_cad
tasks = service.create_project_tasks(project.parent.parent)
window = TrialTaskCenterWindow(service, close_plan_confirmer=lambda: 'discard')
window.resize(1380, 900)
window.archive_on_close_check.setChecked(False)
def capture(name):
window.grab().save(str(output / name))
def finish(error=None):
if state['phase'] == 'closing':
return
state['phase'] = 'closing'
report.update(status='failed' if error else 'passed',
cleanupCalls=state['cleanup_calls'], emptyReadsAfterCleanup=state['empty_reads_after_cleanup'],
parserCalls=state['parser_calls'], cadReads=state['cad_reads'],
projectUnchanged=hashlib.sha256(project.read_bytes()).hexdigest() == project_hash)
if error:
report['error'] = type(error).__name__ + ': ' + str(error)
capture('failure.png')
automation = window._dsh_automation
if automation:
automation._runtime_stopped()
if window._dsh_view:
window._dsh_view.shutdown()
save_report()
window.close()
def pick_bom():
try:
modal = QApplication.activeModalWidget()
if not isinstance(modal, QFileDialog):
raise AssertionError('Actual Qt BOM file dialog did not open')
edit = modal.findChild(QLineEdit, 'fileNameEdit')
assert edit is not None
edit.setFocus()
QTest.keyClicks(edit, str(workbook_path))
buttons = modal.findChild(QDialogButtonBox)
assert buttons is not None
QTest.mouseClick(buttons.button(QDialogButtonBox.StandardButton.Open), Qt.MouseButton.LeftButton)
report['checks'].append('clicked Import BOM and selected the owned invalid XLSX in the actual Qt file dialog')
state['phase'] = 'bom'
save_report()
except Exception as error:
finish(error)
def completed_incident(code):
if code in state['completed']:
return state['completed'][code]
automation = window._dsh_automation
if not automation or automation.worker is not None:
return None
row = automation.latest
if row.get('issue_code') != code or row.get('status') not in {'resolved', 'pending_issue', 'escalated'}:
return None
evidence = Path(row['evidence_dir'])
persisted = json.loads((evidence / 'incident.json').read_text(encoding='utf8'))
assert any(evidence.glob('*.zip')), 'Incident evidence archive missing'
analyses = persisted.get('analyses', [])
assert analyses and all('reply' in entry for entry in analyses), 'Live model analysis failed'
assert all(entry.get('session_id') for entry in analyses), 'Native model session missing'
record = {'issue_code': code, 'incident_id': row['incident_id'], 'status': row['status'],
'sessions': [entry['session_id'] for entry in analyses],
'phases': [entry['phase'] for entry in analyses], 'evidence_dir': str(evidence),
'attempts': row.get('attempts'), 'action': persisted.get('action', 'none'),
'verification': persisted.get('verification', {})}
report['incidents'].append(record)
state['completed'][code] = record
return record
def stage_rendered(label):
if state.get('rendered_stage') == label:
return True
if state.get('checking_stage'):
return False
state['checking_stage'] = True
def observed(text):
state['checking_stage'] = False
if text == label:
state['rendered_stage'] = label
window._dsh_view.web.page().runJavaScript(
"document.querySelector('[data-testid=dx-auto-status]')?.textContent", observed)
return False
def tick():
try:
if state['phase'] == 'closing':
window.close()
return
if time.monotonic() > state['deadline']:
raise TimeoutError('Desktop blocker acceptance exceeded nine minutes')
if state['phase'] == 'select' and window.task_list.list.count() and not window._task_query.busy:
item = window.task_list.list.item(0)
QTest.mouseClick(window.task_list.list.viewport(), Qt.MouseButton.LeftButton,
pos=window.task_list.list.visualItemRect(item).center())
state['phase'] = 'import'
elif state['phase'] == 'import' and window._context and not window._loading and not window._workers:
assert window._context.task.task_id == tasks[0].task_id
assert window._dsh_view is None, 'Assistant was opened before the blocker'
tabs = window.mapping_tabs.tabBar()
QTest.mouseClick(tabs, Qt.MouseButton.LeftButton, pos=tabs.tabRect(1).center())
assert window.plan_panel.import_bom_button.isVisible()
assert window.plan_panel.import_bom_button.isEnabled()
capture('task-before-bom.png')
state['phase'] = 'picker'
QTimer.singleShot(350, pick_bom)
QTest.mouseClick(window.plan_panel.import_bom_button, Qt.MouseButton.LeftButton)
elif state['phase'] == 'bom':
row = completed_incident('bom_validation_failed')
if row and stage_rendered('证据已保存,工单待完整提交'):
assert row['phases'] == ['diagnose', 'reflect'], row
assert row['status'] == 'pending_issue' and row['attempts'] == 0
assert state['parser_calls'] == 1 and state['cad_reads'] == 0
capture('bom-native-diagnosis.png')
report['checks'].append('BOM parser failure automatically opened a native session with real model diagnosis, reflection and local evidence; remote issue submission disabled')
state['resources_pending'] = True
state['phase'] = 'resource'
# Trigger the actual poll path; no error callback is injected.
window._resource_status._poll()
save_report()
elif state['phase'] == 'resource':
row = completed_incident('batch_resources_pending')
if row and stage_rendered('处理结果已通过核验'):
assert row['status'] == 'resolved', row
assert row['action'] == 'cleanup_resources', row
assert row['verification'].get('resources_released') is True
assert state['cleanup_calls'] == 1 and state['empty_reads_after_cleanup'] >= 1
assert set(row['sessions']).isdisjoint(report['incidents'][0]['sessions'])
assert not list(data.rglob('command.tsv'))
capture('resource-cleanup-resolved.png')
report['checks'].append('real model requested resource-only cleanup; independently reread empty resources and resolved in a distinct native session')
finish()
except Exception as error:
finish(error)
timer = QTimer(window)
timer.setInterval(200)
timer.timeout.connect(tick)
timer.start()
return window
application._load_window = lambda: build_window
code = application.main(['--data-root', str(data)])
log_path = data / 'logs/application.log'
log = log_path.read_text(encoding='utf8') if log_path.is_file() else ''
report['cleanShutdown'] = 'application_clean_shutdown exit_code=0' in log
report['uncaughtErrors'] = 'uncaught_main_thread' in log
if code or report['status'] != 'passed' or not report['cleanShutdown'] or report['uncaughtErrors']:
report['status'] = 'failed'
save_report()
print(json.dumps(report, ensure_ascii=True))
return 0 if report['status'] == 'passed' else 1
if __name__ == '__main__':
raise SystemExit(main())
+194
View File
@@ -0,0 +1,194 @@
"""Run real native-Harness blocker diagnosis with memory-only resource fixtures."""
from __future__ import annotations
import json
import os
from pathlib import Path
from queue import Queue
import subprocess
import sys
from threading import Event, Thread
from time import monotonic
from uuid import uuid4
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / 'src'))
class NativeDiagnosis:
"""Use the production stdin/stdout protocol without exposing provider values."""
def __init__(self, root):
from dx_productivity.dsh.native_runtime import launch_environment, node_executable
from dx_productivity.dsh.provider_config import load_provider
from dx_productivity.trial_task_center.application import resolve_data_root
directory = root / 'dsh'
directory.mkdir(parents=True, exist_ok=True)
(directory / 'task-context.json').write_text(json.dumps({
'task_id': 'unrelated-live-task', 'revision': 'unrelated-live-revision'}), encoding='utf8')
provider = load_provider(resolve_data_root(None) / 'dsh')
environment = launch_environment(directory) | provider
assert all(environment.get(key) for key in ('DSH_API_BASE', 'DSH_MODEL', 'DSH_API_KEY')), 'provider_not_configured'
self.process = subprocess.Popen([node_executable(), str(REPO / 'integration/dsh/start.mjs')],
cwd=REPO, env=environment, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True, encoding='utf8',
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
self.events, self.calls = Queue(), []
Thread(target=self._read, daemon=True).start()
def _read(self):
for line in self.process.stdout:
if line.startswith('DX_DSH_READY '):
self.events.put({'status': 'ready'})
elif line.startswith('DX_DSH_DIAGNOSIS '):
self.events.put(json.loads(line[len('DX_DSH_DIAGNOSIS '):]))
self.events.put({'status': 'runtime_exited'})
def __enter__(self):
try:
assert self.events.get(timeout=65)['status'] == 'ready', 'native_runtime_not_ready'
except BaseException:
self.close()
raise
return self
def __call__(self, incident_id, snapshot, evidence, phase):
request_id = uuid4().hex
request = {'type': 'diagnose', 'request_id': request_id, 'incident_id': incident_id,
'snapshot': snapshot, 'evidence': evidence, 'phase': phase}
self.process.stdin.write(json.dumps(request, ensure_ascii=False) + '\n')
self.process.stdin.flush()
deadline = monotonic() + 240
while True:
remaining = deadline - monotonic()
if remaining <= 0:
raise TimeoutError('native_diagnosis_deadline')
value = self.events.get(timeout=remaining)
assert value.get('status') != 'runtime_exited', 'native_runtime_exited'
if value.get('request_id') != request_id or value.get('status') == 'started':
continue
assert value.get('status') == 'completed', 'native_diagnosis_did_not_complete'
self.calls.append({'incident_id': incident_id, 'phase': phase,
'session_id': value.get('session_id', '')})
return value
def close(self):
if self.process.stdin:
self.process.stdin.close()
try:
self.process.wait(timeout=8)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait(timeout=8)
self.process.stdout.close()
def __exit__(self, *args):
self.close()
class OwnedResourceFixture:
"""No CAD, OS process handles, or engineering files exist in this fixture."""
def __init__(self):
self.pending = [{'session_id': 'controlled-owned-session', 'state': 'blocked',
'resource_type': 'in-memory-owned-resource-fixture'}]
self.calls, self.context_calls, self.pending_reads = [], 0, 0
def task_context(self, task_id):
self.context_calls += 1
raise AssertionError('cached_snapshot_must_not_read_live_task_context')
def pending_batch_resources(self):
self.pending_reads += 1
return tuple(dict(item) for item in self.pending)
def cleanup_batch_resources(self):
self.calls.append('cleanup')
self.pending.clear()
return ()
def prepare_failed_quick_run(self, *args, **kwargs):
self.calls.append('forbidden_prepare')
raise AssertionError('engineering_mutation_forbidden')
def execute_quick_run_queue(self, *args, **kwargs):
self.calls.append('forbidden_execute')
raise AssertionError('engineering_mutation_forbidden')
def main():
from dx_productivity.dsh.incidents import IncidentRunner, decision
root = REPO / 'build' / ('dsh-blocker-recovery-' + uuid4().hex[:8])
root.mkdir(parents=True)
report_path = root / 'report.json'
service, publication_attempts = OwnedResourceFixture(), []
report = {'status': 'running', 'model': 'real configured API through native Harness',
'executor': 'in-memory fixture; no CAD or OS process writes', 'remoteIssueWrites': 0}
def local_outbox(record, archive):
assert archive.is_file(), 'missing_local_evidence_archive'
publication_attempts.append(record['incident_id'])
return {'status': 'unavailable', 'reason': 'remote_publication_disabled_for_acceptance'}
try:
with NativeDiagnosis(root) as native:
permission = Event()
permission.set()
runner = IncidentRunner(root, service, native, local_outbox)
cleanup = runner.run('controlled-resource-task', 'batch_resources_pending',
'受控资源释放验收:任务队列已空闲,仅有一个本验收持有的内存资源待释放。'
'资源所有权已在受控服务中确认;cleanup_allowed=true。'
'资源释放不会打开工程、恢复队列或执行 CAD;不需要原始 CAD 执行授权。',
run_id='controlled-resource-run', execution_enabled=permission, cleanup_allowed=True,
snapshot_override={'task_id': 'controlled-resource-task', 'task_name': '受控自有资源释放',
'status': 'blocked', 'progress': {}},
trigger={'operation': 'release_resources', 'source': 'controlled-owned-resource-fixture',
'outcome': 'resources_pending', 'task_queue_idle': True,
'ownership_verified': True, 'pending_resources': service.pending_batch_resources()})
report['cleanupIncident'] = cleanup
assert decision(cleanup['analyses'][0]['reply'])['action'] == 'cleanup_resources', 'model_did_not_recommend_cleanup'
assert cleanup['status'] == 'resolved', 'cleanup_not_resolved'
assert cleanup['verification']['resources_released'] is True, 'resources_not_verified_released'
assert cleanup['verification']['remaining_resources'] == [], 'resources_still_pending'
assert service.calls == ['cleanup'], 'unexpected_cleanup_or_engineering_call'
assert service.pending_reads >= 3, 'missing_independent_resource_reread'
assert service.context_calls == 0, 'cleanup_read_live_task_context'
assert not publication_attempts, 'resolved_cleanup_attempted_publication'
stall = runner.run('controlled-stall-task', 'operation_stalled',
'受控停滞验收:BOM 检查轮询连续未产生新进度。当前只有缓存事件,'
'活动操作可能持有服务锁,执行结果尚不确定。应诊断并保留证据供人工核对。',
run_id='controlled-stall-run', execution_enabled=permission,
snapshot_override={'task_id': 'controlled-stall-task', 'task_name': '受控 BOM 轮询停滞',
'status': 'running', 'progress': {'completed': 0, 'total': 1}},
trigger={'operation': 'inspect_bom_batch', 'source': 'controlled-stall-event',
'outcome': 'stalled', 'last_progress_age_seconds': 180,
'result_unverified': True, 'worker_active': True})
report['stallIncident'] = stall
assert stall['status'] == 'pending_issue', 'stall_did_not_remain_in_local_outbox'
assert stall['attempts'] == 0, 'stall_retried_engineering'
assert service.calls == ['cleanup'], 'stall_mutated_resources_or_engineering'
assert service.context_calls == 0, 'stall_read_live_task_context'
assert publication_attempts == [stall['incident_id']], 'unexpected_publication_attempts'
assert [row['phase'] for row in stall['analyses']] == ['diagnose', 'reflect'], 'missing_real_stall_diagnosis_or_reflection'
sessions = [row.get('session_id') for row in stall['analyses']]
assert sessions[0] and sessions[0] == sessions[1], 'reflection_did_not_reuse_native_session'
directory = Path(stall['evidence_dir'])
assert all((directory / name).is_file() for name in ('trigger.json', 'issue.md', 'evidence.zip', 'ticket.json')), 'missing_local_stall_evidence'
report.update(status='passed', actualCalls=service.calls, contextCalls=service.context_calls,
resourceReads=service.pending_reads, modelCalls=native.calls,
resources_released=True, localOutboxCount=len(publication_attempts))
except BaseException as error:
report.update(status='failed', errorType=type(error).__name__, actualCalls=service.calls,
contextCalls=service.context_calls, localOutboxCount=len(publication_attempts))
raise
finally:
report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf8')
print(json.dumps({'status': report['status'], 'report': str(report_path),
'actualCalls': service.calls, 'contextCalls': service.context_calls,
'modelCallCount': len(report.get('modelCalls', [])),
'localOutboxCount': len(publication_attempts)}, ensure_ascii=False))
if __name__ == '__main__':
main()