feat: complete native BOM and Harness execution acceptance
This commit is contained in:
1 parent
4f8fbd7806
commit
65438cb7e5
234 files changed
+24402
-865
No files matched your search
@@ -3,23 +3,24 @@ import json
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
DEFAULTS = {'response_timeout_seconds': 90, 'model_context_limit': 16000}
|
||||
DEFAULTS = {'response_timeout_seconds': 0, 'model_context_limit': 0}
|
||||
|
||||
|
||||
def validate(raw):
|
||||
if not isinstance(raw, dict) or set(raw) - set(DEFAULTS):
|
||||
raise ValueError('unsupported assistant setting')
|
||||
value = dict(DEFAULTS); value.update(raw)
|
||||
if type(value['response_timeout_seconds']) is not int or not 15 <= value['response_timeout_seconds'] <= 600:
|
||||
raise ValueError('response timeout must be 15..600 seconds')
|
||||
if type(value['model_context_limit']) is not int or not 2000 <= value['model_context_limit'] <= 128000:
|
||||
raise ValueError('model context limit must be 2000..128000 tokens')
|
||||
if type(value['response_timeout_seconds']) is not int or (value['response_timeout_seconds'] != 0 and not 15 <= value['response_timeout_seconds'] <= 600):
|
||||
raise ValueError('response timeout must be 0 (native) or 15..600 seconds')
|
||||
if type(value['model_context_limit']) is not int or (value['model_context_limit'] != 0 and not 2000 <= value['model_context_limit'] <= 128000):
|
||||
raise ValueError('model context limit must be 0 (native) or 2000..128000 tokens')
|
||||
return value
|
||||
|
||||
|
||||
def load_settings(data_root):
|
||||
try:
|
||||
return validate(json.loads((Path(data_root) / 'dsh/assistant-settings.json').read_text(encoding='utf8')))
|
||||
value = validate(json.loads((Path(data_root) / 'dsh/assistant-settings.json').read_text(encoding='utf8')))
|
||||
return dict(DEFAULTS) if value == {'response_timeout_seconds': 90, 'model_context_limit': 16000} else value
|
||||
except (OSError, ValueError, TypeError):
|
||||
return dict(DEFAULTS)
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ class CadVerificationAdapter:
|
||||
'projects': projects, 'blockers': list(dict.fromkeys(blockers)),
|
||||
'evidence_refs': refs[:20]}
|
||||
|
||||
def after_run(self, task_ids):
|
||||
def after_run(self, task_ids, *, netlist_verification=None):
|
||||
tasks, blockers = [], []
|
||||
for task_id in task_ids:
|
||||
try:
|
||||
@@ -55,6 +55,11 @@ class CadVerificationAdapter:
|
||||
blockers.append('failed_items')
|
||||
if row['queue_complete'] is not True:
|
||||
blockers.append('queue_incomplete')
|
||||
report = (netlist_verification or {}).get(task_id, {})
|
||||
row['netlist_verified'] = report.get('status') == 'verified' and report.get('verified') is True
|
||||
row['netlist_status'] = report.get('status', 'unavailable' if row['saved_items'] else 'not_required')
|
||||
if row['saved_items'] and not row['netlist_verified']:
|
||||
blockers.append('netlist_not_verified')
|
||||
except Exception as error:
|
||||
row = {'task_id': task_id, 'saved_items': None, 'failed_items': None,
|
||||
'no_match_items': None, 'queue_complete': None, 'interrupted': True,
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
"""Execute a natively confirmed frozen scope and persist its actual receipt."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from . import task_lifecycle as tasks
|
||||
from .run_journal import RunJournal
|
||||
from .scheduling import ScheduleStore
|
||||
@@ -10,7 +13,7 @@ from ..trial_task_center.task_queue import execute_task_queue
|
||||
|
||||
|
||||
def _failure_evidence(service, journal, run_id, baseline):
|
||||
evidence = {key: baseline[key] for key in ('tasks', 'entries') if key in baseline}
|
||||
evidence = {key: baseline[key] for key in ('tasks', 'entries', 'retry') if key in baseline}
|
||||
if not baseline:
|
||||
return evidence
|
||||
try:
|
||||
@@ -38,9 +41,16 @@ def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resu
|
||||
prior = RunJournal(root).get(run_id) if resume else None
|
||||
schedule_id = schedule['schedule_id'] if schedule else (prior or {}).get('schedule_id')
|
||||
if schedule_id:
|
||||
with ScheduleStore(root).execution_lease(schedule_id):
|
||||
return _execute_confirmed_run(service, root, task_ids, report, stop, run_id,
|
||||
resume=resume, schedule=schedule, automatic=automatic)
|
||||
schedules = ScheduleStore(root)
|
||||
with schedules.execution_lease(schedule_id):
|
||||
if resume:
|
||||
_bound_schedule(schedules, prior)
|
||||
receipt = _execute_confirmed_run(service, root, task_ids, report, stop, run_id,
|
||||
resume=resume, schedule=schedule, automatic=automatic)
|
||||
if resume:
|
||||
schedules.finish(schedule_id, 'interrupted' if receipt['status'] in {'paused', 'blocked'} else receipt['status'],
|
||||
repair_run_id=run_id, run_id=run_id, receipt=receipt)
|
||||
return receipt
|
||||
return _execute_confirmed_run(service, root, task_ids, report, stop, run_id, resume=resume)
|
||||
|
||||
|
||||
@@ -64,6 +74,7 @@ def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, res
|
||||
raise TaskCenterError('run_blocked', '原执行范围或证据已变化,请先核验。')
|
||||
baseline = inspected.get('result') or {}
|
||||
journal.resume(run_id)
|
||||
journal.repair_retry_checkpoint(service, run_id)
|
||||
else:
|
||||
journal.begin(run_id, task_ids, report['plan_hashes'], schedule_id=schedule['schedule_id'] if schedule else None)
|
||||
initialized = True
|
||||
@@ -80,17 +91,31 @@ def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, res
|
||||
if claimed:
|
||||
schedules.finish(schedule['schedule_id'], 'interrupted', run_id=run_id, receipt=failure)
|
||||
raise
|
||||
return _finish_execution_run(service, root, task_ids, stop, run_id, result,
|
||||
schedule=schedule if claimed else None)
|
||||
|
||||
|
||||
def _finish_execution_run(service, root, task_ids, stop, run_id, result, *, schedule=None):
|
||||
journal = RunJournal(root)
|
||||
schedules = ScheduleStore(root) if schedule is not None else None
|
||||
entries = [{'task_id': e.task_id, 'state': e.state, 'message': e.message} for e in result.entries]
|
||||
status = ('blocked' if any(e['state'] == 'blocked' for e in entries)
|
||||
else 'paused' if result.paused else 'failed' if any(e['state'] == 'failed' for e in entries) else 'completed')
|
||||
receipt = {'status': status, 'run_id': run_id, 'queue_id': result.queue_id, 'paused': result.paused,
|
||||
from ..trial_task_center.netlist_verification import verification_summary
|
||||
acceptance = verification_summary(result.netlist_verification)
|
||||
overall = 'failed' if status == 'completed' and acceptance['status'] in {'different', 'unavailable'} else status
|
||||
receipt = {'status': overall, 'execution_status': status, 'acceptance': acceptance,
|
||||
'run_id': run_id, 'queue_id': result.queue_id, 'paused': result.paused,
|
||||
'user_pause_requested': bool(stop.is_set()), 'awaiting_user_resume': bool(result.paused and stop.is_set()),
|
||||
'entries': entries, 'tasks': [], 'reporting_errors': [],
|
||||
'message': '请按每项实际计数判断;未命中不表示已替换保存。'}
|
||||
if result.netlist_verification:
|
||||
receipt['netlist_verification'] = result.netlist_verification
|
||||
# Persist the executor's known outcome before optional readback/enrichment.
|
||||
journal.finish(run_id, receipt)
|
||||
try:
|
||||
receipt['cad_verification'] = CadVerificationAdapter(service).after_run(task_ids)
|
||||
receipt['cad_verification'] = CadVerificationAdapter(service).after_run(task_ids,
|
||||
netlist_verification=result.netlist_verification)
|
||||
except Exception as error:
|
||||
receipt['cad_verification'] = {'status': 'uncertain', 'mode': 'task_center_native',
|
||||
'blockers': ['verification_unavailable'], 'error': type(error).__name__}
|
||||
@@ -104,13 +129,18 @@ def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, res
|
||||
except Exception as error:
|
||||
receipt['reporting_errors'].append({'task_id': entry['task_id'], 'code': getattr(error, 'code', 'context_unavailable')})
|
||||
receipt['tasks'].append(actual)
|
||||
receipt['acceptance'] = verification_summary(result.netlist_verification,
|
||||
required_task_ids=(row['task_id'] for row in receipt['tasks'] if row.get('saved_items')))
|
||||
if status == 'completed' and receipt['acceptance']['status'] in {'different', 'unavailable'}:
|
||||
receipt['status'] = 'failed'
|
||||
receipt['message'] = '替换执行已收尾,独立网表验收未通过;保留已保存回执,不重复替换。'
|
||||
try:
|
||||
journal.finish(run_id, receipt)
|
||||
except Exception as error:
|
||||
receipt['reporting_errors'].append({'code': 'receipt_enrichment_unavailable', 'error': type(error).__name__})
|
||||
if claimed:
|
||||
if schedule is not None:
|
||||
try:
|
||||
schedules.finish(schedule['schedule_id'], 'interrupted' if status in {'paused', 'blocked'} else status,
|
||||
schedules.finish(schedule['schedule_id'], 'interrupted' if receipt['status'] in {'paused', 'blocked'} else receipt['status'],
|
||||
run_id=run_id, receipt=receipt)
|
||||
except Exception as error:
|
||||
receipt['reporting_errors'].append({'code': getattr(error, 'code', 'schedule_receipt_unavailable')})
|
||||
@@ -119,3 +149,116 @@ def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, res
|
||||
except Exception:
|
||||
receipt['reporting_errors'].append({'code': 'receipt_enrichment_unavailable'})
|
||||
return receipt
|
||||
|
||||
|
||||
def _bound_schedule(schedules, run):
|
||||
row = schedules.get(run['schedule_id'])
|
||||
if (not row or row['run_id'] != run['run_id'] or row['task_ids'] != run['task_ids']
|
||||
or row['plan_hashes'] != run['plan_hashes'] or row['status'] not in {'claimed', 'failed', 'interrupted'}):
|
||||
raise TaskCenterError('schedule_run_conflict', '排期不再属于原授权运行,不能自动重试或覆写新尝试。')
|
||||
return row
|
||||
|
||||
|
||||
def execute_incident_retry(service, root, task_id, run_id, *, expected_item, stop_event, operation_keys=None):
|
||||
original = RunJournal(root).get(run_id)
|
||||
if original and original['schedule_id']:
|
||||
schedules = ScheduleStore(root)
|
||||
with schedules.execution_lease(original['schedule_id']):
|
||||
_bound_schedule(schedules, original)
|
||||
result = _execute_incident_retry(service, root, task_id, run_id,
|
||||
expected_item=expected_item, stop_event=stop_event, operation_keys=operation_keys)
|
||||
receipt = RunJournal(root).get(run_id)['result']
|
||||
schedules.finish(original['schedule_id'], 'interrupted' if receipt['status'] in {'paused', 'blocked'} else receipt['status'],
|
||||
repair_run_id=run_id, run_id=run_id, receipt=receipt)
|
||||
return result
|
||||
return _execute_incident_retry(service, root, task_id, run_id,
|
||||
expected_item=expected_item, stop_event=stop_event, operation_keys=operation_keys)
|
||||
|
||||
|
||||
def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, stop_event, operation_keys):
|
||||
"""Retry only the reserved task, refreshing its original acceptance/receipt."""
|
||||
from hashlib import sha256
|
||||
from ..trial_task_center.batch_resources import write_record
|
||||
from ..trial_task_center.netlist_verification import NetlistVerification, verification_summary
|
||||
from ..trial_task_center.task_queue import TaskQueueEntry, TaskQueueResult, _plan_hash, _save
|
||||
root = Path(root)
|
||||
journal = RunJournal(root)
|
||||
original = journal.get(run_id)
|
||||
child = service.for_project_task(task_id) if hasattr(service, 'for_project_task') else service
|
||||
if original and (task_id not in original['task_ids']
|
||||
or _plan_hash(child, task_id) != original['plan_hashes'][task_id]):
|
||||
raise TaskCenterError('assistant_stale', '原授权执行范围或计划已变化,不能自动重试。')
|
||||
if original:
|
||||
candidates = [root / folder / (run_id + '.json') for folder in ('task-queues', 'workspace-queues')]
|
||||
existing = [path for path in candidates if path.is_file()]
|
||||
if len(existing) != 1:
|
||||
raise TaskCenterError('run_scope', '原队列检查点缺失或有歧义;不接续其他任务。')
|
||||
path = existing[0]
|
||||
checkpoint = json.loads(path.read_text(encoding='utf-8'))
|
||||
if (checkpoint.get('task_ids') != original['task_ids'] or checkpoint.get('plan_hashes') != original['plan_hashes']
|
||||
or set(checkpoint['entries']) != set(original['task_ids'])):
|
||||
raise TaskCenterError('run_scope', '原队列检查点身份或范围已变化;不执行重试。')
|
||||
journal.begin_retry(service, run_id, task_id, operation_keys)
|
||||
checkpoint['entries'][task_id].update(state='running', message='仅执行已预约的原失败项重试。')
|
||||
_save(path, checkpoint)
|
||||
token = original['run_id'] if original else sha256(str(run_id).encode('utf-8')).hexdigest()[:32]
|
||||
with NetlistVerification(root, token, stop_event) as checks:
|
||||
# Never capture a partially replaced project as a new "before".
|
||||
checks.before_task(child, task_id, existing_only=True)
|
||||
outcome = service.execute_quick_run_queue(task_id, expected_item=expected_item, stop_event=stop_event)
|
||||
current = service.task_context(task_id)
|
||||
p = current.progress
|
||||
complete = p.queue_complete and not p.failed_items and not current.interrupted and not outcome.paused
|
||||
summary = {key: getattr(p, key, 0) for key in ('saved_items', 'failed_items', 'no_match_items')}
|
||||
if p.saved_items or 'rules' in checks.tasks.get(task_id, {}).get('plan', {}):
|
||||
checks.after_task(task_id, execution_state='completed' if complete else 'failed',
|
||||
execution_summary=summary, refresh=True)
|
||||
reports = checks.finish()
|
||||
if not p.saved_items:
|
||||
reports = {key: report for key, report in reports.items() if report['status'] == 'not_required'}
|
||||
if p.saved_items and task_id not in reports:
|
||||
directory = root / 'tasks' / task_id / 'netlist-checks' / token
|
||||
reports[task_id] = {'status': 'unavailable', 'verified': False,
|
||||
'reason': '原授权执行缺少完整替换前基准,不能事后补造或仅凭保存计数宣称验收通过。',
|
||||
'report_path': str(directory / 'verification.json')}
|
||||
write_record(directory / 'verification.json', reports[task_id])
|
||||
acceptance = verification_summary(reports, required_task_ids=(task_id,) if p.saved_items else ())
|
||||
verification = {'queue_complete': p.queue_complete, 'failed_items': p.failed_items,
|
||||
'saved_items': p.saved_items, 'completed_items': p.completed_items,
|
||||
'interrupted': current.interrupted, 'paused': outcome.paused,
|
||||
'acceptance': acceptance, 'netlist_verification': reports, 'run_receipt_updated': False}
|
||||
if original:
|
||||
# Preserve every other entry/report. This does not resume the parent
|
||||
# queue or dispatch any other engineering task.
|
||||
prior = original.get('result') or {}
|
||||
entries = {row['task_id']: dict(row) for row in prior.get('entries', ())}
|
||||
if set(entries) != set(original['task_ids']):
|
||||
raise TaskCenterError('run_scope', '原执行回执范围不完整,保留本次真实结果等待核验。')
|
||||
state = 'blocked' if current.interrupted else 'paused' if outcome.paused else 'completed' if complete else 'failed'
|
||||
message = 'DSH 已按原失败项范围重试;保存结果与独立验收分别记录。'
|
||||
entries[task_id].update(state=state, message=message)
|
||||
merged = dict(prior.get('netlist_verification') or {})
|
||||
merged.pop(task_id, None)
|
||||
merged.update(reports)
|
||||
candidates = [root / folder / (run_id + '.json') for folder in ('task-queues', 'workspace-queues')]
|
||||
existing = [path for path in candidates if path.is_file()]
|
||||
if len(existing) != 1:
|
||||
raise TaskCenterError('run_scope', '原队列检查点缺失或有歧义;不接续其他任务。')
|
||||
path = existing[0]
|
||||
checkpoint = json.loads(path.read_text(encoding='utf-8'))
|
||||
if (checkpoint.get('task_ids') != original['task_ids'] or checkpoint.get('plan_hashes') != original['plan_hashes']
|
||||
or set(checkpoint['entries']) != set(original['task_ids'])):
|
||||
raise TaskCenterError('run_scope', '原队列检查点身份或范围已变化;保留本次结果。')
|
||||
checkpoint['entries'][task_id].update(state=state, message=message)
|
||||
if path.parent.name == 'workspace-queues':
|
||||
checkpoint['entries'][task_id].update(released=not bool(service.pending_batch_resources()), problems_done=True)
|
||||
if reports:
|
||||
checkpoint['entries'][task_id]['netlist_verification'] = reports[task_id]
|
||||
elif reports:
|
||||
checkpoint.setdefault('netlist_verification', {}).update(reports)
|
||||
_save(path, checkpoint)
|
||||
result = TaskQueueResult(original['queue_id'], tuple(TaskQueueEntry(**entries[key])
|
||||
for key in original['task_ids']), outcome.paused, netlist_verification=merged)
|
||||
receipt = _finish_execution_run(service, root, original['task_ids'], stop_event, run_id, result)
|
||||
verification.update(run_receipt_updated=True, run_status=receipt['status'])
|
||||
return outcome, current, verification
|
||||
@@ -1,23 +1,8 @@
|
||||
"""Conservative classification for automatic incident intervention."""
|
||||
from __future__ import annotations
|
||||
|
||||
_TRANSIENT = {'worker_error', 'worker_timeout', 'timeout', 'quick_run_failed', 'execution_failed', 'native_failed'}
|
||||
_DETERMINISTIC = {'target_identity', 'probe_baseline_missing', 'task_not_retryable', 'assistant_stale'}
|
||||
"""Diagnostic adapters share the queue's evidence-based execution policy."""
|
||||
|
||||
|
||||
def classify_failure(issue_code, status, *, interrupted=False, authorized=False):
|
||||
code = str(issue_code or '').casefold()
|
||||
state = str(status or '').casefold()
|
||||
if interrupted or state in {'uncertain', 'saved_unverified'} or 'uncertain' in code or 'readback' in code:
|
||||
category, reason = 'uncertain', '存在未核验或回读不确定状态'
|
||||
elif state == 'paused' or code in {'paused', 'user_pause'}:
|
||||
category, reason = 'paused', '任务已暂停,需要人工确认后继续'
|
||||
elif code in _TRANSIENT or state in {'timeout', 'timed_out'}:
|
||||
category, reason = 'transient', '可重试的临时执行错误'
|
||||
elif code in _DETERMINISTIC:
|
||||
category, reason = 'deterministic', '错误需要先修正任务或工程状态'
|
||||
else:
|
||||
category, reason = 'observe', '错误类型未进入自动处理白名单'
|
||||
allowed = category == 'transient' and authorized
|
||||
return {'category': category, 'retry_allowed': allowed, 'reason': reason,
|
||||
'backoff_seconds': 5 if allowed else 0, 'max_attempts': 1 if allowed else 0}
|
||||
def classify_failure(issue_code, status, *, interrupted=False, authorized=False,
|
||||
certified=False, phase='unknown'):
|
||||
from ..trial_task_center.execution_problems import classify_execution_failure
|
||||
return classify_execution_failure(issue_code, status, interrupted=interrupted,
|
||||
authorized=authorized, certified=certified, phase=phase)
|
||||
@@ -13,7 +13,6 @@ from typing import Any
|
||||
from ..trial_task_center.errors import TaskCenterError
|
||||
|
||||
|
||||
_MAX_TASKS = 20
|
||||
_MAX_LIMIT = 100
|
||||
|
||||
|
||||
@@ -24,12 +23,12 @@ def _hash(value: Any) -> str:
|
||||
|
||||
|
||||
def _scope(task_ids: object) -> tuple[str, ...]:
|
||||
if not isinstance(task_ids, (list, tuple)) or not 1 <= len(task_ids) <= _MAX_TASKS:
|
||||
raise TaskCenterError("assistant_task_scope", "请选择 1 至 20 个不同的真实任务。")
|
||||
if not isinstance(task_ids, (list, tuple)) or not task_ids:
|
||||
raise TaskCenterError("assistant_task_scope", "请选择不同的真实任务。")
|
||||
if any(not isinstance(task_id, str) or not task_id or len(task_id) > 128 for task_id in task_ids):
|
||||
raise TaskCenterError("assistant_task_scope", "任务编号无效。")
|
||||
if len(set(task_ids)) != len(task_ids):
|
||||
raise TaskCenterError("assistant_task_scope", "请选择 1 至 20 个不同的真实任务。")
|
||||
raise TaskCenterError("assistant_task_scope", "请选择不同的真实任务。")
|
||||
return tuple(task_ids)
|
||||
|
||||
|
||||
@@ -59,8 +58,6 @@ def _policy(task, row) -> tuple[str, str | None]:
|
||||
def _target_row(task, task_id: str, row) -> dict[str, Any]:
|
||||
target = row.target
|
||||
value_policy, proposed = _policy(task, row)
|
||||
if value_policy == "preserve":
|
||||
proposed = target.old_value
|
||||
sync_nc = bool(getattr(row, "sync_nc", True))
|
||||
target_cell = getattr(row, "target_cell", "")
|
||||
return {
|
||||
@@ -118,6 +115,25 @@ def _mapping_row(task, context, task_id: str, rule) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _pending_row(task, context, task_id, request):
|
||||
record = request.record
|
||||
mode = record.value_mode
|
||||
if mode == 'inherit':
|
||||
mode = 'part_label' if task.copy_part_number_to_value else 'preserve'
|
||||
return {
|
||||
'task_id': task_id, 'project': str(context.project.path), 'coverage': 'pending_bom',
|
||||
'enabled': record.enabled, 'component_count': None, 'uid': record.uid or None,
|
||||
'schematic_name': record.schematic or None, 'sheet': record.sheet or None,
|
||||
'sheet_number': record.sheet or None, 'refdes': None, 'requested_refdes': list(record.refs),
|
||||
'old_part_number': record.old, 'new_part_number': record.new, 'old_value': None,
|
||||
'proposed_value': record.custom if mode == 'custom' else record.new if mode == 'part_number' else None,
|
||||
'value_policy': mode, 'value_mode': record.value_mode, 'target_cell': '', 'target_cell_policy': '',
|
||||
'sync_nc': record.sync_nc, 'nc_policy': 'sync' if record.sync_nc else 'preserve',
|
||||
'mapping_scope': None, 'verification_pending': True,
|
||||
'source_file': request.source_file, 'source_row': request.source_row,
|
||||
}
|
||||
|
||||
|
||||
def execution_impact(service, task_ids, *, limit: int = 100) -> dict[str, Any]:
|
||||
"""Return a bounded, deterministic report of the saved execution scope.
|
||||
|
||||
@@ -138,9 +154,19 @@ def execution_impact(service, task_ids, *, limit: int = 100) -> dict[str, Any]:
|
||||
for task_id in ids:
|
||||
context = service.task_context(task_id)
|
||||
task = context.task
|
||||
exact = bool(getattr(task, "target_plan_mode", False))
|
||||
pending = tuple(getattr(context, 'pending_bom', ()))
|
||||
exact = bool(getattr(task, "target_plan_mode", False)) and not pending
|
||||
task_rows: list[dict[str, Any]] = []
|
||||
if exact:
|
||||
if pending:
|
||||
from ..trial_task_center.bom_pending import retained_bom_rows
|
||||
retained = retained_bom_rows(pending, tuple(service.target_plan(task_id)))
|
||||
task_rows = [_pending_row(task, context, task_id, request) for request in pending]
|
||||
task_rows.extend(dict(_target_row(task, task_id, row), retained_from_saved_plan=True) for row in retained)
|
||||
task_coverage = 'pending_bom'
|
||||
task_enabled_scope = sum(len(request.refs) for request in pending if request.record.enabled) + len(retained)
|
||||
known_component_count += len(retained)
|
||||
enabled_scope += task_enabled_scope
|
||||
elif exact:
|
||||
# service.target_plan() is the authoritative saved-row API and
|
||||
# retains target_cell on versions whose context projection is old.
|
||||
saved_rows = tuple(service.target_plan(task_id))
|
||||
@@ -163,7 +189,9 @@ def execution_impact(service, task_ids, *, limit: int = 100) -> dict[str, Any]:
|
||||
"project": str(project.path) if project is not None else "",
|
||||
"coverage": task_coverage,
|
||||
"component_count": task_count if exact else None,
|
||||
"enabled_scope": sum(row["component_count"] for row in task_rows) if exact else sum(1 for row in task_rows if row["enabled"]),
|
||||
"enabled_scope": (task_enabled_scope if pending
|
||||
else sum(row["component_count"] for row in task_rows) if exact
|
||||
else sum(1 for row in task_rows if row["enabled"])),
|
||||
"total_rows": len(task_rows),
|
||||
"returned_rows": 0,
|
||||
"omitted_row_count": 0,
|
||||
|
||||
@@ -254,12 +254,20 @@ class IncidentRunner:
|
||||
return None
|
||||
if cancel_event.is_set():
|
||||
return cancelled()
|
||||
suggestion = analyze('diagnose')
|
||||
# The model explains; only the SQLite receipt and reservation authorize replay.
|
||||
try:
|
||||
overview = self.service.execution_problem_overview(task_id)
|
||||
certified = (context is not None and issue_code in RETRYABLE_CODES
|
||||
and any(item.get('auto_retries_remaining') == 1 for item in overview['items']))
|
||||
except (AttributeError, KeyError, TypeError, ValueError):
|
||||
certified = False
|
||||
suggestion = None if certified else analyze('diagnose')
|
||||
if cancel_event.is_set():
|
||||
return cancelled()
|
||||
policy = classify_failure(issue_code, getattr(context.task.status, 'value', '') if context is not None else 'unknown',
|
||||
interrupted=context is None or bool(getattr(context, 'interrupted', True)),
|
||||
authorized=bool(execution_authorized))
|
||||
authorized=bool(execution_authorized), certified=certified,
|
||||
phase=getattr(context, 'phase', 'unknown'))
|
||||
gates = {'context_available': context is not None, 'no_unverified_result': context is not None and not context.interrupted,
|
||||
'retry_phase': context is not None and context.phase == 'retry', 'known_retryable_error': issue_code in RETRYABLE_CODES,
|
||||
'execution_authorized': bool(execution_authorized), 'not_stopped': not stop_event.is_set(),
|
||||
@@ -270,7 +278,8 @@ class IncidentRunner:
|
||||
'failure_policy': policy}
|
||||
record['gates'] = gates
|
||||
write_json(evidence.directory / 'gates.json', gates)
|
||||
safe = all(value is True for key, value in gates.items() if key != 'failure_policy') and policy['retry_allowed']
|
||||
safe = all(value is True for key, value in gates.items()
|
||||
if key not in {'failure_policy', 'model_requested_retry', 'known_retryable_error'}) and policy['retry_allowed']
|
||||
cleanup_gates = {'cleanup_allowed': bool(cleanup_allowed), 'resource_issue': issue_code in _RESOURCE_CODES,
|
||||
'model_requested_cleanup': bool(suggestion and suggestion['action'] == 'cleanup_resources'),
|
||||
'not_stopped': not stop_event.is_set(),
|
||||
@@ -386,18 +395,19 @@ class IncidentRunner:
|
||||
if (prepared.interrupted or not p.next_project_path or stop_event.is_set() or cancel_event.is_set()
|
||||
or (execution_enabled is not None and not execution_enabled.is_set())):
|
||||
raise ValueError('retry_execution_gate_changed')
|
||||
outcome = self.service.execute_quick_run_queue(task_id, expected_item=expected, stop_event=stop_event)
|
||||
from .execution_runs import execute_incident_retry
|
||||
outcome, current, verification = execute_incident_retry(self.service, self.data_root,
|
||||
task_id, run_id, expected_item=expected, stop_event=stop_event,
|
||||
operation_keys=reserved if reserve_retry is not None else None)
|
||||
update('verifying')
|
||||
current = self.service.task_context(task_id)
|
||||
p = current.progress
|
||||
verification = {'queue_complete': p.queue_complete, 'failed_items': p.failed_items,
|
||||
'saved_items': p.saved_items, 'completed_items': p.completed_items,
|
||||
'interrupted': current.interrupted, 'paused': outcome.paused}
|
||||
write_json(evidence.directory / 'verification.json', verification)
|
||||
record['verification'] = verification
|
||||
if cancel_event.is_set():
|
||||
return cancelled()
|
||||
if p.queue_complete and not p.failed_items and not current.interrupted and not outcome.paused:
|
||||
if (p.queue_complete and not p.failed_items and not current.interrupted and not outcome.paused
|
||||
and verification['acceptance']['status'] in {'verified', 'not_required'}):
|
||||
analyze('diagnose')
|
||||
update('resolved')
|
||||
evidence.capture('diagnostics-after')
|
||||
if cancel_event.is_set():
|
||||
@@ -410,7 +420,9 @@ class IncidentRunner:
|
||||
evidence.event('retry_failed', error=type(error).__name__, code=getattr(error, 'code', ''), detail=str(error)[:1000])
|
||||
record['retry_error'] = scrub({'type': type(error).__name__, 'code': getattr(error, 'code', ''), 'detail': str(error)[:1000]})
|
||||
else:
|
||||
record['retry_skipped'] = 'Policy, execution authorization, current evidence or model recommendation did not admit replay.'
|
||||
record['retry_skipped'] = 'Policy, execution authorization or current durable evidence did not admit replay.'
|
||||
if certified:
|
||||
suggestion = analyze('diagnose')
|
||||
if cancel_event.is_set():
|
||||
return cancelled()
|
||||
snapshot, _ = take_snapshot()
|
||||
|
||||
@@ -32,7 +32,7 @@ def node_executable() -> str:
|
||||
def launch_environment(data_root: Path, *, native_model=False, credential_refs=()) -> dict[str, str]:
|
||||
allowed = {'SystemRoot', 'WINDIR', 'ComSpec', 'PATHEXT', 'PATH', 'TEMP', 'TMP',
|
||||
'APPDATA', 'LOCALAPPDATA', 'USERPROFILE', 'PROGRAMFILES', 'PROGRAMFILES(X86)',
|
||||
'DSH_API_BASE', 'DSH_MODEL', 'DSH_API_KEY'}
|
||||
'DSH_API_BASE', 'DSH_MODEL', 'DSH_API_KEY', 'DX_DSH_MODELS', 'DSH_PERMISSION_MODE'}
|
||||
allowed.update(ref for ref in credential_refs
|
||||
if isinstance(ref, str) and re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', ref))
|
||||
env = {key: value for key, value in os.environ.items() if key.upper() in {s.upper() for s in allowed}}
|
||||
|
||||
@@ -3,7 +3,9 @@ from __future__ import annotations
|
||||
from .actions import ActionProposal
|
||||
from .snapshot import TaskSnapshot
|
||||
|
||||
RETRYABLE_CODES = {"worker_error", "worker_timeout", "timeout", "quick_run_failed", "execution_failed", "native_failed"}
|
||||
from ..trial_task_center.execution_problems import TRANSIENT_CODES, classify_execution_failure
|
||||
|
||||
RETRYABLE_CODES = TRANSIENT_CODES
|
||||
|
||||
|
||||
def classify(snapshot: TaskSnapshot) -> str:
|
||||
@@ -11,9 +13,8 @@ def classify(snapshot: TaskSnapshot) -> str:
|
||||
code = snapshot.issue_code.casefold()
|
||||
if status in {"uncertain", "blocked"} or "uncertain" in code:
|
||||
return "manual_review"
|
||||
if status in {"failed", "error"} and code in RETRYABLE_CODES:
|
||||
return "retryable"
|
||||
if status in {"timeout", "timed_out"}:
|
||||
# A diagnostic snapshot cannot establish durable execution authority.
|
||||
if classify_execution_failure(code, status)['retry_allowed']:
|
||||
return "retryable"
|
||||
if status == "paused":
|
||||
return "paused"
|
||||
|
||||
@@ -35,8 +35,8 @@ def _json(value: Any) -> Any:
|
||||
def _check_scope(run_id: str, task_ids: Any, plan_hashes: Any) -> tuple[list[str], dict[str, str]]:
|
||||
if not isinstance(run_id, str) or not _ID.fullmatch(run_id):
|
||||
raise TaskCenterError("run_id", "run identifier is invalid")
|
||||
if not isinstance(task_ids, (list, tuple)) or not 1 <= len(task_ids) <= 20:
|
||||
raise TaskCenterError("run_scope", "run must contain 1 to 20 tasks")
|
||||
if not isinstance(task_ids, (list, tuple)) or not task_ids:
|
||||
raise TaskCenterError("run_scope", "run must contain distinct task identifiers")
|
||||
ids = list(task_ids)
|
||||
if any(not isinstance(item, str) or not _TASK_ID.fullmatch(item) for item in ids) or len(set(ids)) != len(ids):
|
||||
raise TaskCenterError("run_scope", "task identifiers are invalid")
|
||||
@@ -139,6 +139,136 @@ class RunJournal:
|
||||
db.execute("COMMIT")
|
||||
return self.get(run_id)
|
||||
|
||||
def begin_retry(self, service, run_id, task_id, operation_keys):
|
||||
"""Persist one reserved retry baseline before its first CAD dispatch."""
|
||||
selected = set(operation_keys or ())
|
||||
child = service.for_project_task(task_id)
|
||||
store = child._store
|
||||
context = child.task_context(task_id)
|
||||
if not selected or context.interrupted or context.progress.queue_complete:
|
||||
raise TaskCenterError('run_retry_scope', '重试缺少已准备且未执行的原失败项范围。')
|
||||
with store._lock:
|
||||
current = store._connection.execute('SELECT round_id FROM execution_rounds WHERE task_id=?', (task_id,)).fetchone()
|
||||
selection = store._connection.execute('SELECT keys_json FROM execution_retry_selections WHERE task_id=?', (task_id,)).fetchone()
|
||||
operations = {row['operation_key']: dict(row) for row in store._connection.execute(
|
||||
'SELECT * FROM execution_operations WHERE task_id=? AND round_id=?', (task_id, current[0]))} if current else {}
|
||||
reserved = {row[0] for row in store._connection.execute('''SELECT operation_key FROM execution_problems
|
||||
WHERE task_id=? AND round_id=? AND auto_retries=1 AND reservation_source='dsh' ''',
|
||||
(task_id, current[0]))} if current else set()
|
||||
if (not current or not selection or selected != set(json.loads(selection[0]))
|
||||
or not selected <= reserved or not selected <= operations.keys()
|
||||
or any(operations[key]['state'] != 'pending' for key in selected)):
|
||||
raise TaskCenterError('run_retry_scope', '原失败项重试预约、轮次或代次已变化。')
|
||||
with self._connect() as db:
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
row = self._row(db.execute('SELECT * FROM run_journal WHERE run_id=?', (run_id,)).fetchone())
|
||||
if not row or task_id not in row['task_ids'] or row['status'] not in {'failed', 'blocked', 'interrupted'}:
|
||||
raise TaskCenterError('run_retry_scope', '原运行不接受此自动重试。')
|
||||
value = row['result'] or {}
|
||||
entries = {item['task_id']: item for item in value.get('entries', ())}
|
||||
if set(entries) != set(row['task_ids']):
|
||||
raise TaskCenterError('run_retry_scope', '原运行回执范围不完整。')
|
||||
entries[task_id] = dict(entries[task_id], state='pending', message='已预约原失败项重试,尚未执行。')
|
||||
baseline = {item['task_id']: item for item in value.get('tasks', ())}
|
||||
p = context.progress
|
||||
baseline[task_id] = dict(baseline.get(task_id, {}), task_id=task_id, state='pending',
|
||||
interrupted=False, queue_complete=False, saved_items=p.saved_items,
|
||||
failed_items=p.failed_items, no_match_items=p.no_match_items)
|
||||
value.update(status='running', execution_status='running', entries=[entries[key] for key in row['task_ids']],
|
||||
tasks=list(baseline.values()), retry={'task_id': task_id, 'round_id': current[0],
|
||||
'operation_keys': sorted(selected), 'operations': operations})
|
||||
payload, stamp = json.dumps(value, ensure_ascii=False), _now()
|
||||
db.execute('INSERT INTO run_journal_receipts (run_id,finished_utc,status,result) VALUES (?,?,?,?)',
|
||||
(run_id, stamp, 'running', payload))
|
||||
db.execute("UPDATE run_journal SET status='running',finished_utc=NULL,result=? WHERE run_id=?", (payload, run_id))
|
||||
db.execute('COMMIT')
|
||||
return self.get(run_id)
|
||||
|
||||
@staticmethod
|
||||
def _same_pending_retry(child, task_id, before, after):
|
||||
if not after or before['state'] != 'pending' or after['state'] != 'pending':
|
||||
return False
|
||||
if after == before:
|
||||
return True
|
||||
return (after['attempt_id'] is None
|
||||
and {key: value for key, value in after.items() if key != 'receipt_json'}
|
||||
== {key: value for key, value in before.items() if key != 'receipt_json'}
|
||||
and child._quick_run_preparer.journal.certified_startup_pause(task_id, after))
|
||||
|
||||
@staticmethod
|
||||
def _retry_evidence_valid(service, retry):
|
||||
"""A targeted retry may advance only its reserved generation to success."""
|
||||
from ..trial_task_center.execution_proof import proof_intact
|
||||
try:
|
||||
child = service.for_project_task(retry['task_id'])
|
||||
with child._store._lock:
|
||||
current = child._store._connection.execute('SELECT round_id FROM execution_rounds WHERE task_id=?', (retry['task_id'],)).fetchone()
|
||||
rows = {row['operation_key']: dict(row) for row in child._store._connection.execute(
|
||||
'SELECT * FROM execution_operations WHERE task_id=? AND round_id=?', (retry['task_id'], retry['round_id']))}
|
||||
if not current or current[0] != retry['round_id'] or set(rows) != set(retry['operations']):
|
||||
return False
|
||||
for key, before in retry['operations'].items():
|
||||
after = rows[key]
|
||||
if key not in retry['operation_keys']:
|
||||
if after != before:
|
||||
return False
|
||||
elif after != before:
|
||||
if RunJournal._same_pending_retry(child, retry['task_id'], before, after):
|
||||
continue
|
||||
if (after['command_json'] != before['command_json'] or after['generation'] != before['generation'] + 1
|
||||
or after['state'] not in {'verified', 'restored', 'no_match'}):
|
||||
return False
|
||||
if after['state'] in {'verified', 'restored', 'no_match'}:
|
||||
receipt = json.loads(after['receipt_json'])
|
||||
proof = receipt.get('proof', {})
|
||||
if (not proof_intact(proof) or after['state'] == 'verified' and (
|
||||
not proof.get('files') or not proof.get('baseline')
|
||||
or receipt.get('native_state') not in {'saved_ok', 'restored_ok'})):
|
||||
return False
|
||||
attempt = proof.get('native_attempt')
|
||||
if attempt and (attempt.get('attempt_id') != after['attempt_id']
|
||||
or attempt.get('generation') != after['generation'] or attempt.get('task_id') != retry['task_id']):
|
||||
return False
|
||||
return True
|
||||
except (AttributeError, KeyError, TypeError, ValueError, OSError, sqlite3.Error):
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _retry_pending(service, retry):
|
||||
child = service.for_project_task(retry['task_id'])
|
||||
with child._store._lock:
|
||||
rows = {row['operation_key']: dict(row) for row in child._store._connection.execute(
|
||||
'SELECT * FROM execution_operations WHERE task_id=? AND round_id=?',
|
||||
(retry['task_id'], retry['round_id']))}
|
||||
return all(RunJournal._same_pending_retry(child, retry['task_id'], retry['operations'][key], rows.get(key))
|
||||
for key in retry['operation_keys'])
|
||||
|
||||
def repair_retry_checkpoint(self, service, run_id):
|
||||
"""Native-confirmed resume may finish this exact pre-dispatch intent."""
|
||||
from ..trial_task_center.task_queue import _save
|
||||
row = self.get(run_id)
|
||||
retry = (row.get('result') or {}).get('retry')
|
||||
if not retry:
|
||||
return
|
||||
if not self._retry_evidence_valid(service, retry):
|
||||
raise TaskCenterError('run_retry_scope', '预约重试证据或代次已变化。')
|
||||
if not self._retry_pending(service, retry):
|
||||
return
|
||||
paths = [self.data_root / folder / (run_id + '.json') for folder in ('task-queues', 'workspace-queues')]
|
||||
existing = [path for path in paths if path.is_file()]
|
||||
if len(existing) != 1:
|
||||
raise TaskCenterError('run_retry_scope', '原队列检查点缺失或有歧义。')
|
||||
path = existing[0]
|
||||
state = json.loads(path.read_text(encoding='utf-8'))
|
||||
if state.get('task_ids') != row['task_ids'] or state.get('plan_hashes') != row['plan_hashes']:
|
||||
raise TaskCenterError('run_retry_scope', '原队列范围已变化。')
|
||||
entry = state['entries'][retry['task_id']]
|
||||
if entry['state'] == 'failed':
|
||||
entry.update(state='running', message='接续已持久化的原失败项预约;尚未重放任何成功项。')
|
||||
if path.parent.name == 'workspace-queues':
|
||||
entry.update(released=False, problems_done=False)
|
||||
_save(path, state)
|
||||
|
||||
def get(self, run_id):
|
||||
with self._connect() as db:
|
||||
return self._row(db.execute("SELECT * FROM run_journal WHERE run_id = ?", (run_id,)).fetchone())
|
||||
@@ -155,6 +285,10 @@ class RunJournal:
|
||||
if row is None:
|
||||
raise TaskCenterError("run_missing", "run does not exist")
|
||||
blockers: list[str] = []
|
||||
retry = (row.get('result') or {}).get('retry')
|
||||
retry_valid = not retry or self._retry_evidence_valid(service, retry)
|
||||
if not retry_valid:
|
||||
blockers.append('retry_evidence_changed')
|
||||
checkpoint = self.data_root / "task-queues" / f"{run_id}.json"
|
||||
workspace_checkpoint = self.data_root / "workspace-queues" / f"{run_id}.json"
|
||||
workspace = workspace_checkpoint.is_file()
|
||||
@@ -171,7 +305,7 @@ class RunJournal:
|
||||
entries = queue["entries"]
|
||||
if set(entries) != set(row["task_ids"]) or any(
|
||||
not isinstance(entry, dict) or (not {"state", "message", "released", "problems_done", "checkpoint_id"} <= set(entry)
|
||||
or set(entry) - {"state", "message", "released", "problems_done", "checkpoint_id", "supervisor_batch_id"}
|
||||
or set(entry) - {"state", "message", "released", "problems_done", "checkpoint_id", "supervisor_batch_id", "netlist_verification"}
|
||||
if workspace else set(entry) != {"state", "message"}) or
|
||||
entry["state"] not in {"pending", "running", "paused", "blocked", "completed", "failed", "skipped"} or
|
||||
not isinstance(entry["message"], str) for entry in entries.values()
|
||||
@@ -204,6 +338,12 @@ class RunJournal:
|
||||
safe_continuations.add(task_id)
|
||||
has_evidence = has_evidence or context.has_evidence
|
||||
progress = context.progress
|
||||
if (queue and not workspace and queue['entries'][task_id]['state'] == 'failed'
|
||||
and context.has_evidence and (progress.queue_complete is True or context.phase == 'retry')
|
||||
and not context.interrupted):
|
||||
# The shared supervisor has closed the primary pass; global
|
||||
# resource checks below still gate all resumed problem work.
|
||||
released_primary.add(task_id)
|
||||
item.update({"status": context.task.status.value, "interrupted": bool(context.interrupted),
|
||||
"saved_items": int(getattr(progress, "saved_items", 0)),
|
||||
"failed_items": int(getattr(progress, "failed_items", 0)),
|
||||
@@ -222,7 +362,11 @@ class RunJournal:
|
||||
and context.interrupted is False):
|
||||
blockers.append('checkpoint_evidence_mismatch')
|
||||
from ..trial_task_center.task_queue import _plan_hash
|
||||
current_hashes[task_id] = _plan_hash(service.for_project_task(task_id), task_id)
|
||||
child = service.for_project_task(task_id)
|
||||
journal = getattr(getattr(child, '_quick_run_preparer', None), 'journal', None)
|
||||
if journal is not None and not journal.pending_pauses_intact(task_id):
|
||||
blockers.append('pause_evidence_changed')
|
||||
current_hashes[task_id] = _plan_hash(child, task_id)
|
||||
if current_hashes[task_id] != row["plan_hashes"][task_id]:
|
||||
blockers.append("plan_changed")
|
||||
except Exception:
|
||||
@@ -231,12 +375,17 @@ class RunJournal:
|
||||
if queue:
|
||||
counters["completed"] = sum(queue["entries"][task_id]["state"] in {"completed", "failed", "skipped"} for task_id in row["task_ids"])
|
||||
remaining = [task_id for task_id in row["task_ids"] if not queue or queue["entries"][task_id]["state"] not in {"completed", "failed", "skipped"}]
|
||||
if queue and not workspace and queue.get('phase') in {'primary', 'problems'}:
|
||||
remaining = [key for key in row['task_ids'] if key in remaining or key in released_primary]
|
||||
if workspace and queue:
|
||||
primary_exhausted = all(entry['state'] in {'completed', 'failed', 'skipped', 'blocked'} for entry in queue['entries'].values())
|
||||
remaining = [key for key in row['task_ids'] if key not in isolated and (
|
||||
queue['entries'][key]['state'] not in {'completed', 'failed', 'skipped'} or
|
||||
(queue['phase'] == 'problems' or queue['phase'] == 'primary' and primary_exhausted)
|
||||
and not queue['entries'][key]['problems_done'])]
|
||||
if (retry and retry_valid and queue and queue['entries'][retry['task_id']]['state'] == 'failed'
|
||||
and self._retry_pending(service, retry)):
|
||||
remaining = [key for key in row['task_ids'] if key in remaining or key == retry['task_id']]
|
||||
if "queue_missing" in blockers and not has_evidence:
|
||||
# The receipt may have committed before the executor created its checkpoint.
|
||||
# A native reconfirmation can safely create the original queue; no auto replay.
|
||||
|
||||
@@ -37,10 +37,10 @@ def _now():
|
||||
|
||||
|
||||
def _ids(values, *, required=True):
|
||||
if not isinstance(values, (list, tuple)) or (required and not 1 <= len(values) <= 20):
|
||||
raise TaskCenterError("schedule_scope", "schedule must contain 1 to 20 task identifiers")
|
||||
if not isinstance(values, (list, tuple)) or (required and not values):
|
||||
raise TaskCenterError("schedule_scope", "schedule must contain distinct task identifiers")
|
||||
values = list(values)
|
||||
if len(values) > 20 or any(not isinstance(value, str) or not _TASK_ID.fullmatch(value) for value in values) or len(set(values)) != len(values):
|
||||
if any(not isinstance(value, str) or not _TASK_ID.fullmatch(value) for value in values) or len(set(values)) != len(values):
|
||||
raise TaskCenterError("schedule_scope", "task identifiers are invalid")
|
||||
return values
|
||||
|
||||
@@ -271,16 +271,22 @@ class ScheduleStore:
|
||||
db.execute('COMMIT')
|
||||
return self.get(schedule_id)
|
||||
|
||||
def finish(self, schedule_id, status, **values):
|
||||
def finish(self, schedule_id, status, *, repair_run_id=None, **values):
|
||||
if status not in {"completed", "failed", "interrupted", "cancelled"}:
|
||||
raise TaskCenterError("schedule_status", "schedule finish status is invalid")
|
||||
with self._connect() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
row = db.execute("SELECT status FROM schedules WHERE schedule_id = ?", (schedule_id,)).fetchone()
|
||||
row = db.execute("SELECT status,run_id FROM schedules WHERE schedule_id = ?", (schedule_id,)).fetchone()
|
||||
if row is None:
|
||||
db.execute("ROLLBACK"); raise TaskCenterError("schedule_missing", "schedule does not exist")
|
||||
if row["status"] != "claimed":
|
||||
if repair_run_id is not None and (not isinstance(repair_run_id, str) or not _ID.fullmatch(repair_run_id)
|
||||
or row['run_id'] != repair_run_id or values.get('run_id') != repair_run_id
|
||||
or row['status'] not in {'claimed', 'failed', 'interrupted'}):
|
||||
db.execute('ROLLBACK'); raise TaskCenterError('schedule_run_conflict', '排期已绑定其他尝试或不接受原运行回执修复。')
|
||||
if row["status"] != "claimed" and repair_run_id is None:
|
||||
db.execute("ROLLBACK"); raise TaskCenterError("schedule_status", "only a claimed schedule can finish")
|
||||
if repair_run_id is not None:
|
||||
values['same_run_repair'] = True
|
||||
stamp = _now().isoformat(timespec="seconds")
|
||||
db.execute("UPDATE schedules SET status = ?, updated_utc = ?, finished_utc = ?, run_id = ?, result = ? WHERE schedule_id = ?",
|
||||
(status, stamp, stamp, values.get("run_id"), json.dumps(values, ensure_ascii=False), schedule_id))
|
||||
|
||||
@@ -47,8 +47,8 @@ def fingerprint(service, ids):
|
||||
def preflight(service, task_ids, *, allow_completed=False):
|
||||
from ..trial_task_center.ui.execution_state import execution_state
|
||||
from ..trial_task_center.task_queue import _plan_hash
|
||||
if not isinstance(task_ids, list) or not 1 <= len(task_ids) <= 20 or len(set(task_ids)) != len(task_ids):
|
||||
raise TaskCenterError('assistant_task_scope', '请选择 1 至 20 个不同的真实任务。')
|
||||
from .impact import _scope
|
||||
task_ids = _scope(task_ids)
|
||||
tasks, paths, hashes = [], set(), {}
|
||||
pending = bool(service.pending_batch_resources())
|
||||
for task_id in task_ids:
|
||||
@@ -68,18 +68,23 @@ def preflight(service, task_ids, *, allow_completed=False):
|
||||
blockers.append('本次范围重复包含同一个工程。')
|
||||
else:
|
||||
paths.add(str(path.resolve()).casefold())
|
||||
count = sum(row.enabled for row in (context.targets if context.task.target_plan_mode else context.rules))
|
||||
requests = getattr(context, 'pending_bom', ())
|
||||
from ..trial_task_center.bom_pending import retained_bom_rows
|
||||
retained = retained_bom_rows(requests, context.targets) if requests else ()
|
||||
count = (sum(len(item.refs) for item in requests if item.record.enabled) + len(retained) if requests else
|
||||
sum(row.enabled for row in (context.targets if context.task.target_plan_mode else context.rules)))
|
||||
if not count:
|
||||
blockers.append('没有已启用的替换规则或位号。')
|
||||
try:
|
||||
service._execution_rules(task_id)
|
||||
except TaskCenterError as error:
|
||||
blockers.append(error.message)
|
||||
if not requests:
|
||||
try:
|
||||
service._execution_rules(task_id)
|
||||
except TaskCenterError as error:
|
||||
blockers.append(error.message)
|
||||
if pending:
|
||||
blockers.append('上一次执行的后台资源尚未释放。')
|
||||
hashes[task_id] = _plan_hash(service.for_project_task(task_id), task_id)
|
||||
tasks.append({**_summary(context.task), 'project': str(path or ''), 'enabled_rules': count,
|
||||
'phase': context.phase, 'blockers': list(dict.fromkeys(blockers)),
|
||||
'phase': context.phase, 'verification_pending': bool(requests), 'blockers': list(dict.fromkeys(blockers)),
|
||||
'saved_items': context.progress.saved_items, 'failed_items': context.progress.failed_items,
|
||||
'no_match_items': context.progress.no_match_items})
|
||||
from .impact import execution_impact
|
||||
@@ -224,4 +229,5 @@ def copy_spec(service, task_id):
|
||||
'copy_part_number_to_value': context.task.copy_part_number_to_value,
|
||||
'rules': [{'old_part_number': r.old_part_number, 'new_part_number': r.new_part_number,
|
||||
'target_cell': r.target_cell, 'sync_nc': r.sync_nc, 'enabled': r.enabled,
|
||||
**({'custom_value': r.custom_value} if r.custom_value_enabled else {})} for r in context.rules]}
|
||||
**({'custom_value': r.custom_value} if r.custom_value_enabled else {}),
|
||||
**({'value_mode': r.value_mode} if hasattr(r, 'value_mode') else {})} for r in context.rules]}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.0 MiB |
Binary file not shown.
|
Before Width: | Height: | Size: 48 KiB After Width: | Height: | Size: 107 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 1.0 MiB |
@@ -1,18 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256">
|
||||
<defs>
|
||||
<linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop stop-color="#164D91"/>
|
||||
<stop offset="1" stop-color="#079D98"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect x="16" y="16" width="224" height="224" rx="52" fill="url(#tile)"/>
|
||||
<g fill="none" stroke="#FFFFFF" stroke-width="12" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M62 97V82Q62 60 84 60H184M169 46L184 60L169 74"/>
|
||||
<path d="M194 159V174Q194 196 172 196H72M87 182L72 196L87 210"/>
|
||||
</g>
|
||||
<g fill="none" stroke="#FFFFFF" stroke-width="9" stroke-linecap="round">
|
||||
<rect x="88" y="96" width="80" height="64" rx="10"/>
|
||||
<path d="M76 112H88M76 128H88M76 144H88M168 112H180M168 128H180M168 144H180"/>
|
||||
</g>
|
||||
<rect x="109" y="117" width="38" height="22" rx="5" fill="#9BF0DE"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 883 B |
@@ -159,7 +159,11 @@ def execute_batch(
|
||||
issues = service.execution_problems(task_id)
|
||||
from .execution_journal import command_identity, _hash
|
||||
key = _hash(command_identity(current_row))
|
||||
if not any(issue['operation_key'] == key and issue['classification'] != 'uncertain' for issue in issues):
|
||||
from .execution_problems import classify_execution_failure
|
||||
certified = journal is not None and journal.failure_certified(task_id, current_row)
|
||||
policy = classify_execution_failure(error.code, 'failed', certified=certified)
|
||||
if not policy['continue_allowed'] or not any(
|
||||
issue['operation_key'] == key and issue['classification'] != 'uncertain' for issue in issues):
|
||||
raise
|
||||
candidate = preparer.progress(task_id, projects, rules,
|
||||
copy_part_number_to_value=task.copy_part_number_to_value)
|
||||
|
||||
@@ -10,6 +10,7 @@ from uuid import uuid4
|
||||
from .errors import TaskCenterError
|
||||
from .execution_metrics import measure_phase
|
||||
from .logging_setup import append_task_event
|
||||
from .path_access import internal_path, retry_sharing_violation
|
||||
from .quick_run import TERMINAL_STATES, _path_key
|
||||
from .schematic_backup import BACKUP_MANIFEST_NAME, _is_link_or_reparse
|
||||
|
||||
@@ -19,7 +20,10 @@ _BACKUP_DIRECTORY_NAME = 'batch-backups'
|
||||
|
||||
def inherit_backup_for_retry(archive, root, task_id):
|
||||
"""Carry the verified original backup forward; never back up modified work as original."""
|
||||
if archive is None or not (archive / _BACKUP_STATE_NAME).is_file():
|
||||
if archive is None:
|
||||
return
|
||||
archive, root = internal_path(archive), internal_path(root)
|
||||
if not (archive / _BACKUP_STATE_NAME).is_file():
|
||||
return
|
||||
state = _read_backup_state(archive / _BACKUP_STATE_NAME, task_id)
|
||||
for key, entry in state.items():
|
||||
@@ -36,7 +40,7 @@ def inherit_backup_for_retry(archive, root, task_id):
|
||||
raise TaskCenterError('quick_run_backup_invalid', '重试备份目标已存在,已停止以保留原证据。')
|
||||
temporary = root / f'.retry-backups-{uuid4().hex}'
|
||||
shutil.copytree(source, temporary)
|
||||
os.replace(temporary, destination)
|
||||
retry_sharing_violation(lambda: os.replace(temporary, destination), target=destination)
|
||||
for key, entry in state.items():
|
||||
if entry.get('status') == 'backed_up' and not _reusable_backup(root, key, entry):
|
||||
raise TaskCenterError('quick_run_backup_invalid', '重试备份复制校验失败,原备份保留。')
|
||||
|
||||
@@ -160,7 +160,7 @@ def _process_gone(identity):
|
||||
handle.Close()
|
||||
|
||||
|
||||
def cleanup_pending_resources(root, *, logging_context=None):
|
||||
def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False):
|
||||
from .isolated_desktop import _Win32Api
|
||||
from .batch_release_log import write_release_event
|
||||
from .isolated_cad import RETAINED_CAD_SESSIONS
|
||||
@@ -193,7 +193,7 @@ def cleanup_pending_resources(root, *, logging_context=None):
|
||||
live = LIVE_RESOURCES.get(str(path))
|
||||
if live is not None:
|
||||
try:
|
||||
live.close(reason='manual_retry')
|
||||
live.close(reason='manual_retry' if retry_failed else 'resource_recheck')
|
||||
except Exception:
|
||||
pass # The live owner records the failure and retains ownership.
|
||||
continue
|
||||
|
||||
@@ -6,6 +6,7 @@ import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
from threading import Lock
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from .batch_resources import (BatchResourceCleanupError, LIVE_RESOURCES, cleanup_pending_resources,
|
||||
@@ -133,6 +134,7 @@ class BatchCadRuntime:
|
||||
self._attempt_sources = {}
|
||||
self._close_failure = None
|
||||
self._close_failure_rebuild = False
|
||||
self._release_lock = Lock()
|
||||
|
||||
def bind_logs(self, context, task_ids):
|
||||
"""Keep every participating task's final release outcome visible."""
|
||||
@@ -149,6 +151,13 @@ class BatchCadRuntime:
|
||||
guard_pending_resources(self.root)
|
||||
return self
|
||||
|
||||
def begin_task(self, task_id):
|
||||
# Attribute pre-dispatch work to this task while retaining the previous
|
||||
# CAD project's checkpoint/job until the next worker actually starts.
|
||||
self.record['active_task'] = task_id
|
||||
if self.generation:
|
||||
self._save()
|
||||
|
||||
def __exit__(self, error_type, error, traceback):
|
||||
if error is not None and self._active_evidence is not None:
|
||||
# Only the current generation can still own an in-flight CAD write.
|
||||
@@ -161,6 +170,7 @@ class BatchCadRuntime:
|
||||
if not getattr(getattr(self.stop_event, 'force_event', None), 'is_set', lambda: False)():
|
||||
raise
|
||||
# Explicit force has durable protection; cleanup is now allowed.
|
||||
self._cad_close_error = error
|
||||
try:
|
||||
self.close()
|
||||
except Exception as cleanup:
|
||||
@@ -197,7 +207,8 @@ class BatchCadRuntime:
|
||||
name = 'dx-' + uuid4().hex
|
||||
self._save(state='starting', generation=self.generation, desktop=name,
|
||||
processes=[], cad_pid=None, cad_guid=None, checkpoints={}, native_operations={},
|
||||
cad_process=None, cad_token=None, cad_shutdown=None, cad_start_requested=False, cleanup=None)
|
||||
cad_process=None, cad_token=None, cad_shutdown=None, cad_start_requested=False, cleanup=None,
|
||||
release_state={'mentor': 'not_started', 'desktop': 'pending'})
|
||||
LIVE_RESOURCES[str(self.path)] = self
|
||||
self.desktop = self.desktop_factory(name, enabled=True)
|
||||
started = time.monotonic()
|
||||
@@ -233,14 +244,18 @@ class BatchCadRuntime:
|
||||
cad_process = getattr(self.cad, 'cad', None)
|
||||
if cad_process is not None and cad_process not in processes:
|
||||
processes.append(cad_process)
|
||||
if not processes:
|
||||
cleanup = getattr(self.desktop, 'cleanup_record', None) or {}
|
||||
# Closing our handle follows owned-process cleanup. An external
|
||||
# desktop reference can outlive those processes without owning them.
|
||||
return cleanup.get('desktop_handle_closed') is True
|
||||
try:
|
||||
from .read_recovery import process_tree_exited
|
||||
return bool(processes) and all(process_tree_exited(process) for process in processes)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def reset_project_after_safe_failure(self, project, evidence_root, *, job_id=None):
|
||||
"""Discard a checkpointed project session before another admitted item."""
|
||||
def _closed_project_checkpoint(self, project, evidence_root):
|
||||
root = canonical_path(evidence_root)
|
||||
try:
|
||||
checkpoint = json.loads(internal_path(root / 'project-checkpoint.json').read_text(encoding='utf-8'))
|
||||
@@ -252,6 +267,11 @@ class BatchCadRuntime:
|
||||
safe = False
|
||||
if not safe:
|
||||
raise BatchResourceCleanupError('缺少当前工程关闭检查点证明,不能继续执行。')
|
||||
return root, checkpoint
|
||||
|
||||
def reset_project_after_safe_failure(self, project, evidence_root, *, job_id=None):
|
||||
"""Discard a checkpointed project session after a failed item."""
|
||||
root, checkpoint = self._closed_project_checkpoint(project, evidence_root)
|
||||
from .batch_attempt import can_retry_attempt
|
||||
from .discovery_cache import project_fingerprint
|
||||
attempt_id = checkpoint['attempt_id']
|
||||
@@ -298,7 +318,9 @@ class BatchCadRuntime:
|
||||
|
||||
def dialog_state(self):
|
||||
guard = getattr(self.cad, '_dialogs', None)
|
||||
return guard.summary() if guard is not None else None
|
||||
if guard is None:
|
||||
return None
|
||||
return dict(guard.summary(), release_state=getattr(self.cad, 'record', {}).get('release_state'))
|
||||
|
||||
def business_progress(self):
|
||||
if self._active_evidence is None:
|
||||
@@ -332,15 +354,19 @@ class BatchCadRuntime:
|
||||
try:
|
||||
cad.__enter__()
|
||||
except Exception as error:
|
||||
from .isolated_cad import PrivateCadStartupError
|
||||
from .isolated_cad import PrivateCadStartupError, PrivateCadStartupCancelled
|
||||
if isinstance(error, PrivateCadStartupError):
|
||||
# __enter__ certified its local processes/handles closed.
|
||||
# A never-ready instance must not receive a second Quit.
|
||||
self.cad = None
|
||||
if (isinstance(error, PrivateCadStartupCancelled)
|
||||
and not getattr(getattr(self.stop_event, 'force_event', None), 'is_set', lambda: False)()):
|
||||
check_cancelled(abort_event or self.stop_event)
|
||||
raise
|
||||
self._timing('cad_start', started)
|
||||
self._save(state='ready', cad_pid=cad.binding.pid, cad_guid=cad.binding.guid,
|
||||
cad_process=process_identity(cad.cad) if getattr(cad, 'cad', None) is not None else None)
|
||||
cad_process=process_identity(cad.cad) if getattr(cad, 'cad', None) is not None else None,
|
||||
release_state={'mentor': 'active', 'desktop': 'pending'})
|
||||
return self.cad
|
||||
|
||||
def _prepare_attempts(self, root, command, attempt_id, generation):
|
||||
@@ -382,6 +408,36 @@ class BatchCadRuntime:
|
||||
'worker_closed': True, 'cad_pid': self.record['cad_pid'], 'cad_guid': self.record['cad_guid']})
|
||||
self._active_attempts = []
|
||||
|
||||
def _pause_unlaunched_worker(self, root, project, command, attempt_id, expected, before, inputs):
|
||||
"""Only the caller that has not invoked its process factory may certify this."""
|
||||
from .batch_attempt import can_retry_attempt
|
||||
from .discovery_cache import project_fingerprint
|
||||
from .project_session_health import _source_parameters
|
||||
self.close(reason='pause_before_worker_launch')
|
||||
absent = self.desktop is None and self.cad is None and self.generation == 0
|
||||
if (not absent and (self.record['state'] != 'released' or not self.owned_processes_exited())
|
||||
or before is None or before != project_fingerprint(project, self.root)
|
||||
or any(data != (internal_path(root / name).read_bytes() if internal_path(root / name).exists() else None)
|
||||
for name, data in inputs.items())
|
||||
or not expected or not all(can_retry_attempt(path, record) for path, record in expected)):
|
||||
raise WorkerMonitorError('unlaunched pause lacks unchanged inputs and released ownership')
|
||||
proof = dict(phase='before_worker_launch', worker_launch_attempted=False,
|
||||
task_id=self.record['active_task'], job_id=command[-1], project_path=str(project),
|
||||
session_id=self.session_id, generation=self.generation, attempt_id=attempt_id,
|
||||
resource_record=str(self.path), native_dispatch_not_started=True,
|
||||
project_closed=True, worker_tree_exited=True, resources_released=True,
|
||||
source_sha256=hashlib.sha256(repr(before).encode()).hexdigest(),
|
||||
batch_attempts=[{'path': str(path), 'expected': record} for path, record in expected])
|
||||
proof.update(_source_parameters(project, self.root))
|
||||
for name, key in (('command.tsv', 'command_sha256'), ('current-command.tsv', 'current_command_sha256'),
|
||||
('status.tsv', 'status_sha256'), ('project-session.request', 'request_sha256')):
|
||||
proof[key] = hashlib.sha256(inputs[name]).hexdigest() if inputs[name] is not None else None
|
||||
proof_path = root / ('unlaunched-pause-' + attempt_id + '.json')
|
||||
write_record(proof_path, proof)
|
||||
proof['files'] = [{'path': str(path), 'sha256': hashlib.sha256(internal_path(path).read_bytes()).hexdigest()}
|
||||
for path in (proof_path, *(path for path, record in expected))]
|
||||
return proof
|
||||
|
||||
def run_worker(self, command, timeout, *, abort_event=None, cooperative_abort=False):
|
||||
from .discovery_cache import project_fingerprint
|
||||
from .isolated_cad import PrivateCadStartupError, is_identity_conflict
|
||||
@@ -395,13 +451,15 @@ class BatchCadRuntime:
|
||||
selected = [row for row in _read_commands(internal_path(root / 'command.tsv')) if row[1] == command[-1]]
|
||||
if len(selected) != 1:
|
||||
raise TaskCenterError('target_identity', '批次工作命令身份缺失或重复,已停止。')
|
||||
if canonical_path(selected[0][2]) != canonical_path(self.record['active_project']):
|
||||
if self._active_evidence is None:
|
||||
raise BatchResourceCleanupError('缺少上一工程关闭检查点,不能启动下一工程。')
|
||||
self.reset_project_after_safe_failure(self.record['active_project'], self._active_evidence)
|
||||
if self._active_evidence is None:
|
||||
raise BatchResourceCleanupError('缺少上一工程关闭检查点,不能启动下一工程。')
|
||||
# A new worker needs the preceding empty-project checkpoint even
|
||||
# when it revisits the same project in the retained CAD session.
|
||||
self._closed_project_checkpoint(self.record['active_project'], self._active_evidence)
|
||||
self._active_evidence = root
|
||||
while True:
|
||||
check_cancelled(abort_event or self.stop_event)
|
||||
if self.read_only:
|
||||
check_cancelled(abort_event or self.stop_event)
|
||||
attempt_id = uuid4().hex
|
||||
# No previous empty-project certificate may authorize continuation
|
||||
# once another operation could attach or open a project.
|
||||
@@ -412,28 +470,70 @@ class BatchCadRuntime:
|
||||
generation = self.generation + (self.desktop is None)
|
||||
project, directory, expected = self._prepare_attempts(root, command, attempt_id, generation)
|
||||
self._active_attempts = list(expected)
|
||||
self._ensure_desktop(abort_event)
|
||||
# Make the current task/attempt durable before any worker or CAD
|
||||
# mutation can begin. A crash in the following window must protect
|
||||
# this task rather than a stale completed task from session.json.
|
||||
self._save(active_task=self.record['active_task'], active_attempt=attempt_id)
|
||||
before = project_fingerprint(project, self.root)
|
||||
self._attempt_sources[attempt_id] = before
|
||||
status = internal_path(root / 'status.tsv')
|
||||
status_before = status.read_bytes() if status.exists() else None
|
||||
request_path = internal_path(root / 'project-session.request')
|
||||
request_before = request_path.read_bytes() if request_path.exists() else None
|
||||
current_path = internal_path(root / 'current-command.tsv')
|
||||
current_before = current_path.read_bytes() if current_path.exists() else None
|
||||
inputs = {'command.tsv': internal_path(root / 'command.tsv').read_bytes(),
|
||||
'status.tsv': status_before, 'project-session.request': request_before,
|
||||
'current-command.tsv': current_before}
|
||||
started = time.monotonic()
|
||||
failure = None
|
||||
worker_launch_attempted = False
|
||||
try:
|
||||
check_cancelled(abort_event or self.stop_event)
|
||||
self._ensure_desktop(abort_event)
|
||||
# Persist the current owner before any CAD/worker launch.
|
||||
self._save(active_task=self.record['active_task'], active_attempt=attempt_id)
|
||||
cad = self._ensure_cad(abort_event)
|
||||
cad.checkpoint(root / ('cad-ready-' + attempt_id + '.json'))
|
||||
environment = {'DXPART_ATTEMPT_FILE': str(directory), 'DXPART_ATTEMPT_ID': attempt_id,
|
||||
'DXPART_BATCH_SESSION_ID': self.session_id, 'DXPART_BATCH_GENERATION': str(self.generation)}
|
||||
def start_worker(launch, **options):
|
||||
return cad.start_worker(launch, extra_environment=environment, **options)
|
||||
nonlocal worker_launch_attempted
|
||||
worker_launch_attempted = True
|
||||
return cad.start_worker(launch, job_id=command[-1], extra_environment=environment, **options)
|
||||
result = run_monitored_process(command, timeout, abort_event=abort_event,
|
||||
cooperative_abort=cooperative_abort, process_factory=start_worker,
|
||||
**({'owner_loss_path': self.path.parent / 'owner-loss.json'} if self.read_only else {}),
|
||||
**({'force_control': self.stop_event} if hasattr(self.stop_event, 'force_event') else {}))
|
||||
if result.returncode == 74 and not self.read_only:
|
||||
from .batch_attempt import can_retry_attempt
|
||||
pause = getattr(result, 'startup_pause', {})
|
||||
request = internal_path(root / 'project-session.request').read_text(encoding='utf-8-sig').strip().split('\t')
|
||||
if (len(request) != 3 or pause.get('session_token') != request[0]
|
||||
or request_before is None or request_path.read_bytes() != request_before
|
||||
or request[2] != command[-1] or pause.get('job_id') != command[-1]
|
||||
or canonical_path(request[1]) != project or canonical_path(pause.get('project_path', '')) != project
|
||||
or pause.get('sequence') != 1 or pause.get('worker_tree_exited') is not True
|
||||
or not ((abort_event is not None and abort_event.is_set()) or (self.stop_event is not None and self.stop_event.is_set()))
|
||||
or getattr(getattr(self.stop_event, 'force_event', None), 'is_set', lambda: False)()
|
||||
or before is None or before != project_fingerprint(project, self.root)
|
||||
or status_before != (status.read_bytes() if status.exists() else None)
|
||||
or current_before != (current_path.read_bytes() if current_path.exists() else None)
|
||||
or not expected or not all(can_retry_attempt(path, record) for path, record in expected)):
|
||||
raise WorkerMonitorError('startup pause lacks bound unchanged pre-dispatch evidence')
|
||||
self._checkpoint(root, project, attempt_id)
|
||||
from .project_session_health import _source_parameters
|
||||
proof = dict(pause, task_id=self.record['active_task'], session_id=self.session_id,
|
||||
generation=self.generation, attempt_id=attempt_id, resource_record=str(self.path),
|
||||
project_closed=True, native_dispatch_not_started=True,
|
||||
source_sha256=hashlib.sha256(repr(before).encode()).hexdigest(),
|
||||
request_sha256=hashlib.sha256(request_before).hexdigest(),
|
||||
status_sha256=hashlib.sha256(status_before).hexdigest() if status_before is not None else None,
|
||||
current_command_sha256=hashlib.sha256(current_before).hexdigest() if current_before is not None else None,
|
||||
batch_attempts=[{'path': str(path), 'expected': record} for path, record in expected])
|
||||
proof.update(_source_parameters(project, self.root))
|
||||
proof_path = root / ('startup-pause-' + attempt_id + '.json')
|
||||
write_record(proof_path, proof)
|
||||
files = [proof_path, *(path for path, record in expected)]
|
||||
result.startup_pause = dict(proof, files=[{'path': str(path),
|
||||
'sha256': hashlib.sha256(internal_path(path).read_bytes()).hexdigest()} for path in files])
|
||||
return result
|
||||
if result.returncode and self.read_only:
|
||||
raise WorkerMonitorError(result.stderr or 'read-only worker failed')
|
||||
if result.returncode:
|
||||
@@ -443,11 +543,19 @@ class BatchCadRuntime:
|
||||
if result.returncode not in (2, 3):
|
||||
return result
|
||||
failure = WorkerMonitorError(result.stderr or 'pre-mutation worker startup failed')
|
||||
except TaskCenterError as error:
|
||||
if (error.code == 'operation_cancelled' and not self.read_only and not worker_launch_attempted
|
||||
and not getattr(getattr(self.stop_event, 'force_event', None), 'is_set', lambda: False)()):
|
||||
error.unlaunched_worker_pause = self._pause_unlaunched_worker(
|
||||
root, project, command, attempt_id, expected, before, inputs)
|
||||
raise
|
||||
except (PrivateCadStartupError, WorkerMonitorError, subprocess.TimeoutExpired, OSError) as error:
|
||||
failure = error
|
||||
finally:
|
||||
self._timing('project_worker', started, project=str(project), attempt_id=attempt_id,
|
||||
task_id=self.record['active_task'], job_id=self.record['active_job'])
|
||||
if self.release_for_error(failure, root):
|
||||
raise failure
|
||||
if self.read_only:
|
||||
self.close(reason='read_failure')
|
||||
write_record(root / 'project-read-release.json', {'version': 1,
|
||||
@@ -507,7 +615,31 @@ class BatchCadRuntime:
|
||||
from .stop_control import wait_for_resolution
|
||||
attempts = self._project_attempts.get(str(project).casefold(), expected)
|
||||
if attempts and not all(can_retry_attempt(path, record) for path, record in attempts):
|
||||
wait_for_resolution(self.stop_event, root, error, resolved=self.owned_processes_exited)
|
||||
from .stop_control import MentorReleaseRequired
|
||||
try:
|
||||
wait_for_resolution(self.stop_event, root, error, resolved=self.owned_processes_exited,
|
||||
release_on_failure=True)
|
||||
except MentorReleaseRequired as release:
|
||||
release.primary_error = error
|
||||
self.release_for_error(release, root)
|
||||
raise
|
||||
|
||||
def release_for_error(self, error, root):
|
||||
"""Handle the release signal in its owning supervisor, before batch end."""
|
||||
if getattr(error, 'code', None) != 'mentor_release_required':
|
||||
return False
|
||||
self._cad_close_error = error
|
||||
request = getattr(self.stop_event, 'request_failure_cleanup', None)
|
||||
if request is not None and getattr(self.stop_event, 'cleanup_mode', None) != error.code:
|
||||
request(root, error)
|
||||
elif self.stop_event is not None:
|
||||
self.stop_event.set()
|
||||
try:
|
||||
self.close(reason='error_code')
|
||||
except BatchResourceCleanupError as cleanup:
|
||||
cleanup.primary_error = error
|
||||
raise
|
||||
return True
|
||||
|
||||
def recover_native_failure(self, project, evidence, reason):
|
||||
"""One read-only recovery, based on durable source and worker proof."""
|
||||
@@ -570,14 +702,63 @@ class BatchCadRuntime:
|
||||
pass # A diagnostic write cannot bypass process/desktop cleanup.
|
||||
|
||||
def close(self, *, rebuilding=False, reason=None):
|
||||
if not self._release_lock.acquire(blocking=False):
|
||||
raise BatchResourceCleanupError('资源释放正在进行,请等待当前释放结果。')
|
||||
try:
|
||||
return self._close_once(rebuilding=rebuilding, reason=reason)
|
||||
finally:
|
||||
self._release_lock.release()
|
||||
|
||||
def _close_once(self, *, rebuilding=False, reason=None):
|
||||
if self.desktop is None and not self.generation:
|
||||
return # A cache-only batch never acquired resources.
|
||||
if self.record['state'] == 'released':
|
||||
return
|
||||
reason = reason or ('rebuild' if rebuilding else 'batch_end')
|
||||
if self._close_failure is not None and self._close_failure_rebuild and reason != 'manual_retry':
|
||||
raise BatchResourceCleanupError(str(self._close_failure), completed_result=self.result,
|
||||
cleanup_error=self._close_failure)
|
||||
if self._close_failure is not None:
|
||||
cleanup = getattr(self.desktop, 'cleanup_record', None) or {}
|
||||
if (reason != 'manual_retry' and cleanup.get('desktop_handle_closed') is False
|
||||
and any(event.get('operation') == 'close' and event.get('success') is False
|
||||
for event in cleanup.get('desktop_handle_history', ()))):
|
||||
raise BatchResourceCleanupError(str(self._close_failure),
|
||||
completed_result=self.result, cleanup_error=self._close_failure)
|
||||
if (reason == 'resource_recheck'
|
||||
and self.record.get('release_results', {}).get('desktop_released') is not True
|
||||
and cleanup.get('desktop_handle_closed') is True
|
||||
and not getattr(self.desktop, '_processes', getattr(self.desktop, 'processes', ()))
|
||||
and self.owned_processes_exited()):
|
||||
# Observe the same namespace only. Never replay Quit, process
|
||||
# disposal or CloseDesktop just because a foreign reference stayed.
|
||||
observe = getattr(self.desktop, 'release_desktop', None)
|
||||
if observe is not None:
|
||||
try:
|
||||
observe()
|
||||
except Exception:
|
||||
self.record['cleanup'] = self.desktop.cleanup_record
|
||||
self._save()
|
||||
raise BatchResourceCleanupError(str(self._close_failure),
|
||||
completed_result=self.result, cleanup_error=self._close_failure)
|
||||
cleanup = self.desktop.cleanup_record or {}
|
||||
self.record['cleanup'] = cleanup
|
||||
if cleanup.get('desktop_confirmation', {}).get('released') is True:
|
||||
self.record['release_results'] = {'mentor_released': True, 'desktop_released': True}
|
||||
self.record['release_state'] = {'mentor': 'released', 'desktop': 'released'}
|
||||
self._release_log('started', reason=reason)
|
||||
self._record_release()
|
||||
self._release_log('succeeded', reason=reason)
|
||||
return
|
||||
raise BatchResourceCleanupError(str(self._close_failure),
|
||||
completed_result=self.result, cleanup_error=self._close_failure)
|
||||
if (not self._close_failure_rebuild or reason in {'manual_retry', 'resource_recheck'}) and all(
|
||||
self.record.get('release_results', {}).get(key) is True
|
||||
for key in ('mentor_released', 'desktop_released')):
|
||||
self._record_release()
|
||||
return
|
||||
if self.owned_processes_exited():
|
||||
self.cad = None # Only remaining handle cleanup is needed; never send Quit again.
|
||||
elif reason != 'manual_retry':
|
||||
raise BatchResourceCleanupError(str(self._close_failure), completed_result=self.result,
|
||||
cleanup_error=self._close_failure)
|
||||
if reason == 'manual_retry':
|
||||
self._close_failure = None
|
||||
started = time.monotonic()
|
||||
@@ -597,14 +778,16 @@ class BatchCadRuntime:
|
||||
started = time.monotonic()
|
||||
errors = []
|
||||
retained_cad = False
|
||||
phases = {'mentor': 'closing' if self.cad is not None else 'released', 'desktop': 'waiting_for_mentor'}
|
||||
try:
|
||||
self._save(state='closing')
|
||||
self._save(state='closing', release_state=phases)
|
||||
except Exception as error:
|
||||
errors.append('resource journal: ' + str(error))
|
||||
if self.cad is not None:
|
||||
cad = self.cad
|
||||
try:
|
||||
cad.__exit__(None, None, None)
|
||||
failure = getattr(self, '_cad_close_error', None)
|
||||
cad.__exit__(type(failure) if failure is not None else None, failure, None)
|
||||
self.cad = None
|
||||
except Exception as error:
|
||||
if rebuilding:
|
||||
@@ -629,17 +812,33 @@ class BatchCadRuntime:
|
||||
'state', 'clean', 'cad_exit_code', 'quit_helper_exit_code', 'cleanup_errors',
|
||||
'shutdown_seconds', 'orderly_shutdown', 'diagnostic_errors', 'forced_termination',
|
||||
'forced_root_termination', 'forced_descendant_pids', 'termination_reason',
|
||||
'dialog_supervision', 'read_only_released') if key in cad_record}
|
||||
'dialog_supervision', 'read_only_released', 'cleanup_mode', 'release_state',
|
||||
'project_close_policy', 'owned_project', 'rollback_guaranteed',
|
||||
'changes_may_be_persisted') if key in cad_record}
|
||||
phases['mentor'] = 'failed' if retained_cad else 'released'
|
||||
if self.desktop is not None and not retained_cad:
|
||||
phases['desktop'] = 'closing'
|
||||
try:
|
||||
self.desktop.close()
|
||||
except Exception as error:
|
||||
errors.append(str(error))
|
||||
self._timing('batch_release', started)
|
||||
self.record['cleanup'] = getattr(self.desktop, 'cleanup_record', None)
|
||||
cleanup = self.record['cleanup'] or {}
|
||||
self.record['release_results'] = {
|
||||
'mentor_released': not retained_cad,
|
||||
'desktop_released': cleanup.get('desktop_handle_closed') is True
|
||||
and cleanup.get('desktop_confirmation', {}).get('released') is True}
|
||||
phases['desktop'] = ('waiting_for_mentor' if retained_cad else
|
||||
'released' if self.record['release_results']['desktop_released'] else 'failed')
|
||||
self.record['release_state'] = phases
|
||||
self.record['cleanup_mode'] = getattr(self.stop_event, 'cleanup_mode', None)
|
||||
if errors:
|
||||
self._save(state='blocked', error='; '.join(errors))
|
||||
raise BatchResourceCleanupError('; '.join(errors), completed_result=self.result)
|
||||
self._record_release()
|
||||
|
||||
def _record_release(self):
|
||||
released_at = time.time()
|
||||
release = {'generation': self.generation, 'desktop': self.record['desktop'],
|
||||
'cad_pid': self.record['cad_pid'], 'cad_guid': self.record['cad_guid'],
|
||||
|
||||
@@ -114,7 +114,7 @@ def _worker_context(root):
|
||||
_WORKER_ROOT = canonical_path(root)
|
||||
|
||||
|
||||
def _force_owned_supervisor(root, journal, process):
|
||||
def _force_owned_supervisor(root, journal, process, *, failure=None):
|
||||
"""Persist uncertainty before terminating the exact process/Job we own."""
|
||||
from .batch_resources import write_record
|
||||
from .read_recovery import process_tree_exited
|
||||
@@ -122,7 +122,10 @@ def _force_owned_supervisor(root, journal, process):
|
||||
if (journal.get('force_state') in {'termination_requested', 'confirmed'}
|
||||
and process_tree_exited(process)):
|
||||
return
|
||||
journal['stop_mode'] = 'forced'
|
||||
journal['stop_mode'] = 'mentor_release_required' if failure is not None else 'forced'
|
||||
if failure is not None:
|
||||
journal['cleanup_mode'] = 'mentor_release_required'
|
||||
journal['cleanup_reason'] = str(failure)
|
||||
journal.setdefault('force_requested_at', time.time())
|
||||
journal['force_state'] = 'requested'
|
||||
write_record(path, journal)
|
||||
@@ -130,7 +133,9 @@ def _force_owned_supervisor(root, journal, process):
|
||||
# Protect all possible targets before force; keep their saved results intact.
|
||||
journal['protect_all_targets'] = True
|
||||
try:
|
||||
_mark_interrupted(root, journal, '用户明确强制结束;写入与保存结果须核验,禁止自动重放。')
|
||||
_mark_interrupted(root, journal,
|
||||
'执行控制失败,自动释放本批资源;结果待核验:' + str(failure) if failure is not None else
|
||||
'用户明确强制结束;写入与保存结果须核验,禁止自动重放。')
|
||||
except Exception as error:
|
||||
journal.update(state='blocked', force_state='protection_failed', force_error=str(error))
|
||||
try:
|
||||
@@ -152,8 +157,20 @@ def _force_owned_supervisor(root, journal, process):
|
||||
|
||||
|
||||
def _retain_supervisor_after_control_error(root, journal, process, control, error):
|
||||
"""Do not turn a GUI/transport exception into an unconfirmed Job kill."""
|
||||
"""Protect failed work, then release the exact owned Job without replay."""
|
||||
from .batch_resources import write_record
|
||||
from .read_recovery import process_tree_exited
|
||||
if process.poll() is not None:
|
||||
# Job accounting can briefly outlive its exited root. Observe natural
|
||||
# exit before manufacturing uncertainty; the caller still validates
|
||||
# durable business evidence and protects missing/invalid results.
|
||||
from .isolated_desktop import DESCENDANT_EXIT_GRACE_SECONDS
|
||||
deadline = time.monotonic() + DESCENDANT_EXIT_GRACE_SECONDS
|
||||
while not process_tree_exited(process) and time.monotonic() < deadline:
|
||||
time.sleep(.01)
|
||||
if process_tree_exited(process):
|
||||
control.waiting_for_resolution = False
|
||||
return False
|
||||
control.set()
|
||||
control.waiting_for_resolution = True
|
||||
control.resolution_error = str(error)
|
||||
@@ -168,6 +185,17 @@ def _retain_supervisor_after_control_error(root, journal, process, control, erro
|
||||
{'version': VERSION, 'batch_id': journal['batch_id'], 'attempt_id': journal['attempt_id']})
|
||||
except OSError:
|
||||
pass # Keep ownership; failure to request stop is not permission to kill.
|
||||
try:
|
||||
if control.force_event.is_set():
|
||||
_force_owned_supervisor(root, journal, process)
|
||||
else:
|
||||
_force_owned_supervisor(root, journal, process, failure=error)
|
||||
control.cleanup_mode = 'mentor_release_required'
|
||||
control.cleanup_reason = str(error)
|
||||
control.waiting_for_resolution = False
|
||||
return True
|
||||
except Exception as failure:
|
||||
control.control_error = '失败收尾尚未完成,保留所有权等待重试:' + str(failure)
|
||||
last_notice = time.monotonic()
|
||||
while True:
|
||||
if time.monotonic() - last_notice >= 15:
|
||||
@@ -294,6 +322,9 @@ def reconcile_supervisors(root):
|
||||
continue
|
||||
path = Path(record.pop('record_path'))
|
||||
outcome = 'completed' if record.get('outcome') == 'completed_resources_pending' else 'interrupted'
|
||||
if outcome == 'interrupted':
|
||||
from .task_queue import reconcile_interrupted_queue
|
||||
reconcile_interrupted_queue(root, record)
|
||||
record.update(state='finished', reconciled=True, outcome=outcome, reconciled_at=time.time())
|
||||
write_record(path, record)
|
||||
return pending_supervisors(root)
|
||||
@@ -593,8 +624,11 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
except Exception as error:
|
||||
ownership_cleanup_error = error
|
||||
service._logging.logger.error('forced_stop_cleanup_pending batch_id=%s error=%s', batch_id, error)
|
||||
failure = TaskCenterError('user_forced_stop',
|
||||
automatic = journal.get('cleanup_mode') == 'mentor_release_required'
|
||||
failure = TaskCenterError('mentor_release_required' if automatic else 'user_forced_stop',
|
||||
'执行失败,已自动收尾本批后台进程;已有结果保留,当前结果待核验。' if automatic else
|
||||
'已按确认强制结束;已保存的执行证据保留,当前结果待核验。请先核验恢复,不要重复替换。')
|
||||
failure.resources_released = ownership_cleanup_error is None
|
||||
failure.primary_error = transport_error
|
||||
if ownership_cleanup_error is not None:
|
||||
journal.update(force_state='confirmation_failed', force_cleanup_error=str(ownership_cleanup_error))
|
||||
@@ -602,6 +636,8 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
journal.update(force_state='confirmed', force_confirmed_at=time.time())
|
||||
try:
|
||||
write_record(directory / 'supervisor.json', journal)
|
||||
if ownership_cleanup_error is None:
|
||||
reconcile_supervisors(root)
|
||||
except OSError as persistence_error:
|
||||
if ownership_cleanup_error is not None:
|
||||
combined = TaskCenterError('batch_resources_pending',
|
||||
|
||||
@@ -93,7 +93,7 @@ def _wait_for_owned_writes(runtime, control):
|
||||
from .isolated_cad import RETAINED_CAD_SESSIONS
|
||||
from .read_recovery import process_tree_exited
|
||||
from .worker_monitor import RETAINED_WORKERS, _worker_tree_exited, cleanup_retained_workers
|
||||
from .stop_control import wait_for_resolution
|
||||
from .stop_control import wait_for_resolution, MentorReleaseRequired
|
||||
def exited():
|
||||
if (runtime.record['state'] != 'released' and (runtime.desktop is not None or runtime.cad is not None)
|
||||
and not runtime.owned_processes_exited()):
|
||||
@@ -105,11 +105,14 @@ def _wait_for_owned_writes(runtime, control):
|
||||
return all(_worker_tree_exited(entry['process'], entry['owned'])
|
||||
for entry in tuple(RETAINED_WORKERS.values()) if entry['root'].is_relative_to(runtime.root))
|
||||
if not exited():
|
||||
wait_for_resolution(control, runtime.path.parent,
|
||||
'supervisor retains possible-write Jobs until all owned processes exit', resolved=exited)
|
||||
try:
|
||||
wait_for_resolution(control, runtime.path.parent,
|
||||
'supervisor exit still has owned write processes', resolved=exited, release_on_failure=True)
|
||||
except MentorReleaseRequired:
|
||||
cleanup_retained_workers(runtime.root, force=True)
|
||||
cleanup_retained_workers(runtime.root)
|
||||
if runtime.desktop is not None or runtime.cad is not None:
|
||||
runtime.close(reason='manual_retry')
|
||||
runtime.close(reason='resource_recheck')
|
||||
|
||||
|
||||
def run(request_path):
|
||||
|
||||
@@ -45,6 +45,7 @@ class BomImportReport:
|
||||
errors: tuple[str, ...] = ()
|
||||
source_map_path: Path | None = None
|
||||
passed_preview: BomBatchPreview | None = None
|
||||
deferred: bool = False
|
||||
|
||||
@property
|
||||
def total_rows(self):
|
||||
@@ -152,30 +153,12 @@ def bind_source_report(report, source_hashes, source_map_path):
|
||||
|
||||
|
||||
def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None, on_phase=None, runtime=None,
|
||||
allow_partial=False):
|
||||
allow_partial=False, spreadsheet_only=False, task_scope=False, force_inventory=False):
|
||||
"""Validate all independent rows; never persist inventory or return partial plans.
|
||||
|
||||
Operational failures (including cancellation and native cleanup) propagate so
|
||||
callers cannot accidentally continue opening CAD after an unsafe failure.
|
||||
Native read failures are reported per project. Explicit CAD runtimes retain
|
||||
their session cleanup gate; cancellation always propagates.
|
||||
"""
|
||||
if runtime is None:
|
||||
from .batch_runtime import BatchCadRuntime, BatchResourceCleanupError
|
||||
report = None
|
||||
try:
|
||||
with BatchCadRuntime(service._logging.root, 'bom_import', stop_event) as owned_runtime:
|
||||
try:
|
||||
report = inspect_batch(service, task_id, path, stop_event=stop_event,
|
||||
on_progress=on_progress, on_phase=on_phase, runtime=owned_runtime, allow_partial=allow_partial)
|
||||
except BomInspectionError as error:
|
||||
report = error.bom_report
|
||||
raise
|
||||
owned_runtime.result = report
|
||||
return report
|
||||
except BatchResourceCleanupError as error:
|
||||
error.bom_report = replace(report, preview=None, passed_preview=None) if report is not None else None
|
||||
if isinstance(error.completed_result, BomImportReport):
|
||||
error.completed_result = replace(error.completed_result, preview=None, passed_preview=None)
|
||||
raise
|
||||
def check_cancelled():
|
||||
if stop_event is not None and stop_event.is_set():
|
||||
raise TaskCenterError('operation_cancelled', 'BOM 导入已取消')
|
||||
@@ -188,8 +171,16 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
|
||||
|
||||
check_cancelled()
|
||||
notify('正在读取并校验 BOM Excel 表格…', BomImportPhase.READING)
|
||||
scope = _scope(service._store, task_id)
|
||||
runtime.bind_logs(service._logging, tuple(task.task_id for task, _ in scope))
|
||||
if task_scope:
|
||||
task = service._store.get_task(task_id)
|
||||
projects = service._store.list_projects(task_id)
|
||||
if len(projects) != 1:
|
||||
raise TaskCenterError('project_binding', 'BOM 核验需要当前任务绑定一个工程')
|
||||
scope = ((task, projects[0]),)
|
||||
else:
|
||||
scope = _scope(service._store, task_id)
|
||||
if runtime is not None:
|
||||
runtime.bind_logs(service._logging, tuple(task.task_id for task, _ in scope))
|
||||
routing = ProjectIdentityResolver()
|
||||
owners = {routing.project(project.path): (task, project) for task, project in scope}
|
||||
if len(owners) != len(scope):
|
||||
@@ -197,8 +188,10 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
|
||||
rows, records, grouped = [], {}, {}
|
||||
source_hash = hashlib.sha256(Path(path).read_bytes()).hexdigest() if Path(path).is_file() else ''
|
||||
workbook = None
|
||||
workbook_stream = None
|
||||
try:
|
||||
workbook = load_workbook(Path(path), read_only=True, data_only=False)
|
||||
workbook_stream = Path(path).open('rb')
|
||||
workbook = load_workbook(workbook_stream, read_only=True, data_only=False)
|
||||
sheet = workbook.active
|
||||
cells = iter(sheet.iter_rows())
|
||||
header = next(cells, ())
|
||||
@@ -265,6 +258,8 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
|
||||
finally:
|
||||
if workbook is not None:
|
||||
workbook.close()
|
||||
if workbook_stream is not None:
|
||||
workbook_stream.close()
|
||||
if not rows:
|
||||
return _report(rows, errors=('BOM 尚未填写替换行,请填写旧料号、新料号和位号',))
|
||||
# Do not start any reader until all spreadsheet/routing/editability checks pass.
|
||||
@@ -278,6 +273,10 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
|
||||
rows[index] = replace(rows[index], status='failed', reason=error.message)
|
||||
if any(row.status == 'failed' for row in rows) and not allow_partial:
|
||||
return _report(rows)
|
||||
if spreadsheet_only:
|
||||
failed_paths = {row.project_path for row in rows if row.status == 'failed'}
|
||||
eligible = any(row.project_path not in failed_paths for row in rows)
|
||||
return replace(_report(rows), deferred=eligible)
|
||||
notify(f'BOM 表格校验通过,共 {len(rows)} 行、涉及 {len(grouped)} 个工程;开始核验工程位号。')
|
||||
previews = []
|
||||
for position, (key, indices) in enumerate(grouped.items(), 1):
|
||||
@@ -312,7 +311,7 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
|
||||
(record.old.casefold(), record.new), '')
|
||||
missing_metadata |= ((mode == 'part_label' and row.target.actual_part_label is None)
|
||||
or (bool(cell) and row.target.actual_cell is None))
|
||||
if baseline and all(records[index].old.casefold() in known_parts or records[index].new.casefold() in known_parts
|
||||
if not force_inventory and baseline and all(records[index].old.casefold() in known_parts or records[index].new.casefold() in known_parts
|
||||
for index in indices) and not already_target_inventory:
|
||||
progress(f'「{task.name}」复用已有位号库存,无需启动 CAD')
|
||||
inventory = tuple(row.target for row in baseline)
|
||||
@@ -338,9 +337,9 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
|
||||
reason = f'工程采集失败:{error.message}(错误编号:{error.error_id})'
|
||||
for index in indices:
|
||||
rows[index] = replace(rows[index], status='failed', reason=reason)
|
||||
# Continue only with positive session-release evidence, not
|
||||
# merely a shared error code or an absent uncertainty marker.
|
||||
if isinstance(error, ReleasedProjectReadError):
|
||||
# Native reads own no CAD session; explicit legacy runtimes
|
||||
# still require positive session-release evidence.
|
||||
if task_scope or runtime is None or isinstance(error, ReleasedProjectReadError):
|
||||
progress(f'「{task.name}」采集失败,已记录;继续核验其他工程')
|
||||
continue
|
||||
for index, row in enumerate(rows):
|
||||
|
||||
@@ -21,6 +21,7 @@ class BomImportPhase(Enum):
|
||||
RELEASING = 'releasing'
|
||||
CANCELLING = 'cancelling'
|
||||
PREVIEW_READY = 'preview_ready'
|
||||
DEFERRED = 'deferred'
|
||||
REJECTED = 'rejected'
|
||||
CANCELLED = 'cancelled'
|
||||
FAILED = 'failed'
|
||||
@@ -82,13 +83,14 @@ class BomImportMachine:
|
||||
if not self._current(attempt) or not self.state.can_cancel:
|
||||
return False
|
||||
self.state = replace(self.state, phase=BomImportPhase.CANCELLING,
|
||||
message='正在取消;等待自有 CAD 会话安全释放…')
|
||||
message='正在取消;等待当前读取安全结束…')
|
||||
return True
|
||||
|
||||
def receive(self, attempt: int, report: BomImportReport) -> bool:
|
||||
if not self._current(attempt) or not self.state.can_cancel:
|
||||
return False
|
||||
phase = BomImportPhase.PREVIEW_READY if report.preview is not None else BomImportPhase.REJECTED
|
||||
phase = (BomImportPhase.DEFERRED if report.deferred else
|
||||
BomImportPhase.PREVIEW_READY if report.preview is not None else BomImportPhase.REJECTED)
|
||||
self.state = replace(self.state, phase=phase, message='', report=report)
|
||||
return True
|
||||
|
||||
@@ -107,7 +109,7 @@ class BomImportMachine:
|
||||
elif cancelled_error or self.state.phase is BomImportPhase.CANCELLING:
|
||||
self.state = replace(self.state, phase=BomImportPhase.CANCELLED, report=None,
|
||||
message='本次 BOM 导入已取消,原有预览和编辑保留。')
|
||||
elif self.state.phase not in (BomImportPhase.PREVIEW_READY, BomImportPhase.REJECTED):
|
||||
elif self.state.phase not in (BomImportPhase.PREVIEW_READY, BomImportPhase.DEFERRED, BomImportPhase.REJECTED):
|
||||
self.state = replace(self.state, phase=BomImportPhase.FAILED,
|
||||
message='本次 BOM 导入未返回校验结果,请重新导入。')
|
||||
self.state = replace(self.state, settled=True)
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Persist validated spreadsheet requests separately from real component identities."""
|
||||
from dataclasses import asdict, dataclass, replace
|
||||
import json
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from uuid import uuid4
|
||||
|
||||
from .bom_batch import _scope, _assert_editable
|
||||
from .bom_import_report import inspect_batch
|
||||
from .bom_plan import BomRecord, read_bom_records, write_bom_template
|
||||
from .errors import TaskCenterError
|
||||
from .operation_control import check_cancelled
|
||||
from .workspace_bom import load_sources, route_sources, write_routed_bom
|
||||
from .logging_setup import append_task_event
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PendingBomRequest:
|
||||
record: BomRecord
|
||||
source_file: str
|
||||
source_row: int
|
||||
source_sha256: str
|
||||
|
||||
@property
|
||||
def refs(self):
|
||||
return self.record.refs
|
||||
|
||||
|
||||
def retained_bom_rows(pending, existing_rows):
|
||||
"""Return enabled saved rows untouched by selectors in this project's BOM."""
|
||||
existing_rows = tuple(existing_rows)
|
||||
by_identity = {}
|
||||
for index, row in enumerate(existing_rows):
|
||||
target = row.target
|
||||
by_identity.setdefault((target.old_part_number.casefold(), target.refdes.casefold()), []).append(index)
|
||||
touched = set()
|
||||
for request in pending:
|
||||
record = request.record
|
||||
for ref in record.refs:
|
||||
candidates = tuple(index for identity in dict.fromkeys(((record.old.casefold(), ref.casefold()),
|
||||
(record.new.casefold(), ref.casefold()))) for index in by_identity.get(identity, ())
|
||||
if (not record.schematic or existing_rows[index].target.schematic_name.casefold() == record.schematic.casefold())
|
||||
and (not record.sheet or existing_rows[index].target.sheet_number.casefold() == record.sheet.casefold())
|
||||
and (not record.uid or existing_rows[index].target.uid == record.uid))
|
||||
if len(candidates) > 1:
|
||||
raise TaskCenterError('bom_scope_ambiguous', f'位号 {ref} 无法唯一匹配已保存位号;请填写原理图、图页或 UID:'
|
||||
f'{request.source_file} 第 {request.source_row} 行')
|
||||
touched.update(candidates)
|
||||
return tuple(row for index, row in enumerate(existing_rows) if row.enabled and index not in touched)
|
||||
|
||||
|
||||
def pending_requests(store, task_id):
|
||||
with store._lock:
|
||||
row = store._connection.execute('SELECT payload_json FROM pending_bom WHERE task_id=?', (task_id,)).fetchone()
|
||||
if row is None:
|
||||
return ()
|
||||
payload = json.loads(row['payload_json'])
|
||||
return tuple(PendingBomRequest(BomRecord(**dict(item['record'], refs=tuple(item['record']['refs']))),
|
||||
item['source_file'], item['source_row'], item['source_sha256']) for item in payload)
|
||||
|
||||
|
||||
def _template_record(record):
|
||||
return dict(project_path=record.project_path, old_part_number=record.old, new_part_number=record.new,
|
||||
refdes=','.join(record.refs), schematic_name=record.schematic, sheet_number=record.sheet, uid=record.uid,
|
||||
enabled=record.enabled, custom_value=record.custom, sync_nc=record.sync_nc, value_mode=record.value_mode)
|
||||
|
||||
|
||||
def resolution_binding(store, task_id):
|
||||
with store._lock:
|
||||
row = store._connection.execute('SELECT confirmed_hash, resolved_hash FROM bom_resolution WHERE task_id=?',
|
||||
(task_id,)).fetchone()
|
||||
return dict(row) if row is not None else None
|
||||
|
||||
|
||||
def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=None, on_phase=None, allow_partial=False):
|
||||
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress, allow_partial=allow_partial)
|
||||
scope = _scope(service._store, task_id)
|
||||
paths = tuple(project.path for _, project in scope)
|
||||
names = {project.path: task.name for task, project in scope}
|
||||
routes = route_sources(rows, paths, single=len(paths) == 1, project_names=names)
|
||||
unresolved = tuple(row for row in rows if routes.get(row.project_key) is None)
|
||||
if unresolved:
|
||||
locations = '; '.join(f'{row.source.name} 第 {row.excel_row} 行:{row.project_name or row.project_path}'
|
||||
for row in unresolved[:20])
|
||||
raise TaskCenterError('project_binding', f'无法唯一匹配 BOM 工程:{locations}')
|
||||
root = service._logging.root / 'tasks' / task_id / 'bom-imports' / uuid4().hex
|
||||
normalized = root / 'normalized-bom.xlsx'
|
||||
mapping = root / 'source-map.json'
|
||||
write_routed_bom(normalized, rows, routes, project_names=names)
|
||||
append_task_event(service._logging, level='INFO', task_id=task_id,
|
||||
operation='import_bom_drafts', message='BOM 表格来源记录已保存,工程位号待核验',
|
||||
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows})})
|
||||
try:
|
||||
report = inspect_batch(service, task_id, normalized, stop_event=stop_event, on_progress=on_progress,
|
||||
on_phase=on_phase, spreadsheet_only=True, allow_partial=allow_partial)
|
||||
finally:
|
||||
normalized.unlink(missing_ok=True)
|
||||
failed_paths = {result.project_path for result in report.rows if result.status == 'failed'}
|
||||
annotated = []
|
||||
for result, source in zip(report.rows, rows):
|
||||
reason = result.reason
|
||||
if result.duplicate_rows:
|
||||
locations = (f'{rows[number - 2].source.name} 第 {rows[number - 2].excel_row} 行'
|
||||
for number in result.duplicate_rows)
|
||||
reason = '位号在 BOM 中重复(' + ';'.join(locations) + ')'
|
||||
if report.deferred and result.project_path not in failed_paths:
|
||||
reason = '表格已保存,执行前核验工程位号'
|
||||
annotated.append(replace(result, source_file=str(source.source), source_row=source.excel_row, reason=reason))
|
||||
report = replace(report, rows=tuple(annotated), source_map_path=mapping)
|
||||
if report.deferred:
|
||||
accepted_sources = tuple(source for result, source in zip(report.rows, rows)
|
||||
if result.project_path not in failed_paths)
|
||||
with TemporaryDirectory(prefix='dx-bom-validate-') as directory:
|
||||
accepted = write_routed_bom(Path(directory) / 'accepted.xlsx', accepted_sources, routes, project_names=names)
|
||||
records = read_bom_records(accepted)
|
||||
by_path = {str(project.path.resolve()).casefold(): task.task_id for task, project in scope}
|
||||
grouped = {}
|
||||
for record, source in zip(records, accepted_sources):
|
||||
owner = by_path[str(Path(record.project_path).resolve()).casefold()]
|
||||
grouped.setdefault(owner, []).append(PendingBomRequest(record, str(source.source),
|
||||
source.excel_row, source.source_sha256))
|
||||
check_cancelled(stop_event)
|
||||
with service._store.transaction():
|
||||
for owner, payload in grouped.items():
|
||||
_assert_editable(service, owner)
|
||||
retained_bom_rows(payload, service._store.list_target_plan(owner))
|
||||
service._store._connection.execute('INSERT OR REPLACE INTO pending_bom VALUES (?, ?)',
|
||||
(owner, json.dumps([asdict(item) for item in payload], ensure_ascii=False)))
|
||||
service._store._connection.execute('DELETE FROM bom_resolution WHERE task_id=?', (owner,))
|
||||
return report
|
||||
|
||||
|
||||
def resolve_pending(service, task_id, *, stop_event=None, on_progress=None, runtime=None):
|
||||
pending = pending_requests(service._store, task_id)
|
||||
if not pending:
|
||||
return service._store.list_target_plan(task_id)
|
||||
check_cancelled(stop_event)
|
||||
with TemporaryDirectory(prefix='dx-bom-resolve-') as directory:
|
||||
path = write_bom_template(Path(directory) / 'bom.xlsx', tuple(_template_record(item.record) for item in pending))
|
||||
report = inspect_batch(service, task_id, path, stop_event=stop_event, on_progress=on_progress,
|
||||
runtime=runtime, task_scope=True, force_inventory=True)
|
||||
report = replace(report, rows=tuple(replace(row, source_file=request.source_file,
|
||||
source_row=request.source_row,
|
||||
reason=row.reason + f';来源:{request.source_file} 第 {request.source_row} 行')
|
||||
for row, request in zip(report.rows, pending)))
|
||||
if report.preview is None:
|
||||
message = '\n'.join((*report.errors, *(row.reason for row in report.rows if row.status == 'failed')))
|
||||
error = TaskCenterError('bom_resolution', message or 'BOM 工程位号核验未通过,待核验清单已保留')
|
||||
error.bom_report = report
|
||||
raise error
|
||||
project = report.preview.projects[0]
|
||||
check_cancelled(stop_event)
|
||||
with service._store.transaction():
|
||||
if pending_requests(service._store, task_id) != pending:
|
||||
raise TaskCenterError('assistant_stale', '待核验 BOM 已变化,请重新确认执行')
|
||||
_assert_editable(service, task_id)
|
||||
if tuple(service._store.list_target_plan(task_id)) != project.baseline:
|
||||
raise TaskCenterError('target_identity', 'BOM 核验期间位号计划已变化')
|
||||
from .task_queue import _plan_hash
|
||||
child = service.for_project_task(task_id)
|
||||
confirmed_hash = _plan_hash(child, task_id, resolve_alias=False)
|
||||
service._store.record_target_inventory(task_id, project.inventory)
|
||||
result = service._store.replace_target_plan(task_id, project.rows)
|
||||
service._store._connection.execute('DELETE FROM pending_bom WHERE task_id=?', (task_id,))
|
||||
resolved_hash = _plan_hash(child, task_id, resolve_alias=False)
|
||||
service._store._connection.execute('INSERT OR REPLACE INTO bom_resolution VALUES (?, ?, ?)',
|
||||
(task_id, confirmed_hash, resolved_hash))
|
||||
return result
|
||||
@@ -228,7 +228,7 @@ class BomMatcher:
|
||||
mode = self.default_value_mode if record.value_mode == 'inherit' else record.value_mode
|
||||
expected = {'preserve': current.old_value, 'custom': record.custom, 'part_number': current.old_part_number,
|
||||
'part_label': current.actual_part_label}.get(mode)
|
||||
has_nc = lambda value: any(part.strip().casefold() == 'nc' for part in value.split('/')[1:])
|
||||
has_nc = lambda value: '/' in value and any(part.strip().casefold() == 'nc' for part in value.split('/'))
|
||||
if expected is not None and record.sync_nc and has_nc(current.old_value) and not has_nc(expected):
|
||||
expected = expected.rstrip() + ('NC' if expected.rstrip().endswith('/') else '/NC')
|
||||
if expected is None or (mode == 'part_label' and not expected) or current.old_value != expected:
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from threading import RLock
|
||||
|
||||
@@ -91,8 +92,9 @@ def _script_error(row):
|
||||
title = row['title'].strip().casefold()
|
||||
body = row['text'].casefold()
|
||||
buttons = row['buttons']
|
||||
diagnostic = re.search(r"(?ms)^source:.*?^line:\s*\d+\s+char:\s*\d+\s*\nerror:\s*0x800a[0-9a-f]{4}\b", body)
|
||||
return (row.get('complete') is True and title in {'script error', 'microsoft vbscript', 'dxdesigner', '脚本错误'}
|
||||
and any(marker in body for marker in ('microsoft vbscript compilation error', 'microsoft vbscript 编译器错误'))
|
||||
and (diagnostic or any(marker in body for marker in ('microsoft vbscript compilation error', 'microsoft vbscript 编译器错误')))
|
||||
and len(buttons) == 1 and buttons[0]['id'] in {1, 2} and buttons[0]['enabled']
|
||||
and buttons[0]['text'].replace('&', '').strip().casefold() in {'ok', '确定', '确定(o)'})
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
@@ -248,6 +249,9 @@ def read_library_cell_catalog(library_path: Path, part_number: str, evidence_roo
|
||||
_dispose_clone(root)
|
||||
else:
|
||||
raise TaskCenterError('batch_resources_pending', 'catalog reader cleanup/release evidence is missing') from error
|
||||
if isinstance(error, subprocess.TimeoutExpired):
|
||||
raise TaskCenterError('cell_catalog',
|
||||
f'目标库读取超时({error.timeout} 秒),已确认读取进程释放,未执行器件替换;诊断:{root}') from error
|
||||
raise
|
||||
|
||||
|
||||
@@ -282,16 +286,15 @@ def read_project_cell_choices(project_paths: tuple[Path, ...], part_number: str,
|
||||
|
||||
|
||||
def preflight_target_libraries(project_paths, rules, evidence_root, *, allow_cold_read=True):
|
||||
"""Prove each requested target PN and Cell using the isolated readonly reader.
|
||||
|
||||
An empty Cell choice still requires an authoritative associated cell list;
|
||||
missing parts and ambiguous partitions are rejected by the reader itself.
|
||||
"""
|
||||
"""Validate explicit Cell choices; native replacement validates the target part."""
|
||||
projects = tuple(project_paths)
|
||||
if not projects:
|
||||
_fail('no project libraries are available for target preflight')
|
||||
requests = tuple(dict.fromkeys((rule.new_part_number, getattr(rule, 'target_cell', ''))
|
||||
for rule in rules if getattr(rule, 'enabled', True)))
|
||||
for rule in rules if getattr(rule, 'enabled', True)
|
||||
and getattr(rule, 'target_cell', '')))
|
||||
if not requests:
|
||||
return ()
|
||||
proof = []
|
||||
for library in dict.fromkeys(project_library_path(project) for project in projects):
|
||||
for part, cell in requests:
|
||||
@@ -304,7 +307,7 @@ def preflight_target_libraries(project_paths, rules, evidence_root, *, allow_col
|
||||
|
||||
|
||||
def preflight_command_target(command, evidence_root, *, allow_cold_read=True):
|
||||
"""Execution adapter for one frozen command, before journal claim or CAD writes."""
|
||||
"""Validate a frozen command's explicit Cell before dispatching CAD writes."""
|
||||
from types import SimpleNamespace
|
||||
try:
|
||||
return preflight_target_libraries((Path(command['project_path']),),
|
||||
|
||||
@@ -63,8 +63,16 @@ def _targets(command):
|
||||
def read_command_rows(path):
|
||||
from .quick_run import _decode_vbs_field
|
||||
with internal_path(path).open(encoding='utf-8-sig',newline='') as stream:
|
||||
return tuple({key:_decode_vbs_field(value) for key,value in row.items()}
|
||||
for row in csv.DictReader(stream,delimiter='\t'))
|
||||
reader = csv.DictReader(stream, delimiter='\t')
|
||||
required = {'task_id', 'job_id', 'project_path', 'old_part', 'new_part'}
|
||||
if not required <= set(reader.fieldnames or ()):
|
||||
raise TaskCenterError('quick_run_command', 'quick-run command is malformed')
|
||||
rows = []
|
||||
for row in reader:
|
||||
if None in row or any(value is None for value in row.values()):
|
||||
raise TaskCenterError('quick_run_command', 'quick-run command is malformed')
|
||||
rows.append({key: _decode_vbs_field(value) for key, value in row.items()})
|
||||
return tuple(rows)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -118,6 +126,15 @@ class ExecutionJournal:
|
||||
if not set(selected)<=valid:raise TaskCenterError('problem_retry_scope','重试范围不属于原失败项。')
|
||||
self.store._connection.execute('INSERT INTO execution_retry_selections VALUES (?,?,?)',(task_id,current['round_id'],_json(selected)))
|
||||
self.store._connection.execute('UPDATE execution_rounds SET retry_authorized=1 WHERE task_id=?',(task_id,))
|
||||
# Explicit preparation also spends the original target's automatic allowance.
|
||||
rows = self.store._connection.execute('''SELECT operation_key FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND state='failed' ''', (task_id,current['round_id']))
|
||||
for row in rows:
|
||||
if operation_keys is None or row[0] in operation_keys:
|
||||
self.store._connection.execute('''UPDATE execution_problems
|
||||
SET auto_retries=1,reservation_source=COALESCE(reservation_source,'manual')
|
||||
WHERE task_id=? AND round_id=? AND operation_key=? AND auto_retries=0''',
|
||||
(task_id,current['round_id'],row[0]))
|
||||
|
||||
def has_pending_components(self,task_id):
|
||||
with self.store._lock:
|
||||
@@ -203,14 +220,27 @@ class ExecutionJournal:
|
||||
if receipt.get('job_id') != row['job_id']:
|
||||
raise TaskCenterError('quick_run_uncertain', '健康证明任务与原失败回执不一致。')
|
||||
attempt = JournalAttempt(task_id, current['round_id'], key, record['attempt_id'], record['generation'])
|
||||
proof = receipt.get('proof', {})
|
||||
baselines = self.expected_baselines(task_id, row['project_path'])
|
||||
if proof.get('baseline') and proof.get('files'):
|
||||
baselines = (*baselines, dict(proof['baseline'], files=list(proof['files'])))
|
||||
bound = native_completion(Path(self.store.path).parent / 'task-evidence' / task_id,
|
||||
row, attempt, health, self.expected_baselines(task_id, row['project_path']),
|
||||
receipt.get('proof', {}).get('native_dispatch', {}))
|
||||
row, attempt, health, baselines, proof.get('native_dispatch', {}))
|
||||
proof = receipt.setdefault('proof', {'files': []})
|
||||
proof['failure_health'] = bound
|
||||
proof.setdefault('files', []).extend(bound['files'])
|
||||
self.store._connection.execute('''UPDATE execution_operations SET receipt_json=?
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''', (_json(receipt), task_id, current['round_id'], key))
|
||||
baseline = bound.get('verified_baseline')
|
||||
if baseline is not None:
|
||||
self.store._connection.execute('''INSERT INTO execution_baselines VALUES (?,?,?,?,?,?)
|
||||
ON CONFLICT(task_id,round_id,project_path,schematic_name,sheet_number)
|
||||
DO UPDATE SET baseline_json=excluded.baseline_json''',
|
||||
(task_id, current['round_id'], command_identity(row)['project_path'],
|
||||
baseline['schematic_name'], baseline['sheet_number'], _json(baseline)))
|
||||
from .execution_problems import ExecutionProblems
|
||||
ExecutionProblems(self.store).record(attempt, json.loads(record['command_json']), 'failed',
|
||||
receipt['code'], receipt['message'], certified=self.failure_certified(task_id, row))
|
||||
|
||||
def failure_certified(self, task_id, row):
|
||||
from .project_session_health import affirmative
|
||||
@@ -239,6 +269,141 @@ class ExecutionJournal:
|
||||
with self.store.transaction():
|
||||
self.store._connection.execute('UPDATE execution_rounds SET pause_requested=1 WHERE task_id=?',(task_id,))
|
||||
|
||||
def pause_before_dispatch(self, attempt, row, proof):
|
||||
"""Return only this certified unstarted claim to the original pending plan."""
|
||||
from .execution_proof import proof_intact
|
||||
from .batch_attempt import can_retry_attempt
|
||||
from .project_session_health import _source_digest
|
||||
if proof.get('phase') == 'before_worker_launch':
|
||||
from .project_session_health import _intact_certificate
|
||||
if not _intact_certificate(proof):
|
||||
raise TaskCenterError('quick_run_uncertain', '启动前暂停证书与当前回执不符。')
|
||||
if (proof.get('task_id') != attempt.task_id or proof.get('job_id') != attempt.job_id
|
||||
or canonical_path(proof.get('project_path', '')) != canonical_path(row['project_path'])
|
||||
or proof.get('native_dispatch_not_started') is not True or proof.get('project_closed') is not True
|
||||
or proof.get('worker_tree_exited') is not True or not proof.get('files') or not proof_intact(proof)
|
||||
or proof.get('phase') == 'before_worker_launch' and (
|
||||
proof.get('worker_launch_attempted') is not False or proof.get('resources_released') is not True)
|
||||
or _source_digest(proof) != proof.get('source_sha256') or not proof.get('source_sha256')
|
||||
or not proof.get('batch_attempts') or not all(can_retry_attempt(item['path'], item['expected'])
|
||||
for item in proof['batch_attempts'])):
|
||||
raise TaskCenterError('quick_run_uncertain', '暂停缺少完整的未派发与关闭证明。')
|
||||
with self.store.transaction():
|
||||
current = self._round(attempt.task_id)
|
||||
record = self.store._connection.execute('''SELECT * FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''',
|
||||
(attempt.task_id, attempt.round_id, attempt.operation_key)).fetchone()
|
||||
if (not current or current['round_id'] != attempt.round_id or record is None
|
||||
or record['state'] != 'prepared' or record['attempt_id'] != attempt.attempt_id
|
||||
or record['generation'] != attempt.generation or _hash(command_identity(row)) != attempt.operation_key):
|
||||
raise TaskCenterError('quick_run_uncertain', '暂停回执不属于当前执行声明。')
|
||||
self.store._connection.execute('''UPDATE execution_operations SET state='pending',attempt_id=NULL,generation=?,receipt_json=?
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''',
|
||||
(attempt.generation - 1, _json({'startup_pause': dict(proof, journal_round_id=attempt.round_id,
|
||||
journal_operation_key=attempt.operation_key, journal_generation=attempt.generation,
|
||||
journal_attempt_id=attempt.attempt_id)}), attempt.task_id, attempt.round_id, attempt.operation_key))
|
||||
self.store._connection.execute('UPDATE execution_rounds SET pause_requested=1 WHERE task_id=?', (attempt.task_id,))
|
||||
task = self.store.get_task(attempt.task_id)
|
||||
HistoryRepository(self.store).append(task_id=attempt.task_id, task_name=task.name,
|
||||
project_path=row['project_path'], operation='quick_run_paused', state='paused',
|
||||
summary='启动阶段已确认未派发原生替换;保留原队列待执行项。', details={'proof': proof},
|
||||
source_key=f'pause:{attempt.task_id}:{attempt.round_id}:{attempt.operation_key}:{attempt.attempt_id}')
|
||||
|
||||
def certified_startup_pause(self, task_id, operation_record):
|
||||
"""Read-only validation of a retired claim; marker existence is irrelevant."""
|
||||
from .execution_proof import proof_intact
|
||||
from .project_session_health import _source_digest
|
||||
from .batch_attempt import can_retry_attempt
|
||||
try:
|
||||
record = dict(operation_record)
|
||||
proof = json.loads(record.get('receipt_json') or '{}').get('startup_pause', {})
|
||||
command = json.loads(record['command_json'])
|
||||
original = json.loads(internal_path(proof['files'][0]['path']).read_text(encoding='utf-8'))
|
||||
with self.store._lock:
|
||||
current = self._round(task_id)
|
||||
live = self.store._connection.execute('''SELECT * FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''',
|
||||
(task_id, record['round_id'], record['operation_key'])).fetchone()
|
||||
return bool(current and current['round_id'] == record['round_id'] and live and dict(live) == record
|
||||
and record['task_id'] == task_id and record['state'] == 'pending' and record['attempt_id'] is None
|
||||
and proof.get('task_id') == task_id and proof.get('job_id')
|
||||
and proof.get('journal_round_id') == record['round_id']
|
||||
and proof.get('journal_operation_key') == record['operation_key']
|
||||
and proof.get('journal_generation') == record['generation'] + 1 and proof.get('journal_attempt_id')
|
||||
and all(proof.get(key) == value for key, value in original.items())
|
||||
and _hash(command) == record['operation_key']
|
||||
and canonical_path(proof.get('project_path', '')) == canonical_path(command['project_path'])
|
||||
and proof.get('native_dispatch_not_started') is True and proof.get('project_closed') is True
|
||||
and proof.get('worker_tree_exited') is True and proof.get('files') and proof_intact(proof)
|
||||
and (proof.get('phase') != 'before_worker_launch' or (
|
||||
proof.get('worker_launch_attempted') is False and proof.get('resources_released') is True))
|
||||
and proof.get('source_sha256') and _source_digest(proof) == proof['source_sha256']
|
||||
and proof.get('batch_attempts') and all(can_retry_attempt(item['path'], item['expected'])
|
||||
for item in proof['batch_attempts']))
|
||||
except (AttributeError, IndexError, KeyError, TypeError, ValueError, OSError):
|
||||
return False
|
||||
|
||||
def pending_pauses_intact(self, task_id):
|
||||
"""Explicit resume admission rechecks retired claims without polling CAD."""
|
||||
with self.store._lock:
|
||||
current = self._round(task_id)
|
||||
rows = tuple(self.store._connection.execute('''SELECT * FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND state='pending' AND receipt_json IS NOT NULL''',
|
||||
(task_id, current['round_id']))) if current else ()
|
||||
return all(self._pending_pause_intact(task_id, row) for row in rows)
|
||||
|
||||
def _pending_pause_intact(self, task_id, record):
|
||||
try:
|
||||
receipt = json.loads(record['receipt_json'] or '{}')
|
||||
return 'startup_pause' not in receipt or self.certified_startup_pause(task_id, record)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
def finalize_startup_pause(self, task_id, root):
|
||||
"""Retire only the exact marker of a durably committed no-dispatch pause."""
|
||||
from .execution_proof import proof_intact
|
||||
from .project_session_health import _source_digest
|
||||
from .batch_attempt import can_retry_attempt
|
||||
from .path_access import retry_sharing_violation
|
||||
marker = internal_path(root / 'current-command.tsv')
|
||||
if not marker.is_file():
|
||||
return
|
||||
rows = read_command_rows(root / 'current-command.tsv')
|
||||
if len(rows) != 1 or rows[0]['task_id'] != task_id:
|
||||
return
|
||||
row = rows[0]
|
||||
with self.store._lock:
|
||||
current = self._round(task_id)
|
||||
if not current:
|
||||
return
|
||||
record = self.store._connection.execute(
|
||||
'SELECT * FROM execution_operations WHERE task_id=? AND round_id=? AND operation_key=?',
|
||||
(task_id, current['round_id'], _hash(command_identity(row)))).fetchone()
|
||||
if record is None or not self.certified_startup_pause(task_id, record):
|
||||
return
|
||||
proof = json.loads(record['receipt_json'] or '{}').get('startup_pause', {})
|
||||
if (proof.get('task_id') != task_id or proof.get('job_id') != row['job_id']
|
||||
or proof.get('native_dispatch_not_started') is not True
|
||||
or proof.get('project_closed') is not True or proof.get('worker_tree_exited') is not True
|
||||
or not proof.get('files') or not proof_intact(proof)
|
||||
or _source_digest(proof) != proof.get('source_sha256')
|
||||
or hashlib.sha256(marker.read_bytes()).hexdigest() != proof.get('current_command_sha256')
|
||||
or hashlib.sha256(internal_path(root / 'status.tsv').read_bytes()).hexdigest() != proof.get('status_sha256')
|
||||
# Scope cleanup removes this request after the durable pause;
|
||||
# a surviving request must still match the certified one.
|
||||
or internal_path(root / 'project-session.request').exists() and hashlib.sha256(
|
||||
internal_path(root / 'project-session.request').read_bytes()).hexdigest() != proof.get('request_sha256')
|
||||
or not proof.get('batch_attempts') or not all(can_retry_attempt(item['path'], item['expected'])
|
||||
for item in proof['batch_attempts'])):
|
||||
return
|
||||
try:
|
||||
retry_sharing_violation(lambda: marker.unlink())
|
||||
except OSError:
|
||||
# Certification remains durable while the exact ephemeral
|
||||
# marker is locked. Snapshot retries retirement next time.
|
||||
pass
|
||||
return proof['current_command_sha256'] if marker.is_file() else None
|
||||
|
||||
def requires_retry(self,task_id):
|
||||
with self.store._lock:
|
||||
current=self._round(task_id)
|
||||
@@ -362,6 +527,8 @@ class ExecutionJournal:
|
||||
and not self.can_continue_component(task_id,command_identity(row))):
|
||||
raise TaskCenterError('quick_run_retry_required','本工程有失败项,请准备失败项重试;不会重新执行成功项。')
|
||||
if record['state']!='pending':raise TaskCenterError('quick_run_uncertain','上次尝试尚未核验,禁止再次派发。')
|
||||
if not self._pending_pause_intact(task_id, record):
|
||||
raise TaskCenterError('quick_run_uncertain', '原暂停的未派发证明缺失或变化,禁止再次派发。')
|
||||
if not importing and row.get('execution_unit')=='component' and not self.can_continue_component(task_id,command_identity(row)):
|
||||
raise TaskCenterError('quick_run_uncertain','工程有未决尝试或健康证明不足,暂缓独立位号。')
|
||||
identifier=uuid4().hex;generation=record['generation']+1
|
||||
@@ -423,7 +590,9 @@ class ExecutionJournal:
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''',
|
||||
(state,_json(receipt),attempt.task_id,attempt.round_id,attempt.operation_key))
|
||||
from .execution_problems import ExecutionProblems
|
||||
ExecutionProblems(self.store).record(attempt,command,state,code,message)
|
||||
failure_row = dict(command, task_id=attempt.task_id, job_id=receipt.get('job_id'))
|
||||
ExecutionProblems(self.store).record(attempt,command,state,code,message,
|
||||
certified=state == 'failed' and self.failure_certified(attempt.task_id, failure_row))
|
||||
if state in _SUCCESS:
|
||||
if proof and proof.get('baseline'):
|
||||
baseline=dict(proof['baseline'])
|
||||
|
||||
@@ -5,8 +5,37 @@ import json
|
||||
from .errors import TaskCenterError
|
||||
|
||||
|
||||
RULE_VERSION = 'safe-prewrite-v1'
|
||||
RETRYABLE_CODES = frozenset({'cad_attachment_failed', 'worker_timeout_before_write'})
|
||||
RULE_VERSION = 'evidence-prewrite-v2'
|
||||
# Error codes describe causes, never establish absence of a write.
|
||||
TRANSIENT_CODES = frozenset({'cad_attachment_failed', 'worker_timeout_before_write',
|
||||
'worker_error', 'worker_timeout', 'timeout', 'quick_run_failed', 'execution_failed', 'native_failed'})
|
||||
DETERMINISTIC_CODES = frozenset({'target_identity', 'probe_baseline_missing', 'task_not_retryable',
|
||||
'assistant_stale', 'target_cell', 'invalid_target', 'target_not_found'})
|
||||
|
||||
|
||||
def classify_execution_failure(code, state, *, certified=False, phase='unknown',
|
||||
interrupted=False, authorized=False):
|
||||
"""One policy; certified means identity-bound, intact no-write/release evidence."""
|
||||
code, state = str(code or '').casefold(), str(state or '').casefold()
|
||||
if interrupted or state in {'uncertain', 'saved_unverified', 'prepared', 'batch_saved_unverified'} or (
|
||||
phase in {'may_write', 'saved'} and not certified):
|
||||
category = 'uncertain'
|
||||
elif state == 'paused' or code in {'paused', 'user_pause'}:
|
||||
category = 'paused'
|
||||
elif state in {'verified', 'saved_ok', 'restored', 'no_match'}:
|
||||
category = 'resolved'
|
||||
elif code in DETERMINISTIC_CODES:
|
||||
category = 'deterministic'
|
||||
elif certified and code in TRANSIENT_CODES:
|
||||
category = 'transient'
|
||||
else:
|
||||
category = 'observe'
|
||||
allowed = category == 'transient' and authorized
|
||||
return dict(category=category, retry_allowed=allowed, phase=phase,
|
||||
continue_allowed=bool((certified or phase in {'read', 'not_dispatched'})
|
||||
and category not in {'uncertain', 'paused', 'resolved'}),
|
||||
reason='Identity-bound no-write and resource-release evidence required; input errors need correction.',
|
||||
backoff_seconds=0, max_attempts=int(allowed))
|
||||
|
||||
|
||||
def create_problem_schema(connection):
|
||||
@@ -37,15 +66,33 @@ class ExecutionProblems:
|
||||
def __init__(self, store):
|
||||
self.store = store
|
||||
|
||||
def record(self, attempt, command, state, code, message):
|
||||
def certified_failures(self, task_id):
|
||||
"""Read current receipts again; a stored classification is not live proof."""
|
||||
from .execution_journal import ExecutionJournal
|
||||
with self.store._lock:
|
||||
current = self.store._connection.execute(
|
||||
'SELECT round_id FROM execution_rounds WHERE task_id=?', (task_id,)).fetchone()
|
||||
if current is None:
|
||||
return False
|
||||
rows = self.store._connection.execute('''SELECT command_json,state,receipt_json
|
||||
FROM execution_operations WHERE task_id=? AND round_id=?''', (task_id,current[0])).fetchall()
|
||||
failed = [row for row in rows if row['state'] == 'failed']
|
||||
if not failed or any(row['state'] in {'prepared', 'uncertain'} for row in rows):
|
||||
return False
|
||||
journal = ExecutionJournal(self.store)
|
||||
return all(journal.failure_certified(task_id, dict(json.loads(row['command_json']),
|
||||
task_id=task_id, job_id=json.loads(row['receipt_json']).get('job_id'))) for row in failed)
|
||||
|
||||
def record(self, attempt, command, state, code, message, *, certified=False):
|
||||
key = problem_key(command)
|
||||
if state in {'verified', 'restored', 'no_match'}:
|
||||
self.store._connection.execute('''UPDATE execution_problems SET state='resolved'
|
||||
WHERE task_id=? AND round_id=? AND problem_key=?''',
|
||||
(attempt.task_id, attempt.round_id, key))
|
||||
return
|
||||
category = ('uncertain' if state == 'uncertain' else
|
||||
'retryable' if code in RETRYABLE_CODES else 'manual')
|
||||
policy = classify_execution_failure(code, state, certified=certified, authorized=True)
|
||||
category = ('uncertain' if policy['category'] == 'uncertain' else
|
||||
'retryable' if policy['retry_allowed'] else 'manual')
|
||||
self.store._connection.execute('''INSERT INTO execution_problems
|
||||
(task_id,round_id,problem_key,operation_key,classification,state,code,message,rule_version)
|
||||
VALUES (?,?,?,?,?,'open',?,?,?)
|
||||
@@ -134,10 +181,19 @@ class ExecutionProblems:
|
||||
AND p.state='open' AND p.auto_retries=0 AND o.state='failed' ORDER BY p.rowid''', (task_id, round_id)).fetchall()
|
||||
keys = []
|
||||
for row in rows:
|
||||
if json.loads(row['command_json']).get('execution_unit') != 'component':
|
||||
command = json.loads(row['command_json'])
|
||||
if command.get('execution_unit') != 'component' and (source != 'dsh'
|
||||
or command.get('target_scope', 'all') != 'all' or command.get('target_selectors')):
|
||||
continue
|
||||
if requested is not None and row['operation_key'] not in requested:
|
||||
continue
|
||||
from .execution_journal import ExecutionJournal
|
||||
receipt = self.store._connection.execute('''SELECT receipt_json FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''',
|
||||
(task_id, round_id, row['operation_key'])).fetchone()
|
||||
command.update(task_id=task_id, job_id=json.loads(receipt[0]).get('job_id'))
|
||||
if not ExecutionJournal(self.store).failure_certified(task_id, command):
|
||||
continue
|
||||
self.store._connection.execute('''UPDATE execution_problems SET auto_retries=1,
|
||||
reservation_source=? WHERE task_id=? AND round_id=? AND problem_key=? AND auto_retries=0''',
|
||||
(source, task_id, round_id, row['problem_key']))
|
||||
|
||||
@@ -104,7 +104,6 @@ def capture_result(data_root,root,row,outcome,*,strict=False,persist=True):
|
||||
def capture_recovery(data_root,audit,row,outcome,*,strict=False):
|
||||
"""The recovery audit proves readback; it never asserts a second replacement."""
|
||||
worker=audit/'worker'
|
||||
proof=capture_result(data_root,worker,row,('recovery_readback','',outcome[2]),strict=strict)
|
||||
try:
|
||||
record=json.loads((audit/'recovery.json').read_text(encoding='utf8'))
|
||||
snapshot=audit/'evidence-before'/f'snapshot-{row["job_id"]}.tsv'
|
||||
@@ -113,14 +112,75 @@ def capture_recovery(data_root,audit,row,outcome,*,strict=False):
|
||||
record['native_replacement_called'] is not False or
|
||||
hashlib.sha256(snapshot.read_bytes()).hexdigest()!=record['snapshot_sha256']):
|
||||
raise ValueError('recovery proof differs from original operation')
|
||||
mode=record.get('mode','native_transaction')
|
||||
if mode not in {'source_only','native_transaction'}:
|
||||
raise ValueError('unknown recovery mode')
|
||||
sources=[(audit/'recovery.json','recovery.json'),(snapshot,snapshot.name),
|
||||
(worker/'status.tsv','status.tsv')]
|
||||
if mode=='source_only':
|
||||
_require_source_recovery(audit,row,record,outcome,snapshot)
|
||||
sources.extend(((audit/'evidence-before'/'command.tsv','original/command.tsv'),
|
||||
(worker/'command.tsv','worker/command.tsv'),
|
||||
(worker/snapshot.name,'worker/'+snapshot.name)))
|
||||
else:
|
||||
sources.append((Path(str(snapshot)+'.native.json'),snapshot.name+'.native.json'))
|
||||
proof=capture_result(data_root,worker,row,('recovery_readback','',outcome[2]),strict=strict)
|
||||
if mode=='source_only' and 'baseline' in proof:
|
||||
from .native_helper import read_snapshot
|
||||
metadata,_=read_snapshot(snapshot)
|
||||
if metadata[4]!=proof['baseline']['schematic_name']+':'+proof['baseline']['sheet_number']:
|
||||
raise ValueError('source readback sheet differs from snapshot')
|
||||
destination=internal_path(data_root/'execution-proof'/uuid4().hex)
|
||||
destination.mkdir(parents=True,exist_ok=False)
|
||||
for path in (audit/'recovery.json',snapshot,Path(str(snapshot)+'.native.json'),worker/'status.tsv'):
|
||||
data=path.read_bytes();target=destination/path.name
|
||||
for path,name in sources:
|
||||
data=path.read_bytes();target=destination/name
|
||||
target.parent.mkdir(parents=True,exist_ok=True)
|
||||
with target.open('xb') as stream:
|
||||
stream.write(data);stream.flush();os.fsync(stream.fileno())
|
||||
proof['files'].append({'path':str(canonical_path(target)),'sha256':hashlib.sha256(data).hexdigest()})
|
||||
proof['recovery_id']=audit.name
|
||||
proof['recovery_mode']=mode
|
||||
return proof
|
||||
except (OSError,ValueError,KeyError,TypeError) as error:
|
||||
raise TaskCenterError('quick_run_uncertain','恢复审计无法与原执行项绑定,保护记录保留。') from error
|
||||
|
||||
|
||||
def _require_source_recovery(audit,row,record,outcome,snapshot):
|
||||
from .execution_journal import read_command_rows
|
||||
from .native_helper import read_snapshot, snapshot_target_cell
|
||||
from .quick_run import _read_command_options, _read_command_sheet_targets, _read_status_details
|
||||
original=audit/'evidence-before'/'command.tsv'
|
||||
worker=audit/'worker'/'command.tsv'
|
||||
originals=[entry for entry in read_command_rows(original) if entry['job_id']==row['job_id']]
|
||||
workers=read_command_rows(worker)
|
||||
if (record['state']!='retry_ready' or outcome[0]!='retry_ready' or
|
||||
originals!=[row] or len(workers)!=1 or workers[0].get('recovery_source_only')!='1' or
|
||||
_read_status_details(worker.parent/'status.tsv')!=(tuple(record['worker_result']),)):
|
||||
raise ValueError('source-only recovery is not a bound original-state readback')
|
||||
actual=workers[0]
|
||||
for key,default in (('task_id',''),('job_id',''),('old_part',''),('new_part',''),
|
||||
('target_scope','all'),('target_selectors',''),('target_cell','')):
|
||||
if row.get(key,default)!=actual.get(key,default):
|
||||
raise ValueError('source-only worker command changed')
|
||||
if canonical_path(row['project_path'])!=canonical_path(actual['project_path']):
|
||||
raise ValueError('source-only worker project changed')
|
||||
options=_read_command_options(original)[row['job_id']]
|
||||
original_sheets=_read_command_sheet_targets(original) or {}
|
||||
worker_sheets=_read_command_sheet_targets(worker) or {}
|
||||
if (options!=_read_command_options(worker)[row['job_id']] or
|
||||
original_sheets.get(row['job_id'])!=worker_sheets.get(row['job_id'])):
|
||||
raise ValueError('source-only worker policy or sheet changed')
|
||||
if (Path(str(snapshot)+'.native.json').exists() or
|
||||
Path(str(worker.parent/snapshot.name)+'.native.json').exists() or
|
||||
(worker.parent/snapshot.name).read_bytes()!=snapshot.read_bytes()):
|
||||
raise ValueError('source-only recovery evidence changed')
|
||||
for path in (snapshot,original):
|
||||
if hashlib.sha256(path.read_bytes()).hexdigest()!=record['evidence_before'][path.name]:
|
||||
raise ValueError('source-only original evidence changed')
|
||||
metadata,_=read_snapshot(snapshot)
|
||||
if (canonical_path(metadata[1])!=canonical_path(row['project_path']) or
|
||||
metadata[2:4]!=[row['old_part'],row['new_part']] or metadata[5]!=options[0] or
|
||||
(metadata[6:8] if len(metadata)>=8 else ['', '1'])!=[options[1],'1' if options[2] else '0'] or
|
||||
(metadata[9] if len(metadata)==10 else '')!=row.get('target_selectors','') or
|
||||
(snapshot_target_cell(snapshot,required=False) or '')!=row.get('target_cell','')):
|
||||
raise ValueError('source-only snapshot differs from original command')
|
||||
@@ -3,7 +3,7 @@ from .errors import TaskCenterError
|
||||
from .path_access import internal_path
|
||||
|
||||
|
||||
def assert_handoff_intact(root, task_id, *, files=None):
|
||||
def assert_handoff_intact(root, task_id, *, files=None, startup_pause_marker=None):
|
||||
from . import quick_run as api
|
||||
command=root/'command.tsv'; status=root/'status.tsv'
|
||||
exists=lambda path:internal_path(path).is_file()
|
||||
@@ -31,8 +31,11 @@ def assert_handoff_intact(root, task_id, *, files=None):
|
||||
if exists(current):
|
||||
current_commands=api._read_commands(parser(current))
|
||||
latest={row[0]:row[1] for row in details}
|
||||
import hashlib
|
||||
certified = (startup_pause_marker is not None and
|
||||
hashlib.sha256(internal_path(current).read_bytes()).hexdigest() == startup_pause_marker)
|
||||
if (len(current_commands)!=1 or current_commands[0] not in commands
|
||||
or current_commands[0][1] not in latest):
|
||||
or (current_commands[0][1] not in latest and not certified)):
|
||||
raise ValueError('dispatched item has no matching outcome')
|
||||
except (OSError, UnicodeError, ValueError, TaskCenterError) as error:
|
||||
raise TaskCenterError('quick_run_uncertain',
|
||||
|
||||
@@ -7,7 +7,7 @@ import subprocess
|
||||
import sys
|
||||
import time
|
||||
from traceback import clear_frames
|
||||
from threading import Event, Thread
|
||||
from threading import Event, Thread, Lock
|
||||
from uuid import uuid4
|
||||
|
||||
from .cad_identity import CadBinding, current_desktop_name, verify_application, project_file_path
|
||||
@@ -23,6 +23,10 @@ class PrivateCadStartupError(WorkerMonitorError):
|
||||
"""The owned desktop was released before any project worker was launched."""
|
||||
|
||||
|
||||
class PrivateCadStartupCancelled(PrivateCadStartupError):
|
||||
"""Startup stopped on an explicit abort before project execution."""
|
||||
|
||||
|
||||
class CadIdentityConflict(WorkerMonitorError, ValueError):
|
||||
"""An invalid CAD ownership certificate can never authorize automatic replay."""
|
||||
|
||||
@@ -108,6 +112,7 @@ class IsolatedCadSession:
|
||||
self._dialog_monitor_error = ''
|
||||
self._dialog_stop = Event()
|
||||
self._dialog_thread = None
|
||||
self._release_lock = Lock()
|
||||
|
||||
def _record(self, **values):
|
||||
self.record.update(values)
|
||||
@@ -183,11 +188,13 @@ class IsolatedCadSession:
|
||||
self._record(state='released', clean=False, startup_error=str(error))
|
||||
if is_identity_conflict(error):
|
||||
raise PrivateCadIdentityError(str(error)) from error
|
||||
if isinstance(error, PrivateCadStartupCancelled):
|
||||
raise
|
||||
raise PrivateCadStartupError(str(error)) from error
|
||||
|
||||
def _check_abort(self):
|
||||
if self.abort_event is not None and self.abort_event.is_set():
|
||||
raise WorkerMonitorError('private CAD startup was cancelled before execution')
|
||||
raise PrivateCadStartupCancelled('private CAD startup was cancelled before execution')
|
||||
|
||||
def _start_dialog_monitor(self):
|
||||
if getattr(self.desktop, 'inspect_dialogs', None) is None:
|
||||
@@ -213,6 +220,8 @@ class IsolatedCadSession:
|
||||
except Exception as error:
|
||||
self._dialog_monitor_error = str(error)
|
||||
self.record['dialog_supervision'] = dict(self._dialogs.summary(), monitor_error=self._dialog_monitor_error)
|
||||
if phase == 'closing':
|
||||
self.record['release_state'] = 'waiting_dialog' if self._dialogs.summary()['blocked'] else 'closing'
|
||||
if phase in {'startup', 'checkpoint'} and self._dialogs.failure:
|
||||
raise WorkerMonitorError(self._dialogs.failure + self._dialog_description())
|
||||
|
||||
@@ -237,9 +246,17 @@ class IsolatedCadSession:
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
|
||||
def start_worker(self, command, *, extra_environment=None, **options):
|
||||
def start_worker(self, command, *, job_id=None, extra_environment=None, **options):
|
||||
if self.binding is None or self.cad.poll() is not None:
|
||||
raise WorkerMonitorError('owned private CAD is unavailable')
|
||||
if job_id is not None:
|
||||
from .quick_run import _read_commands
|
||||
manifest = internal_path(Path(command[3]) / 'command.tsv')
|
||||
if manifest.is_file():
|
||||
rows = [row for row in _read_commands(manifest) if row[1] == job_id]
|
||||
if len(rows) != 1:
|
||||
raise CadIdentityConflict('owned project command identity is ambiguous')
|
||||
self.record['owned_project'] = str(canonical_path(rows[0][2]))
|
||||
environment = self.binding.environment()
|
||||
environment.update(extra_environment or {})
|
||||
# The verified CAD binding cannot be overridden by attempt metadata.
|
||||
@@ -276,6 +293,17 @@ class IsolatedCadSession:
|
||||
return result
|
||||
|
||||
def __exit__(self, error_type, error, traceback):
|
||||
if not self._release_lock.acquire(blocking=False):
|
||||
raise WorkerMonitorError('Mentor 释放正在进行,请等待当前释放结果。')
|
||||
try:
|
||||
if self.record.get('release_state') == 'released':
|
||||
return
|
||||
return self._close_session(error_type, error, traceback)
|
||||
finally:
|
||||
self._release_lock.release()
|
||||
|
||||
def _close_session(self, error_type, error, traceback):
|
||||
self.record['release_state'] = 'closing'
|
||||
if self.read_only:
|
||||
return self._close_read_only()
|
||||
self._stop_dialog_monitor()
|
||||
@@ -324,8 +352,17 @@ class IsolatedCadSession:
|
||||
raise WorkerMonitorError('owned CAD exited before the authorized quit request')
|
||||
if self.cad is not None and self.binding is not None:
|
||||
self._poll_dialogs('closing')
|
||||
environment = self.binding.environment()
|
||||
environment.pop('DXPART_CLOSE_WITHOUT_SAVE_PROTECTED', None)
|
||||
environment['DXPART_OWNED_PROJECT'] = self.record.get('owned_project', '')
|
||||
self.record['project_close_policy'] = 'saved_only'
|
||||
if error is not None:
|
||||
# No unsaved-document close starts until uncertainty is durable.
|
||||
self._uncertain(str(error), project_close_policy='no_save_protected',
|
||||
rollback_guaranteed=False, changes_may_be_persisted=True)
|
||||
environment['DXPART_CLOSE_WITHOUT_SAVE_PROTECTED'] = self.token
|
||||
closing = self.desktop.start_process(_helper_command('quit', self.root / 'private-desktop.json', self.cad.pid),
|
||||
env=_child_environment(self.binding.environment()), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
env=_child_environment(environment), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
quit_code = self._wait_process(closing, 20, 'closing')
|
||||
exit_codes['quit_helper_exit_code'] = quit_code
|
||||
if quit_code:
|
||||
@@ -352,6 +389,14 @@ class IsolatedCadSession:
|
||||
from .read_recovery import process_tree_exited
|
||||
cad_running = not all(process_tree_exited(process)
|
||||
for process in self._owned_processes(closing))
|
||||
if cad_running and self.record['orderly_shutdown']:
|
||||
from .isolated_desktop import DESCENDANT_EXIT_GRACE_SECONDS
|
||||
deadline = time.monotonic() + DESCENDANT_EXIT_GRACE_SECONDS
|
||||
# A successful Quit can precede a child's normal exit.
|
||||
while cad_running and time.monotonic() < deadline:
|
||||
time.sleep(min(.01, max(0, deadline - time.monotonic())))
|
||||
cad_running = not all(process_tree_exited(process)
|
||||
for process in self._owned_processes(closing))
|
||||
except Exception as failure:
|
||||
remember('cad_exit_check', failure)
|
||||
if cad_running:
|
||||
@@ -360,11 +405,9 @@ class IsolatedCadSession:
|
||||
persist_uncertain()
|
||||
from .stop_control import StopControl
|
||||
if not isinstance(self.stop_control, StopControl):
|
||||
self._retain_for_manual(closing)
|
||||
raise WorkerMonitorError('owned CAD is still running; handles retained until explicit force or exit')
|
||||
# A refused/timed-out Quit may still be saving or closing.
|
||||
# Keep both CAD and its helper owned and alive until the
|
||||
# caller confirms force or both retained processes exit.
|
||||
self.stop_control = StopControl()
|
||||
# A failed Quit is a failure-release boundary; protect the
|
||||
# result before closing our own CAD and helper Jobs.
|
||||
from .stop_control import wait_for_resolution
|
||||
def owned_processes_exited():
|
||||
self._poll_dialogs('closing')
|
||||
@@ -372,12 +415,13 @@ class IsolatedCadSession:
|
||||
return all(process_tree_exited(process) for process in self._owned_processes(closing))
|
||||
try:
|
||||
wait_for_resolution(self.stop_control, self.root, failure_message(),
|
||||
resolved=owned_processes_exited)
|
||||
resolved=owned_processes_exited, release_on_failure=True)
|
||||
except WorkerMonitorError as failure:
|
||||
force_event = getattr(self.stop_control, 'force_event', None)
|
||||
if force_event is None or not force_event.is_set():
|
||||
raise
|
||||
remember('forced_stop', failure)
|
||||
self.record['cleanup_mode'] = getattr(self.stop_control, 'cleanup_mode', None)
|
||||
remember('failure_release' if self.record['cleanup_mode'] else 'forced_stop', failure)
|
||||
if closing is not None:
|
||||
try:
|
||||
closing.close()
|
||||
@@ -388,6 +432,9 @@ class IsolatedCadSession:
|
||||
RETAINED_CAD_SESSIONS.pop(str(self.root), None)
|
||||
except Exception as failure:
|
||||
remember('desktop_release', failure)
|
||||
from .read_recovery import process_tree_exited
|
||||
self.record['release_state'] = 'released' if all(
|
||||
process_tree_exited(process) for process in self._owned_processes(closing)) else 'failed'
|
||||
desktop_cleanup = getattr(self.desktop, 'cleanup_record', None) or {}
|
||||
forced = [item for item in desktop_cleanup.get('processes', []) if item.get('forced_termination')]
|
||||
self.record.update(forced_termination=bool(forced),
|
||||
@@ -408,7 +455,11 @@ class IsolatedCadSession:
|
||||
if failures:
|
||||
persist_uncertain()
|
||||
if failures:
|
||||
raise WorkerMonitorError('private CAD cleanup requires reconciliation: ' + failure_message()) from failures[0]
|
||||
from .stop_control import MentorReleaseRequired
|
||||
failure_type = MentorReleaseRequired if self.record.get('cleanup_mode') else WorkerMonitorError
|
||||
failure = failure_type('private CAD cleanup requires reconciliation: ' + failure_message())
|
||||
failure.primary_error = error or failures[0]
|
||||
raise failure from failures[0]
|
||||
|
||||
def _owned_processes(self, closing=None):
|
||||
processes = list(getattr(self.desktop, '_processes', getattr(self.desktop, 'processes', ())))
|
||||
@@ -440,7 +491,7 @@ class IsolatedCadSession:
|
||||
self._record(state='read_only_release_pending', clean=False, cleanup_error=str(error))
|
||||
raise WorkerMonitorError('read-only generation release was not confirmed: ' + str(error)) from error
|
||||
self._record(state='session_closed' if self.borrowed_desktop else 'released',
|
||||
clean=True, read_only_released=True, desktop_retained_by_batch=self.borrowed_desktop,
|
||||
clean=True, read_only_released=True, release_state='released', desktop_retained_by_batch=self.borrowed_desktop,
|
||||
shutdown_seconds=time.monotonic() - started,
|
||||
desktop_cleanup=getattr(self.desktop, 'cleanup_record', None))
|
||||
|
||||
@@ -456,8 +507,14 @@ def run_isolated_process(command, timeout, *, abort_event=None, cooperative_abor
|
||||
return runtime.run_worker(command, timeout, abort_event=abort_event,
|
||||
cooperative_abort=cooperative_abort)
|
||||
try:
|
||||
with IsolatedCadSession(Path(command[3]), abort_event=abort_event, read_only=cooperative_abort) as session:
|
||||
return run_monitored_process(command, timeout, abort_event=abort_event, process_factory=session.start_worker,
|
||||
from .stop_control import StopControl
|
||||
control = StopControl()
|
||||
with IsolatedCadSession(Path(command[3]), abort_event=abort_event,
|
||||
stop_control=control, read_only=cooperative_abort) as session:
|
||||
def start_worker(launch, **options):
|
||||
return session.start_worker(launch, job_id=command[-1], **options)
|
||||
return run_monitored_process(command, timeout, abort_event=abort_event, process_factory=start_worker,
|
||||
force_control=control,
|
||||
**({'cooperative_abort': True} if cooperative_abort else {}))
|
||||
except CadIdentityConflict:
|
||||
raise
|
||||
@@ -497,6 +554,7 @@ def _native_action(action, evidence, expected_pid):
|
||||
import win32process
|
||||
pythoncom.CoInitialize()
|
||||
app = None
|
||||
documents = sheets = sheet = None
|
||||
try:
|
||||
desktop = os.environ.get('DXPART_DESKTOP', '')
|
||||
token = os.environ.get('DXPART_SESSION_TOKEN', '')
|
||||
@@ -539,8 +597,29 @@ def _native_action(action, evidence, expected_pid):
|
||||
raise CadIdentityConflict(str(error)) from error
|
||||
# ActiveViewHandle can retain a destroyed/reused HWND after closing
|
||||
# the last project. The private ROT/GUID binds this empty instance.
|
||||
if opened_project:
|
||||
if opened_project and action == 'checkpoint':
|
||||
raise CadIdentityConflict('owned CAD still has a project open; no implicit save or discard')
|
||||
if opened_project:
|
||||
expected_project = os.environ.get('DXPART_OWNED_PROJECT', '')
|
||||
if not expected_project or canonical_path(opened_project) != canonical_path(expected_project):
|
||||
raise CadIdentityConflict('owned CAD still has a project open; project is untracked or changed')
|
||||
documents = app.SchematicSheetDocuments()
|
||||
sheets = [documents.Item(index) for index in range(1, int(documents.Count) + 1)]
|
||||
close_without_save = os.environ.get('DXPART_CLOSE_WITHOUT_SAVE_PROTECTED') == binding.token
|
||||
if not close_without_save and any(getattr(sheet, 'Saved', None) is not True for sheet in sheets):
|
||||
raise ValueError('owned project has unsaved or unknown document state; no implicit save or discard')
|
||||
for sheet in sheets:
|
||||
if canonical_path(project_file_path(app)) != canonical_path(expected_project):
|
||||
raise CadIdentityConflict('owned project changed before document close')
|
||||
# Disable implicit Save; this is not proof of database rollback.
|
||||
sheet.Close(False, '')
|
||||
if canonical_path(project_file_path(app)) != canonical_path(expected_project):
|
||||
raise CadIdentityConflict('owned project changed before project close')
|
||||
if app.CloseProject() is not True:
|
||||
raise ValueError('owned project refused CloseProject')
|
||||
if project_file_path(app):
|
||||
raise ValueError('owned project remained open after CloseProject')
|
||||
sheets = documents = sheet = None
|
||||
if action == 'quit':
|
||||
app.Quit()
|
||||
else:
|
||||
@@ -564,7 +643,7 @@ def _native_action(action, evidence, expected_pid):
|
||||
finally:
|
||||
# Release our automation proxy while its COM apartment is still alive.
|
||||
# Leaving it in this frame until return defers Release past shutdown.
|
||||
app = None
|
||||
documents = sheets = sheet = app = None
|
||||
pythoncom.CoUninitialize()
|
||||
return 0
|
||||
|
||||
|
||||
@@ -34,6 +34,34 @@ def _native_handle(handle):
|
||||
return None
|
||||
|
||||
|
||||
def _job_process_ids(job, *, query=None):
|
||||
# pywin32 312 can leave NULL tuple slots when assigned processes exit mid-query.
|
||||
if query is None:
|
||||
query = ctypes.WinDLL('kernel32', use_last_error=True).QueryInformationJobObject
|
||||
query.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p,
|
||||
wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
|
||||
query.restype = wintypes.BOOL
|
||||
capacity = 64
|
||||
for _ in range(8):
|
||||
buffer = ctypes.create_string_buffer(8 + capacity * ctypes.sizeof(ctypes.c_size_t))
|
||||
returned = wintypes.DWORD()
|
||||
success = query(int(job), 3, buffer, ctypes.sizeof(buffer), ctypes.byref(returned))
|
||||
assigned, count = (wintypes.DWORD * 2).from_buffer(buffer)
|
||||
if not success:
|
||||
error = ctypes.get_last_error()
|
||||
if error != 234: # ERROR_MORE_DATA
|
||||
raise ctypes.WinError(error)
|
||||
capacity = max(capacity * 2, assigned)
|
||||
continue
|
||||
if count > capacity:
|
||||
raise OSError('Job process list exceeds its returned buffer')
|
||||
result = tuple((ctypes.c_size_t * count).from_buffer(buffer, 8))
|
||||
if any(pid == 0 for pid in result):
|
||||
raise OSError('Job process list contains an invalid process ID')
|
||||
return result
|
||||
raise OSError('Job process list kept growing during snapshot')
|
||||
|
||||
|
||||
def _resource_event(operation, handle, success, error=None):
|
||||
return {'operation': operation, 'handle': _native_handle(handle), 'success': success,
|
||||
'pid': os.getpid(), 'thread_id': get_native_id(), 'time_ns': time.time_ns(),
|
||||
@@ -60,6 +88,7 @@ class _Win32Api:
|
||||
self.con, self.job, self.process, self.service = win32con, win32job, win32process, win32service
|
||||
self.event = win32event
|
||||
self.open_process = win32api.OpenProcess
|
||||
self.process_ids = _job_process_ids
|
||||
self._pending_cleanup = []
|
||||
|
||||
def create_desktop(self, name: str):
|
||||
@@ -99,6 +128,7 @@ class _Win32Api:
|
||||
|
||||
def _desktop_windows(self, name):
|
||||
"""Diagnose residue without switching desktops or terminating foreign owners."""
|
||||
import pywintypes
|
||||
import win32gui
|
||||
|
||||
desktop = self.service.OpenDesktop(name, 0, False, 1) # DESKTOP_READOBJECTS
|
||||
@@ -117,9 +147,13 @@ class _Win32Api:
|
||||
if not enumerate_windows(int(desktop), callback, 0) and ctypes.get_last_error():
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
for handle in handles:
|
||||
thread, pid = self.process.GetWindowThreadProcessId(handle)
|
||||
windows.append({'hwnd': int(handle), 'pid': pid, 'thread_id': thread,
|
||||
'class': win32gui.GetClassName(handle)})
|
||||
try:
|
||||
thread, pid = self.process.GetWindowThreadProcessId(handle)
|
||||
windows.append({'hwnd': int(handle), 'pid': pid, 'thread_id': thread,
|
||||
'class': win32gui.GetClassName(handle)})
|
||||
except pywintypes.error as error:
|
||||
if error.winerror != 1400 or win32gui.IsWindow(handle):
|
||||
raise
|
||||
finally:
|
||||
desktop.CloseDesktop()
|
||||
return windows
|
||||
@@ -153,7 +187,7 @@ class _Win32Api:
|
||||
None, None, False, flags, env, str(cwd) if cwd else None, startup,
|
||||
)
|
||||
process = _Win32Process(self.process, self.job, self.event, handle, job, int(pid), command,
|
||||
open_process=getattr(self, 'open_process', None))
|
||||
open_process=getattr(self, 'open_process', None), process_ids=self.process_ids)
|
||||
process.stdout, process.stderr = streams
|
||||
process.thread = thread
|
||||
self.job.AssignProcessToJobObject(job, handle)
|
||||
@@ -318,10 +352,12 @@ def _create_redirected_process(command, desktop, cwd, env, flags, stdout, stderr
|
||||
|
||||
|
||||
class _Win32Process:
|
||||
def __init__(self, process_api, job_api, event_api, handle, job, pid: int, args, *, open_process=None):
|
||||
def __init__(self, process_api, job_api, event_api, handle, job, pid: int, args, *, open_process=None,
|
||||
process_ids=_job_process_ids):
|
||||
self._process_api, self._job_api = process_api, job_api
|
||||
self._event_api = event_api
|
||||
self._open_process = open_process
|
||||
self._process_ids = process_ids
|
||||
self._descendant_handles = []
|
||||
self._descendant_pids = set()
|
||||
self.handle, self.job, self.pid = handle, job, pid
|
||||
@@ -413,7 +449,7 @@ class _Win32Process:
|
||||
active = set()
|
||||
if self._open_process is None or self.job is None:
|
||||
return active
|
||||
for pid in self._job_api.QueryInformationJobObject(self.job, self._job_api.JobObjectBasicProcessIdList):
|
||||
for pid in self._process_ids(self.job):
|
||||
if pid == self.pid:
|
||||
continue
|
||||
if pid in self._descendant_pids:
|
||||
@@ -645,6 +681,25 @@ class PrivateDesktop:
|
||||
close_pending()
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
try:
|
||||
self.release_desktop()
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
self.cleanup_record['errors'] = [str(error) for error in errors]
|
||||
if errors:
|
||||
self.cleanup_record['owned_resource_diagnostics'] = self._owned_resource_diagnostics()
|
||||
_raise_cleanup_errors(errors)
|
||||
|
||||
def release_desktop(self) -> None:
|
||||
"""Release only our desktop handle; process cleanup is a separate action."""
|
||||
errors = []
|
||||
if self.cleanup_record is None:
|
||||
self.cleanup_record = {'desktop': self.name, 'processes': []}
|
||||
from .read_recovery import process_tree_exited
|
||||
if any(not process_tree_exited(process) for process in self._processes):
|
||||
self.cleanup_record.update(desktop_release_state='waiting_for_mentor',
|
||||
desktop_handle_closed=self._handle is None)
|
||||
raise TaskCenterError('desktop_waiting_for_mentor', '关联进程仍在运行,桌面释放等待 Mentor 收尾。')
|
||||
close_desktop = getattr(self._handle, "CloseDesktop", None)
|
||||
if close_desktop:
|
||||
event = _resource_event('close', self._handle, False)
|
||||
@@ -663,6 +718,7 @@ class PrivateDesktop:
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
self.cleanup_record.update(desktop_handle_closed=self._handle is None,
|
||||
desktop_release_state='failed' if errors else 'released',
|
||||
desktop_confirmation=getattr(self._api, 'desktop_release_check', None),
|
||||
desktop_handle_history=deepcopy(self._desktop_handle_history),
|
||||
process_history=deepcopy(self._process_history),
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Hidden CLI processes owned by a Job; no desktop is created or switched."""
|
||||
from __future__ import annotations
|
||||
|
||||
from .errors import TaskCenterError
|
||||
|
||||
_UNCERTAIN_SCOPES = []
|
||||
|
||||
|
||||
class OwnedCliScope:
|
||||
def __init__(self, name=None, *, enabled=True, api=None):
|
||||
self._api = api
|
||||
self._processes = []
|
||||
self.cleanup_record = None
|
||||
|
||||
def __enter__(self):
|
||||
if self._api is None:
|
||||
from .isolated_desktop import _Win32Api
|
||||
self._api = _Win32Api()
|
||||
return self
|
||||
|
||||
def __exit__(self, *_exc):
|
||||
self.close()
|
||||
|
||||
def start_process(self, command, *, cwd=None, env=None, stdout=None, stderr=None):
|
||||
process = self._api.create_process(command, 'winsta0\\Default', cwd, env,
|
||||
stdout=stdout, stderr=stderr)
|
||||
self._processes.append(process)
|
||||
return process
|
||||
|
||||
def close(self):
|
||||
errors, records = [], []
|
||||
for process in self._processes:
|
||||
try:
|
||||
process.close()
|
||||
except Exception as error:
|
||||
errors.append(str(error))
|
||||
records.append(getattr(process, 'cleanup_record', None))
|
||||
try:
|
||||
self._api.close_pending()
|
||||
except Exception as error:
|
||||
errors.append(str(error))
|
||||
self.cleanup_record = {'workers_closed': not errors, 'processes': records, 'errors': errors,
|
||||
'desktop_created': False}
|
||||
if errors:
|
||||
if self not in _UNCERTAIN_SCOPES:
|
||||
_UNCERTAIN_SCOPES.append(self)
|
||||
raise TaskCenterError('inventory_cleanup', '; '.join(errors))
|
||||
|
||||
|
||||
def installation_root():
|
||||
from .isolated_cad import _designer_executable
|
||||
return _designer_executable().parents[3]
|
||||
|
||||
|
||||
def environment(root):
|
||||
import os
|
||||
root = str(root)
|
||||
env = dict(os.environ, SDD_HOME=root, SDD_PLATFORM='win32')
|
||||
from pathlib import Path
|
||||
folders = ('common/win32/lib', 'common/win32/bin', 'wv/win32/bin', 'iCDB/win32/bin')
|
||||
env['PATH'] = os.pathsep.join([str(Path(root) / folder) for folder in folders] + [env.get('PATH', '')])
|
||||
return env
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Native current-sheet replacement adapter for the existing QuickPartReplace runner."""
|
||||
import argparse
|
||||
from collections import Counter
|
||||
import faulthandler
|
||||
import ctypes
|
||||
import csv
|
||||
@@ -432,13 +433,17 @@ def check_context(app, api, metadata, records, require_selection=True):
|
||||
if actual != wanted:
|
||||
raise ValueError(f"Source batch changed since snapshot: expected={sorted(wanted)!r} actual={sorted(actual)!r}")
|
||||
if require_selection:
|
||||
selected = {_component_uid(api.IVdComp(component._oleobj_))
|
||||
for component in app.ActiveView.Query(128, 1)}
|
||||
if selected != wanted:
|
||||
raise ValueError(f"Selected component set differs from snapshot: expected={sorted(wanted)!r} actual={sorted(selected)!r}")
|
||||
_check_snapshot_selection(app, api, wanted)
|
||||
return components
|
||||
|
||||
|
||||
def _check_snapshot_selection(app, api, wanted):
|
||||
selected = {_component_uid(api.IVdComp(component._oleobj_))
|
||||
for component in app.ActiveView.Query(128, 1)}
|
||||
if selected != wanted:
|
||||
raise ValueError(f"Selected component set differs from snapshot: expected={sorted(wanted)!r} actual={sorted(selected)!r}")
|
||||
|
||||
|
||||
def _target_selectors(value):
|
||||
result = {}
|
||||
for item in value.split("\x1e"):
|
||||
@@ -451,21 +456,77 @@ def _target_selectors(value):
|
||||
return result
|
||||
|
||||
|
||||
def verify_unselected_snapshot(snapshot, components, selected_uids):
|
||||
def _duplicate_unselected_identities(lines, baseline):
|
||||
names = ('part number', 'value', 'part name', 'part label')
|
||||
versions = [line.split('\t') for line in lines if line.startswith('X\t')]
|
||||
full_rows = [line.split('\t') for line in lines if line.startswith('G\t')]
|
||||
if not versions and not full_rows:
|
||||
return {} # Legacy U-only snapshots retain their existing scalar check.
|
||||
if versions != [['X', 'untouched_full_v1']]:
|
||||
raise ValueError('Unselected full-state version is missing or invalid')
|
||||
seen, duplicates = set(), {}
|
||||
for row in full_rows:
|
||||
if len(row) != 3:
|
||||
raise ValueError('Unselected full-state row is malformed')
|
||||
uid = decode(row[1])
|
||||
if uid not in baseline or uid in seen:
|
||||
raise ValueError('Unselected full-state owner differs from identity baseline')
|
||||
seen.add(uid)
|
||||
records = [[decode(field) for field in line.split('\t')]
|
||||
for line in decode(row[2]).splitlines() if line]
|
||||
headers = [r for r in records if r[0] == 'C']
|
||||
if (len(headers) != 1 or len(headers[0]) != 8
|
||||
or headers[0][1:3] != [uid, baseline[uid][0]]):
|
||||
raise ValueError('Unselected full-state header differs from identity baseline')
|
||||
attrs, summary = [], {}
|
||||
for record in records:
|
||||
if record[0] == 'C':
|
||||
continue
|
||||
if len(record) != 12 or record[0] != 'A' or record[1] != uid:
|
||||
raise ValueError('Unselected attribute owner or record is invalid')
|
||||
name = record[2].casefold()
|
||||
if name in names:
|
||||
attrs.append(tuple(record[2:5]))
|
||||
summary.setdefault(name, record[4] or record[3])
|
||||
if (headers[0][2], *(summary.get(name, '') for name in names)) != baseline[uid]:
|
||||
raise ValueError('Unselected identity summary differs from full-state attributes')
|
||||
if len({attr[0].casefold() for attr in attrs}) != len(attrs):
|
||||
duplicates[uid] = Counter(attrs)
|
||||
if seen != set(baseline):
|
||||
raise ValueError('Unselected full-state baseline is incomplete')
|
||||
return duplicates
|
||||
|
||||
|
||||
def verify_unselected_snapshot(snapshot, components, selected_uids, *, api=None):
|
||||
"""Compare the full identity/value baseline for components outside target scope."""
|
||||
selected_uids = {str(uid) for uid in selected_uids}
|
||||
rows = [line.split("\t") for line in Path(snapshot).read_text(encoding="utf-8-sig").splitlines()
|
||||
if line.startswith("U\t")]
|
||||
lines = Path(snapshot).read_text(encoding="utf-8-sig").splitlines()
|
||||
rows = [line.split("\t") for line in lines if line.startswith("U\t")]
|
||||
if any(len(row) != 7 for row in rows):
|
||||
raise ValueError("Unselected component baseline is malformed")
|
||||
baseline = {decode(row[1]): tuple(decode(value) for value in row[2:]) for row in rows}
|
||||
if len(baseline) != len(rows):
|
||||
if len(baseline) != len(rows) or any(not uid for uid in baseline):
|
||||
raise ValueError("Duplicate unselected component UID")
|
||||
duplicates = _duplicate_unselected_identities(lines, baseline)
|
||||
current = {}
|
||||
for component in components:
|
||||
uid = _component_uid(component)
|
||||
if uid in selected_uids:
|
||||
continue
|
||||
if uid in duplicates:
|
||||
observed = []
|
||||
for item in component.Attributes:
|
||||
attribute = api.IVdAttr(item._oleobj_) if api is not None else item
|
||||
name = str(attribute.Name)
|
||||
if name.casefold() in {'part number', 'value', 'part name', 'part label'}:
|
||||
base, instance = attribute.Value, attribute.InstanceValue
|
||||
observed.append((name, '' if base is None else str(base),
|
||||
'' if instance is None else str(instance)))
|
||||
if str(component.Refdes) != baseline[uid][0] or Counter(observed) != duplicates[uid]:
|
||||
raise ValueError('An unselected component identity attribute was changed')
|
||||
# The full occurrence set proves the otherwise ambiguous scalar summary.
|
||||
current[uid] = baseline[uid]
|
||||
continue
|
||||
current[uid] = (str(component.Refdes), *(attribute_value(component, name)
|
||||
for name in ("Part Number", "Value", "Part Name", "Part Label")))
|
||||
if baseline != current:
|
||||
@@ -478,7 +539,10 @@ def select_snapshot_batch(app, api, metadata, records):
|
||||
wanted = {row[1] for row in records}
|
||||
for component in components:
|
||||
selection(component, _component_uid(component) in wanted)
|
||||
return check_context(app, api, metadata, records)
|
||||
# Selection changes no component data; keep these proxies only in this call.
|
||||
check_active_context(app, metadata)
|
||||
_check_snapshot_selection(app, api, wanted)
|
||||
return components
|
||||
|
||||
|
||||
def existing_replacement_uids(components, records, target, binding, require_part_label=True):
|
||||
@@ -565,12 +629,12 @@ def replacement_matches(components, records, target, require_part_label, *, libr
|
||||
|
||||
|
||||
def verify_replacement_readback(snapshot, components, metadata, records, before_uids,
|
||||
untouched, require_part_label, library_row, replaced_uids):
|
||||
untouched, require_part_label, library_row, replaced_uids, *, api=None):
|
||||
if len(components) != len(before_uids):
|
||||
raise ValueError('Component count changed during replacement')
|
||||
if len(metadata) == 10:
|
||||
# The persisted U baseline already covers exactly these identity fields.
|
||||
verify_unselected_snapshot(snapshot, components, {row[1] for row in records})
|
||||
verify_unselected_snapshot(snapshot, components, {row[1] for row in records}, api=api)
|
||||
else:
|
||||
current = {_component_uid(component): component for component in components}
|
||||
for uid, identity in untouched.items():
|
||||
@@ -603,7 +667,7 @@ def run_native(snapshot, report):
|
||||
components = components_on_sheet(app, api)
|
||||
wanted = {row[1] for row in records}
|
||||
if len(metadata) == 10:
|
||||
verify_unselected_snapshot(snapshot, components, wanted)
|
||||
verify_unselected_snapshot(snapshot, components, wanted, api=api)
|
||||
source_uids = {
|
||||
_component_uid(component)
|
||||
for component in components
|
||||
@@ -833,7 +897,7 @@ def run_native(snapshot, report):
|
||||
raise
|
||||
current = components_on_sheet(app, api)
|
||||
verify_replacement_readback(snapshot, current, metadata, records, before_uids,
|
||||
untouched, require_part_label, columns, report['replaced_uids'])
|
||||
untouched, require_part_label, columns, report['replaced_uids'], api=api)
|
||||
report["stage"] = "native_replace_applied"
|
||||
save_report(snapshot, report)
|
||||
report["stage"] = "pin_promotion_started"
|
||||
|
||||
@@ -14,12 +14,11 @@ from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import canonical_path, internal_path, retry_sharing_violation
|
||||
from .isolated_desktop import PrivateDesktop
|
||||
from .native_cli import OwnedCliScope
|
||||
from .native_inventory_protocol import NativeInventoryUnsupported, read_ascii_discovery, read_native_text
|
||||
from .operation_control import check_cancelled, report_progress
|
||||
|
||||
|
||||
_RETRY_NATIVE_READ = object()
|
||||
_NATIVE_CRASH_CODES = frozenset({0xC0000005, 0xC000001D, 0xC0000094,
|
||||
0xC00000FD, 0xC0000374, 0xC0000409})
|
||||
|
||||
@@ -67,7 +66,7 @@ class NativeInventoryReader:
|
||||
temporary_root=None, timeout=30):
|
||||
self.data_root = Path(data_root)
|
||||
self.tool_directory = tool_directory
|
||||
self.desktop_factory = desktop_factory or PrivateDesktop
|
||||
self.desktop_factory = desktop_factory or OwnedCliScope
|
||||
self.temporary_root = temporary_root
|
||||
self.timeout = timeout
|
||||
|
||||
@@ -89,17 +88,11 @@ class NativeInventoryReader:
|
||||
text, block, snapshot, database = _project_options(project)
|
||||
tools = self._tools()
|
||||
except (NativeInventoryUnsupported, OSError, ImportError, UnicodeError, TaskCenterError) as error:
|
||||
report_progress(on_progress, f'使用 CAD 核验位号:{str(error)[:160]}')
|
||||
return None
|
||||
for attempt in range(2):
|
||||
result = self._read(project, text, block, snapshot, database, tools, old_part_numbers,
|
||||
stop_event=stop_event, on_progress=on_progress, runtime=runtime,
|
||||
allow_retry=runtime is not None and attempt == 0)
|
||||
if result is not _RETRY_NATIVE_READ:
|
||||
return result
|
||||
return None
|
||||
raise TaskCenterError('native_inventory', f'原生清单读取不可用:{str(error)[:160]}') from error
|
||||
return self._read(project, text, block, snapshot, database, tools, old_part_numbers,
|
||||
stop_event=stop_event, on_progress=on_progress)
|
||||
|
||||
def _read(self, project, text, block, snapshot, database, tools, old_part_numbers, *, stop_event, on_progress, runtime=None, allow_retry=False):
|
||||
def _read(self, project, text, block, snapshot, database, tools, old_part_numbers, *, stop_event, on_progress):
|
||||
token = uuid4().hex
|
||||
evidence = internal_path(self.data_root / 'quick-run-history' / ('native-inventory-' + token))
|
||||
retry_sharing_violation(lambda: evidence.mkdir(parents=True, exist_ok=False))
|
||||
@@ -107,8 +100,7 @@ class NativeInventoryReader:
|
||||
/ 'DxProductivity' / 'native-inventory').resolve()
|
||||
base.mkdir(parents=True, exist_ok=True)
|
||||
workspace = Path(tempfile.mkdtemp(prefix='dx-cli-', dir=base)).resolve()
|
||||
desktop = (runtime.native_scope(canonical_path(evidence)) if runtime is not None
|
||||
else self.desktop_factory('dx-cli-' + token, enabled=True))
|
||||
desktop = self.desktop_factory('dx-cli-' + token, enabled=True)
|
||||
record = {'backend': 'native_cli', 'project': str(project), 'state': 'reading',
|
||||
'workspace': str(workspace), 'tools': []}
|
||||
started = time.monotonic()
|
||||
@@ -142,7 +134,8 @@ class NativeInventoryReader:
|
||||
report_progress(on_progress, '正在使用原生接口读取工程快照中的器件和位号…')
|
||||
try:
|
||||
desktop.__enter__()
|
||||
environment = dict(os.environ, SDD_HOME=str(tools[0].parents[3]))
|
||||
from .native_cli import environment as cli_environment
|
||||
environment = cli_environment(tools[0].parents[3])
|
||||
for command in commands:
|
||||
self._run_tool(desktop, command, workspace, environment, output,
|
||||
record, stop_event)
|
||||
@@ -174,32 +167,8 @@ class NativeInventoryReader:
|
||||
_verify_sources(source_hashes)
|
||||
record.update(source_hashes_unchanged=True,
|
||||
source_hashes={str(path): digest for path, digest in source_hashes.items()})
|
||||
retry = False
|
||||
cleanup = getattr(desktop, 'cleanup_record', None)
|
||||
session_failure = runtime is not None and isinstance(error, _NativeInventoryProcessError)
|
||||
if (session_failure
|
||||
and clean and isinstance(cleanup, dict) and cleanup.get('workers_closed') is True):
|
||||
check_cancelled(stop_event)
|
||||
from .batch_resources import write_record
|
||||
write_record(evidence / 'native-retry-proof.json', {
|
||||
'version': 1, 'native_read_only': True, 'project_path': str(project),
|
||||
'source_hashes': {str(path): digest for path, digest in source_hashes.items()},
|
||||
'workers_closed': True, 'evidence_root': str(canonical_path(evidence)),
|
||||
'binding': dict(desktop.identity),
|
||||
})
|
||||
_verify_sources(source_hashes)
|
||||
if allow_retry:
|
||||
retry = runtime.recover_native_failure(project, evidence, str(error))
|
||||
if session_failure and not retry:
|
||||
record.update(state='session_failed', reason=str(error))
|
||||
raise TaskCenterError('inventory_session',
|
||||
f'原生读取会话异常,未能完成安全重试,批次已停止。请保留诊断记录后排查:{evidence};{error}') from error
|
||||
record.update(state='retrying' if retry else 'fallback', reason=str(error))
|
||||
if retry:
|
||||
result = _RETRY_NATIVE_READ
|
||||
report_progress(on_progress, '原生读取会话已安全释放,正在重新核验一次…')
|
||||
else:
|
||||
report_progress(on_progress, f'原生清单未能完整核对,改用 CAD 采集:{str(error)[:160]}')
|
||||
record.update(state='failed', reason=str(error))
|
||||
raise TaskCenterError('native_inventory', f'原生清单未能完整核对:{str(error)[:160]}') from error
|
||||
except TaskCenterError as error:
|
||||
if record['state'] == 'uncertain':
|
||||
try:
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
@@ -147,14 +148,63 @@ def _parse_scope(text, requested, effective, inconsistent_refs):
|
||||
return blocks, sheets, targets
|
||||
|
||||
|
||||
def _hierarchical_root_discovery(project, report_path, effective_path, requested, expected_root):
|
||||
# ComponentTarget has no instance path: certify only globally unique root selections.
|
||||
from .native_netlist import _parse_ascii, _check_hierarchy_graph, _is_pcb
|
||||
text = read_native_text(report_path)
|
||||
roots = re.findall(r'^Block ([^\t\r\n]+)\tRoot$', text, re.MULTILINE)
|
||||
root = expected_root or (roots[0].rstrip() if len(roots) == 1 else None)
|
||||
try:
|
||||
components, _ = _parse_ascii(effective_path, require_connections=False)
|
||||
_check_hierarchy_graph(report_path, {'components': components}, root)
|
||||
except ValueError as error:
|
||||
raise NativeInventoryUnsupported(str(error)) from error
|
||||
physical = {uid: row for uid, row in components.items() if _is_pcb(row)}
|
||||
source_uids = Counter(row.get('source_uid', uid) for uid, row in components.items())
|
||||
references = Counter(row['refdes'] for row in physical.values())
|
||||
scopes, sheets, block = {}, set(), None
|
||||
for line in text.splitlines():
|
||||
if line.startswith('Block '):
|
||||
block = line[6:].split('\t', 1)[0].rstrip()
|
||||
elif line.startswith(' Symbol '):
|
||||
match = re.fullmatch(r' Symbol (.+?)\tpage (.+)', line)
|
||||
if match is None or block is None:
|
||||
raise NativeInventoryUnsupported('分层报告图页身份不明确')
|
||||
scopes[(block, match[1])] = match[2]
|
||||
sheets.add((block, match[2]))
|
||||
targets = []
|
||||
for uid, row in physical.items():
|
||||
attributes = row['attributes']
|
||||
if attributes.get('Part Number', '').casefold() not in requested:
|
||||
continue
|
||||
if row.get('instance_path') or source_uids[uid] != 1 or references[row['refdes']] != 1:
|
||||
raise NativeInventoryUnsupported('请求物料含子实例或非唯一 UID/位号,当前写入选择器不能安全定位')
|
||||
if 'source_refdes' in row or row.get('ambiguous_attributes'):
|
||||
raise NativeInventoryUnsupported('请求物料的位号或生效属性存在歧义')
|
||||
sheet = scopes.get((root, uid))
|
||||
if not sheet:
|
||||
raise NativeInventoryUnsupported('请求物料缺少唯一根块图页')
|
||||
targets.append(ComponentTarget(Path(project), root, sheet, uid, row['refdes'],
|
||||
attributes['Part Number'], attributes.get('Value', ''), attributes.get('Part Label'),
|
||||
attributes.get('Cell Name')))
|
||||
matches = {sheet: set() for sheet in sheets}
|
||||
for target in targets:
|
||||
matches[(target.schematic_name, target.sheet_number)].add(target.old_part_number.casefold())
|
||||
return ProjectDiscovery(tuple(sorted(sheets)), {key: frozenset(value) for key, value in matches.items()},
|
||||
tuple(sorted(targets, key=lambda target: target.key)), complete_sheet_manifest=False)
|
||||
|
||||
|
||||
def read_ascii_discovery(project, report_path, old_part_numbers, *, expected_root=None,
|
||||
effective_report_path=None):
|
||||
text = read_native_text(report_path)
|
||||
_require_report(text, 'HIER BLOCKS')
|
||||
if effective_report_path is None:
|
||||
raise NativeInventoryUnsupported('缺少实例生效属性报告,需由 CAD 核验')
|
||||
effective, inconsistent_refs = _effective_properties(read_native_text(effective_report_path))
|
||||
requested = {part.casefold() for part in old_part_numbers}
|
||||
effective_text = read_native_text(effective_report_path)
|
||||
if re.search(r'^\tPath [^\r\n]+', effective_text, re.MULTILINE):
|
||||
return _hierarchical_root_discovery(project, report_path, effective_report_path, requested, expected_root)
|
||||
effective, inconsistent_refs = _effective_properties(effective_text)
|
||||
blocks, available, targets = _parse_scope(text, requested, effective, inconsistent_refs)
|
||||
if expected_root is not None and expected_root not in blocks:
|
||||
raise NativeInventoryUnsupported('原生全工程报告与工程根块身份不一致')
|
||||
|
||||
@@ -0,0 +1,510 @@
|
||||
"""Capture saved sources now; export and compare their complete native graphs later."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter, defaultdict
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .native_inventory import _hash, _project_options
|
||||
from .native_inventory_protocol import _require_report, read_native_text
|
||||
from .native_cli import OwnedCliScope, environment, installation_root
|
||||
from .operation_control import check_cancelled
|
||||
from .path_access import canonical_path, internal_path
|
||||
|
||||
_VALUE_COVERAGE = 'ASCII serializes an absent Value as empty text; empty text does not prove attribute presence.'
|
||||
|
||||
|
||||
def _write_json(path, record):
|
||||
internal_path(path).write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
|
||||
|
||||
def capture_project(project: Path, destination: Path) -> dict:
|
||||
project = canonical_path(internal_path(project), strict=True)
|
||||
text, block, snapshot, database = _project_options(project)
|
||||
destination = canonical_path(destination)
|
||||
if destination.is_relative_to(project.parent):
|
||||
raise ValueError('Capture destination must be outside the live project')
|
||||
internal_path(destination).mkdir(parents=True, exist_ok=False)
|
||||
files = {'input.prj': project, 'database/icdb.dat': database}
|
||||
for name in ('Integration/AugmentedPins.txt', 'dxnetlister.ini', 'speccomp.ini'):
|
||||
path = project.parent / name
|
||||
if internal_path(path).is_file():
|
||||
files[name] = path
|
||||
hashes = {str(path): _hash(path) for path in files.values()}
|
||||
for relative, source in files.items():
|
||||
target = internal_path(destination / relative)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(internal_path(source), target)
|
||||
if _hash(target) != hashes[str(source)]:
|
||||
raise TaskCenterError('target_identity', '保存的工程在建立网表快照时发生变化,请重新保存后重试')
|
||||
if any(_hash(path) != hashes[str(path)] for path in files.values()):
|
||||
raise TaskCenterError('target_identity', '建立网表快照时源文件发生变化')
|
||||
if read_native_text(internal_path(destination / 'input.prj')) != text:
|
||||
raise TaskCenterError('target_identity', '建立网表快照时工程配置发生变化')
|
||||
for key, value in (('iCDBDir', 'database'), ('DedicatedServerName', ''), ('CentralLibrary', '')):
|
||||
text = re.sub(r'^KEY ' + key + r' "[^"\r\n]*"\s*$',
|
||||
lambda match: f'KEY {key} "{value}"', text, flags=re.MULTILINE)
|
||||
internal_path(destination / 'input.prj').write_text(text, encoding='utf-8')
|
||||
record = {'status': 'captured', 'project': str(project), 'root': str(destination),
|
||||
'root_block': block, 'snapshot': snapshot, 'project_path': str(destination / 'input.prj'),
|
||||
'database_path': str(destination / 'database/icdb.dat'), 'source_hashes': hashes,
|
||||
'capture_hashes': {relative: _hash(destination / relative) for relative in files},
|
||||
'manifest_path': str(destination / 'capture.json')}
|
||||
_write_json(destination / 'capture.json', record)
|
||||
return record
|
||||
|
||||
|
||||
def _check_capture(capture):
|
||||
if capture.get('status') != 'captured' or not capture.get('capture_hashes'):
|
||||
raise ValueError('Missing saved source capture')
|
||||
for relative, digest in capture['capture_hashes'].items():
|
||||
if _hash(Path(capture['root']) / relative) != digest:
|
||||
raise ValueError('Saved source capture changed before export')
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _export_workspace(result):
|
||||
work = Path(tempfile.mkdtemp(prefix='dx-net-'))
|
||||
try:
|
||||
yield work
|
||||
except TaskCenterError as error:
|
||||
if error.code == 'inventory_cleanup':
|
||||
result.update(workspace_preserved=str(work), cleanup_uncertain=True)
|
||||
raise
|
||||
finally:
|
||||
if not result.get('cleanup_uncertain'):
|
||||
shutil.rmtree(work)
|
||||
|
||||
|
||||
def _instance_identity(uid, path):
|
||||
if path in ('', 'root'):
|
||||
return uid
|
||||
if not re.fullmatch(r'\$\d+I\d+(?:/\$\d+I\d+)*', path):
|
||||
raise ValueError('Unsupported or ambiguous native instance path')
|
||||
return path + '/' + uid
|
||||
|
||||
|
||||
def _is_pcb(component):
|
||||
symbol = component.get('symbol')
|
||||
return 'ForwardPCB' in symbol.split() if symbol is not None else bool(component['attributes'].get('Part Number'))
|
||||
|
||||
|
||||
def _parse_ascii(path, *, hierarchy_boundaries=(), require_connections=True):
|
||||
text = read_native_text(path)
|
||||
_require_report(text, 'FLAT BLOCKS')
|
||||
if require_connections and re.findall(r'^\s*CONNECTION LISTS:\s*(\S+)', text, re.MULTILINE) != ['ON']:
|
||||
raise ValueError('Complete connection lists required')
|
||||
if len(re.findall(r'^Config .+', text, re.MULTILINE)) != 1:
|
||||
raise ValueError('Exactly one effective configuration required')
|
||||
components, nets, expected, symbols = {}, defaultdict(Counter), {}, []
|
||||
symbol = pin = net = conn = None
|
||||
for line in text.splitlines():
|
||||
if line.startswith(' Symbol '):
|
||||
match = re.fullmatch(r' Symbol (.+?)\tref des ([^\t]*)\tpage [^\t]*', line)
|
||||
if not match:
|
||||
raise ValueError('Invalid effective symbol identity')
|
||||
symbol = {'uid': match[1], 'refdes': match[2], 'attributes': {}, 'pins': {}, 'paths': []}
|
||||
symbols.append(symbol)
|
||||
pin = None
|
||||
elif symbol is not None:
|
||||
if line.startswith('\tPath '):
|
||||
symbol['paths'].append(line[6:])
|
||||
elif line.startswith('\tSymbol name '):
|
||||
symbol['symbol'] = line[13:]
|
||||
elif line.startswith('\tProp '):
|
||||
# Property names contain spaces; native format separates only by known names.
|
||||
value = line[6:]
|
||||
known = ('Ref Designator', 'Part Number', 'Part Label', 'Part Name', 'Cell Name', 'Value')
|
||||
key = next((key for key in known if value == key or value.startswith(key + ' ')), None)
|
||||
if key is not None:
|
||||
attributes = symbol['attributes']
|
||||
ambiguous = symbol.get('ambiguous_attributes', {})
|
||||
item = value[len(key) + 1:]
|
||||
if key in attributes or key in ambiguous:
|
||||
if key in {'Ref Designator', 'Part Number'}:
|
||||
raise ValueError('Duplicate effective identity attribute')
|
||||
if key not in ambiguous:
|
||||
ambiguous = symbol.setdefault('ambiguous_attributes', {})
|
||||
ambiguous[key] = [attributes.pop(key)]
|
||||
ambiguous[key].append(item)
|
||||
ambiguous[key].sort()
|
||||
else:
|
||||
attributes[key] = item
|
||||
else:
|
||||
symbol.setdefault('other_attributes', []).append(value)
|
||||
elif line.startswith('\tPin '):
|
||||
fields = line[5:].split('\t')
|
||||
pin = fields[0]
|
||||
if pin in symbol['pins']:
|
||||
raise ValueError('Duplicate effective pin')
|
||||
symbol['pins'][pin] = {'number': next((v[4:] for v in fields[1:] if v.startswith('num ')), ''), 'nets': []}
|
||||
elif line.startswith('\t\tConn net '):
|
||||
if pin is None:
|
||||
raise ValueError('Connection without pin')
|
||||
symbol['pins'][pin]['nets'].append(line[11:])
|
||||
elif line.startswith('\tNet '):
|
||||
net = line[5:]
|
||||
if not net or net in expected:
|
||||
raise ValueError('Duplicate or empty net')
|
||||
expected[net] = Counter()
|
||||
elif line.startswith('\t\tConn '):
|
||||
match = re.fullmatch(r'\t\tConn (.+?) pin (.+?) page .*', line)
|
||||
if net is None or not match:
|
||||
raise ValueError('Invalid net endpoint')
|
||||
conn = match.groups()
|
||||
elif line.startswith('\t\tPath '):
|
||||
path_value = line[7:]
|
||||
if conn is None or not path_value:
|
||||
raise ValueError('Endpoint missing instance path')
|
||||
conn = (_instance_identity(conn[0], path_value), conn[1])
|
||||
expected[net][conn] += 1
|
||||
conn = None
|
||||
if conn is not None:
|
||||
raise ValueError('Endpoint missing path')
|
||||
for symbol in symbols:
|
||||
uid = symbol.pop('uid')
|
||||
paths = symbol.pop('paths')
|
||||
if len(paths) != 1:
|
||||
raise ValueError('Symbol instance path is missing or ambiguous')
|
||||
source_uid = uid
|
||||
uid = _instance_identity(uid, paths[0])
|
||||
attrs = symbol['attributes']
|
||||
if paths[0]:
|
||||
symbol.update(instance_path=paths[0], source_uid=source_uid, source_refdes=symbol['refdes'])
|
||||
symbol['refdes'] = attrs.get('Ref Designator', '')
|
||||
elif attrs.get('Ref Designator') and attrs['Ref Designator'] != symbol['refdes']:
|
||||
symbol['source_refdes'], symbol['refdes'] = symbol['refdes'], attrs['Ref Designator']
|
||||
if _is_pcb(symbol) and (not re.fullmatch(r'\$\d+I\d+', source_uid) or not symbol['refdes'] or attrs.get('Ref Designator') != symbol['refdes']):
|
||||
raise ValueError(f'PCB component identity is ambiguous: {uid!r} / {symbol["refdes"]!r}')
|
||||
symbol['other_attributes'] = sorted(symbol.get('other_attributes', []))
|
||||
if uid in components:
|
||||
old = components[uid]
|
||||
if (re.fullmatch(r'\$\d+I\d+', source_uid) or symbol['refdes'] or old['refdes']
|
||||
or attrs.get('Part Number') or old['attributes'].get('Part Number')
|
||||
or 'ForwardPCB' in symbol.get('symbol', '')
|
||||
or old.get('symbol') != symbol.get('symbol') or old['pins'] != symbol['pins']):
|
||||
raise ValueError('Duplicate or ambiguous electrical symbol identity within native instance path')
|
||||
instances = old.get('annotation_instances', [old]) + [symbol]
|
||||
components[uid] = {'refdes': '', 'attributes': {}, 'pins': symbol['pins'],
|
||||
'symbol': symbol.get('symbol'),
|
||||
'annotation_instances': sorted(instances, key=lambda row: json.dumps(row, sort_keys=True))}
|
||||
else:
|
||||
components[uid] = symbol
|
||||
for pin, row in symbol['pins'].items():
|
||||
if len(row['nets']) > 1:
|
||||
raise ValueError('Pin has multiple nets')
|
||||
for net in row['nets']:
|
||||
nets[net][(uid, pin)] += 1
|
||||
for name, endpoints in expected.items():
|
||||
for (uid, port), count in list(endpoints.items()):
|
||||
if uid not in hierarchy_boundaries:
|
||||
continue
|
||||
child_port = components.get(uid + '/' + port)
|
||||
if (count != 1 or child_port is None or _is_pcb(child_port)
|
||||
or len(child_port['pins']) != 1
|
||||
or next(iter(child_port['pins'].values()))['nets'] != [name]
|
||||
or 'boundary_endpoint' in child_port):
|
||||
raise ValueError('Native hierarchy boundary lacks a unique reciprocal named port')
|
||||
child_port['boundary_endpoint'] = [uid, port, name]
|
||||
del endpoints[(uid, port)]
|
||||
if not components or (require_connections and (not nets or dict(nets) != dict(expected))):
|
||||
mismatched = [name for name in set(nets) | set(expected) if nets.get(name) != expected.get(name)]
|
||||
raise ValueError(f'ASCII reciprocal net/pin coverage is missing or incomplete: {sorted(mismatched)[:5]}')
|
||||
return components, {net: set(endpoints) for net, endpoints in nets.items()}
|
||||
|
||||
|
||||
def _parse_keyin(path):
|
||||
text = read_native_text(path)
|
||||
if '%net' not in text or '%Part' not in text:
|
||||
raise ValueError('Keyin net/part sections missing')
|
||||
nets, parts = defaultdict(set), {}
|
||||
mode = current = part_number = None
|
||||
for raw in text.splitlines():
|
||||
line = raw.strip()
|
||||
if line == '%net':
|
||||
mode = 'net'
|
||||
elif line == '%Part':
|
||||
mode = 'part'
|
||||
elif not line or line.startswith((';;', '%Prior=', '%page=')):
|
||||
continue
|
||||
elif line.startswith('%'):
|
||||
raise ValueError('Unknown Keyin section')
|
||||
elif mode == 'net':
|
||||
if line.startswith('*'):
|
||||
if current is None:
|
||||
raise ValueError('Orphan Keyin continuation')
|
||||
rest = line[1:]
|
||||
else:
|
||||
match = re.match(r'^\\([^\\]+)\\(.*)$', line)
|
||||
if not match:
|
||||
raise ValueError('Invalid Keyin net')
|
||||
current, rest = match.groups()
|
||||
endpoints = re.findall(r'\\([^\\]+)\\-\\([^\\]+)\\', rest)
|
||||
if not endpoints or re.sub(r'\\([^\\]+)\\-\\([^\\]+)\\', '', rest).strip():
|
||||
raise ValueError('Invalid Keyin endpoint')
|
||||
nets[current].update(endpoints)
|
||||
elif mode == 'part':
|
||||
continuation = line.startswith('*')
|
||||
if continuation:
|
||||
if part_number is None:
|
||||
raise ValueError('Orphan Keyin part continuation')
|
||||
line = line[1:].strip()
|
||||
values = re.findall(r'\\([^\\]*)\\', line)
|
||||
if len(values) < (1 if continuation else 2) or re.sub(r'\\([^\\]*)\\', '', line).strip():
|
||||
raise ValueError('Invalid Keyin part record')
|
||||
if not continuation:
|
||||
part_number, values = values[0], values[1:]
|
||||
for ref in values:
|
||||
if not ref or ref in parts:
|
||||
raise ValueError('Duplicate Keyin part reference')
|
||||
parts[ref] = part_number
|
||||
else:
|
||||
raise ValueError('Keyin content outside sections')
|
||||
if not nets or not parts:
|
||||
raise ValueError('Empty Keyin graph')
|
||||
return nets, parts
|
||||
|
||||
|
||||
def read_graph(ascii_path, keyin_path, *, hierarchy_path=None, root_block=None):
|
||||
boundaries = _check_hierarchy_graph(hierarchy_path, None, root_block)[1] if hierarchy_path is not None else ()
|
||||
components, nets = _parse_ascii(ascii_path, hierarchy_boundaries=boundaries)
|
||||
keyin, parts = _parse_keyin(keyin_path)
|
||||
expected_parts, expected_nets, physical_pins = {}, defaultdict(set), set()
|
||||
for uid, component in components.items():
|
||||
attrs, ref = component['attributes'], component['refdes']
|
||||
if not _is_pcb(component):
|
||||
continue
|
||||
part = attrs.get('Part Number', '')
|
||||
if not ref or (ref in expected_parts and expected_parts[ref] != part):
|
||||
raise ValueError('PCB references are missing or ambiguous')
|
||||
expected_parts[ref] = part
|
||||
for pin, row in component['pins'].items():
|
||||
physical = (ref, row['number'])
|
||||
if row['number'] and physical in physical_pins:
|
||||
raise ValueError('PCB physical pin identity overlaps between symbol slots')
|
||||
physical_pins.add(physical)
|
||||
if row['nets'] and not row['number']:
|
||||
raise ValueError('Physical pin number missing')
|
||||
for net in row['nets']:
|
||||
expected_nets[net].add((ref, row['number']))
|
||||
connected_refs = {ref for endpoints in keyin.values() for ref, pin in endpoints}
|
||||
isolated_empty = sorted(ref for ref, part in parts.items()
|
||||
if not part and ref not in expected_parts and ref not in connected_refs)
|
||||
if dict(expected_nets) != dict(keyin) or set(expected_parts) != set(parts) - set(isolated_empty):
|
||||
raise ValueError('ASCII/Keyin component or physical endpoint coverage differs')
|
||||
graph = {'components': components,
|
||||
'identity_tables': {'keyin': {'part_numbers': parts,
|
||||
'isolated_empty_parts': isolated_empty,
|
||||
'part_number_differences': [{'refdes': ref, 'effective_ascii': expected_parts[ref], 'keyin': parts[ref]}
|
||||
for ref in sorted(expected_parts) if expected_parts[ref] != parts[ref]]}},
|
||||
'nets': [{'name': net, 'endpoints': [list(endpoint) for endpoint in sorted(endpoints)]}
|
||||
for net, endpoints in sorted(nets.items())]}
|
||||
if hierarchy_path is not None:
|
||||
_check_hierarchy_graph(hierarchy_path, graph, root_block)
|
||||
return graph
|
||||
|
||||
|
||||
def _check_hierarchy_graph(path, graph, root_block):
|
||||
"""Expand native child links independently; inventory UID selectors stay root-only."""
|
||||
text = read_native_text(path)
|
||||
_require_report(text, 'HIER BLOCKS')
|
||||
blocks, roots, block = {}, [], None
|
||||
for line in text.splitlines():
|
||||
if line.startswith('Block '):
|
||||
fields = line[6:].split('\t')
|
||||
block = fields[0].rstrip()
|
||||
if not block or block in blocks:
|
||||
raise ValueError('Duplicate or missing native hierarchy block')
|
||||
blocks[block] = {'children': {}, 'symbols': Counter()}
|
||||
if fields[1:] == ['Root']:
|
||||
roots.append(block)
|
||||
elif line.startswith('\tChild '):
|
||||
match = re.fullmatch(r'\tChild (.+)\.\d+\tinstance name (\$\d+I\d+)\tview .*', line)
|
||||
if block is None or match is None or match[2] in blocks[block]['children']:
|
||||
raise ValueError('Ambiguous native hierarchy child')
|
||||
blocks[block]['children'][match[2]] = match[1]
|
||||
elif line.startswith(' Symbol '):
|
||||
match = re.fullmatch(r' Symbol (.+?)\tpage (.+)', line)
|
||||
if block is None or match is None:
|
||||
raise ValueError('Ambiguous native hierarchy symbol')
|
||||
blocks[block]['symbols'][match[1]] += 1
|
||||
if roots != [root_block]:
|
||||
raise ValueError('Native hierarchy root differs from captured project')
|
||||
identities, boundaries = Counter(), set()
|
||||
|
||||
pending = [(root_block, '', set())]
|
||||
while pending:
|
||||
name, path, ancestors = pending.pop()
|
||||
if name not in blocks or name in ancestors:
|
||||
raise ValueError('Native hierarchy is incomplete or recursive')
|
||||
row = blocks[name]
|
||||
identities.update({_instance_identity(uid, path): count for uid, count in row['symbols'].items()
|
||||
if uid not in row['children']})
|
||||
for uid, child in row['children'].items():
|
||||
if uid not in row['symbols']:
|
||||
raise ValueError('Native hierarchy child symbol missing')
|
||||
identity = _instance_identity(uid, path)
|
||||
boundaries.add(identity)
|
||||
pending.append((child, identity, ancestors | {name}))
|
||||
if graph is not None:
|
||||
effective = Counter({uid: len(row.get('annotation_instances', [row])) for uid, row in graph['components'].items()})
|
||||
if identities != effective:
|
||||
raise ValueError('Hierarchical/effective instance coverage differs')
|
||||
return identities, boundaries
|
||||
|
||||
|
||||
def export_netlist(capture: dict, output: Path, *, stop_event=None) -> dict:
|
||||
output = Path(output)
|
||||
result = {'status': 'failed', 'complete': False, 'capture': capture, 'outputs': {}, 'runs': [],
|
||||
'coverage_limits': [_VALUE_COVERAGE]}
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
check_cancelled(stop_event)
|
||||
_check_capture(capture)
|
||||
root = installation_root()
|
||||
ascii_tool, keyin_tool = root / 'iCDB/win32/bin/icdb2ascii.exe', root / 'wv/win32/bin/KeyinNetlist.exe'
|
||||
if not ascii_tool.is_file() or not keyin_tool.is_file():
|
||||
raise ValueError('Native ASCII/Keyin tools unavailable')
|
||||
with _export_workspace(result) as work:
|
||||
for relative in capture['capture_hashes']:
|
||||
target = work / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(internal_path(Path(capture['root']) / relative), target)
|
||||
if _hash(target) != capture['capture_hashes'][relative]:
|
||||
raise ValueError('Capture changed while preparing native export')
|
||||
db, project = work / 'database', work / 'input.prj'
|
||||
for mode in ('hier', 'effective', 'keyin'):
|
||||
target = work / ('design.kyn' if mode == 'keyin' else mode + '.txt')
|
||||
if mode == 'keyin':
|
||||
command = (str(keyin_tool), '-block=' + capture['root_block'], '-icdbdir=' + str(db),
|
||||
'-icdbsnapshot=' + capture['snapshot'], '-flowtype=DX', '-out=' + str(target))
|
||||
else:
|
||||
command = (str(ascii_tool), '-project=' + str(project), '-icdb=' + str(db),
|
||||
'-snap=' + capture['snapshot'], '-h' if mode == 'hier' else '-f',
|
||||
'-t', '-c', '-offline', '-file=' + str(target))
|
||||
metric = {'command': list(command), 'tool_sha256': _hash(Path(command[0]))}
|
||||
result['runs'].append(metric)
|
||||
with OwnedCliScope() as scope:
|
||||
with (output / (mode + '.stdout.txt')).open('wb') as stdout, (output / (mode + '.stderr.txt')).open('wb') as stderr:
|
||||
process = scope.start_process(command, cwd=work, env=environment(root), stdout=stdout, stderr=stderr)
|
||||
started = time.monotonic()
|
||||
while process.poll() is None:
|
||||
check_cancelled(stop_event)
|
||||
if time.monotonic() - started >= 120:
|
||||
raise ValueError('Native netlist export timed out')
|
||||
time.sleep(0.05)
|
||||
metric['exit_code'] = process.poll()
|
||||
if metric['exit_code'] != 0:
|
||||
raise ValueError(f'Native {mode} export failed: {metric["exit_code"]}')
|
||||
metric['cleanup'] = scope.cleanup_record
|
||||
if not target.is_file():
|
||||
raise ValueError('Native output missing')
|
||||
destination = output / target.name
|
||||
shutil.copyfile(target, destination)
|
||||
result['outputs'][mode] = str(destination)
|
||||
_check_capture(capture)
|
||||
result['graph'] = read_graph(Path(result['outputs']['effective']), Path(result['outputs']['keyin']),
|
||||
hierarchy_path=Path(result['outputs']['hier']), root_block=capture['root_block'])
|
||||
result.update(status='success', complete=True)
|
||||
_write_json(output / 'graph.json', result['graph'])
|
||||
result['outputs']['graph'] = str(output / 'graph.json')
|
||||
except Exception as error:
|
||||
result.update(status='cancelled' if isinstance(error, TaskCenterError) and error.code == 'operation_cancelled' else 'failed', reason=str(error))
|
||||
_write_json(output / 'netlist.json', result)
|
||||
return result
|
||||
|
||||
|
||||
def _proven_symbol(old, new, proof):
|
||||
if type(proof.get('slot_count')) is not int or proof['slot_count'] < 1:
|
||||
return False
|
||||
expected = re.fullmatch(r'(?:[^:\s]+:)?([^:\s]+?)(?:\.(\d+))?', proof.get('target_symbol', ''))
|
||||
actual = re.fullmatch(r'([^\s]+?)\.(\d+) type (.+?)\s*', new.get('symbol', ''))
|
||||
original = re.fullmatch(r'([^\s]+?)\.(\d+) type (.+?)\s*', old.get('symbol', ''))
|
||||
return bool(expected and actual and original and expected[1] == actual[1]
|
||||
and (expected[2] is None or expected[2] == actual[2])
|
||||
and 1 <= int(actual[2]) <= proof['slot_count']
|
||||
and original[3] == actual[3])
|
||||
|
||||
|
||||
def _physical_pins(component):
|
||||
pins = component.get('pins')
|
||||
if not pins or any(not row.get('number') for row in pins.values()):
|
||||
return None
|
||||
return sorted((row['number'], json.dumps(row, sort_keys=True)) for row in pins.values())
|
||||
|
||||
|
||||
def _connections(graph):
|
||||
nets = []
|
||||
for row in graph['nets']:
|
||||
endpoints = []
|
||||
for uid, pin in row['endpoints']:
|
||||
component = graph['components'].get(uid)
|
||||
if component is not None and _is_pcb(component) and 'pins' in component:
|
||||
pin = component['pins'][pin]['number']
|
||||
if not pin:
|
||||
raise ValueError('Connected PCB endpoint lacks physical pin number')
|
||||
endpoints.append((uid, pin))
|
||||
nets.append((row['name'], sorted(endpoints)))
|
||||
return sorted(nets)
|
||||
|
||||
|
||||
def compare_netlists(before: dict, after: dict, *, expected_changes=None, expected_symbols=None) -> dict:
|
||||
for result in (before, after):
|
||||
graph = result.get('graph', {})
|
||||
if result.get('status') != 'success' or result.get('complete') is not True or not graph.get('components') or not graph.get('nets'):
|
||||
return {'status': 'unavailable', 'verified': False, 'reason': 'Complete nonempty native graphs required'}
|
||||
left, right = before['graph'], after['graph']
|
||||
differences = []
|
||||
try:
|
||||
connections_changed = _connections(left) != _connections(right)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return {'status': 'unavailable', 'verified': False, 'reason': 'Physical endpoint mapping is incomplete'}
|
||||
if connections_changed:
|
||||
differences.append({'field': 'connections', 'reason': 'Net endpoints changed'})
|
||||
if set(left['components']) != set(right['components']):
|
||||
differences.append({'field': 'components', 'reason': 'Stable component identities changed'})
|
||||
expected_changes = expected_changes or {}
|
||||
expected_symbols = expected_symbols or {}
|
||||
for uid in set(left['components']) | set(right['components']) | set(expected_changes) | set(expected_symbols):
|
||||
old, new = left['components'].get(uid), right['components'].get(uid)
|
||||
if old is None or new is None:
|
||||
differences.append({'uid': uid, 'reason': 'Expected component missing'})
|
||||
continue
|
||||
expected = dict(old['attributes'])
|
||||
declared = expected_changes.get(uid, {})
|
||||
if not set(declared) <= {'Part Number', 'Value', 'Cell Name', 'Part Name', 'Part Label'}:
|
||||
differences.append({'uid': uid, 'reason': 'Unsupported declared attribute'})
|
||||
for name, value in declared.items():
|
||||
if value is None:
|
||||
expected.pop(name, None)
|
||||
else:
|
||||
expected[name] = value
|
||||
if new['attributes'] != expected:
|
||||
differences.append({'uid': uid, 'field': 'attributes', 'expected': expected, 'actual': new['attributes']})
|
||||
proof = expected_symbols.get(uid)
|
||||
proven = proof is not None and uid in expected_changes and _proven_symbol(old, new, proof)
|
||||
if proof is not None and not proven:
|
||||
differences.append({'uid': uid, 'field': 'symbol', 'reason': 'Transaction target symbol could not be matched'})
|
||||
for key in set(old) | set(new):
|
||||
if key == 'ambiguous_attributes':
|
||||
old_ambiguous = {name: values for name, values in old.get(key, {}).items() if name not in declared}
|
||||
if old_ambiguous != new.get(key, {}):
|
||||
differences.append({'uid': uid, 'field': key, 'reason': 'Undeclared or unresolved duplicate attribute values'})
|
||||
continue
|
||||
if proven and key == 'symbol':
|
||||
continue
|
||||
if proven and key == 'pins':
|
||||
old_pins, new_pins = _physical_pins(old), _physical_pins(new)
|
||||
if old_pins is None or new_pins is None or old_pins != new_pins:
|
||||
differences.append({'uid': uid, 'field': 'pins', 'reason': 'Physical pins or their nets changed'})
|
||||
continue
|
||||
if key != 'attributes' and old.get(key) != new.get(key):
|
||||
differences.append({'uid': uid, 'field': key, 'reason': 'Undeclared component data changed'})
|
||||
return {'status': 'different' if differences else 'verified', 'verified': not differences,
|
||||
'differences': differences, 'coverage_limits': [_VALUE_COVERAGE]}
|
||||
@@ -0,0 +1,381 @@
|
||||
"""Overlap native exports with replacement, keeping each saved input immutable."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import asdict
|
||||
import json
|
||||
import hashlib
|
||||
import marshal
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from . import native_netlist
|
||||
from .batch_resources import write_record
|
||||
|
||||
|
||||
def _export_saved_capture(capture, directory, *, stop_event):
|
||||
"""Reuse intact exports of an immutable baseline, including on resume."""
|
||||
manifest = directory / 'netlist.json'
|
||||
cache = directory / 'export-cache.json'
|
||||
code = native_netlist.__loader__.get_code(native_netlist.__name__)
|
||||
parser_digest = hashlib.sha256(marshal.dumps(code)).hexdigest()
|
||||
try:
|
||||
native_netlist._check_capture(capture)
|
||||
proof = json.loads(cache.read_text(encoding='utf-8'))
|
||||
result = json.loads(manifest.read_text(encoding='utf-8'))
|
||||
if (proof['parser'] == parser_digest and proof['result'] == native_netlist._hash(manifest)
|
||||
and result['capture'] == capture and result['status'] == 'success' and result['complete'] is True
|
||||
and proof['outputs'] and all(native_netlist._hash(directory / name) == digest
|
||||
for name, digest in proof['outputs'].items())
|
||||
and result['runs'] and all(native_netlist._hash(Path(run['command'][0])) == run['tool_sha256']
|
||||
for run in result['runs'])):
|
||||
return result
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
pass
|
||||
result = native_netlist.export_netlist(capture, directory, stop_event=stop_event)
|
||||
if result.get('status') == 'success' and result.get('complete') and manifest.is_file():
|
||||
try:
|
||||
outputs = {Path(path).resolve().relative_to(directory.resolve()).as_posix(): native_netlist._hash(Path(path))
|
||||
for path in result['outputs'].values()}
|
||||
write_record(cache, {'parser': parser_digest, 'result': native_netlist._hash(manifest), 'outputs': outputs})
|
||||
except (OSError, ValueError):
|
||||
pass # A cache write failure does not invalidate the completed export.
|
||||
return result
|
||||
|
||||
|
||||
def library_from_receipt(command, receipt):
|
||||
"""Read selected library identity from the already committed native proof."""
|
||||
if receipt.get('native_state') not in {'saved_ok', 'restored_ok'}:
|
||||
return {}
|
||||
from .execution_proof import proof_intact
|
||||
from .native_helper import read_snapshot, require_resumable_transaction
|
||||
from .path_access import canonical_path, internal_path
|
||||
proof = receipt.get('proof', {})
|
||||
native_files = [Path(item['path']) for item in proof.get('files', ())
|
||||
if item['path'].endswith('.native.json')]
|
||||
if not native_files:
|
||||
return {}
|
||||
if not proof_intact(proof):
|
||||
raise ValueError('原生库件回执证据已变化,无法独立核验')
|
||||
paths = {str(Path(item['path'])) for item in proof['files']}
|
||||
result = {}
|
||||
for path in native_files:
|
||||
snapshot = Path(str(path).removesuffix('.native.json'))
|
||||
if str(snapshot) not in paths:
|
||||
raise ValueError('原生库件证据缺少配套快照')
|
||||
report = json.loads(internal_path(path).read_text(encoding='utf-8'))
|
||||
if report.get('ok') is not True or report.get('stage') != 'native_replace_verified':
|
||||
raise ValueError('原生库件回执未通过实际替换核验')
|
||||
metadata, records = read_snapshot(snapshot)
|
||||
binding = require_resumable_transaction(snapshot, report, metadata, records)
|
||||
if (canonical_path(metadata[1]) != canonical_path(command['project_path'])
|
||||
or metadata[2:4] != [command['old_part'], command['new_part']]
|
||||
or metadata[4] != f"{command['schematic_name']}:{command['sheet_number']}"):
|
||||
raise ValueError('原生库件证据属于不同执行项')
|
||||
row = binding['library_row']
|
||||
if row[1].casefold() != command['new_part'].casefold() or not row[4]:
|
||||
raise ValueError('原生库件证据与目标料号不符')
|
||||
readback = proof.get('value_readback', {})
|
||||
values = {}
|
||||
if readback.get('value_readback_status') == 'verified':
|
||||
if (readback.get('value_readback_job_id') != receipt.get('job_id')
|
||||
or canonical_path(readback.get('project_path', '')) != canonical_path(command['project_path'])
|
||||
or readback.get('schematic_name') != command['schematic_name']
|
||||
or readback.get('sheet_number') != command['sheet_number']):
|
||||
raise ValueError('Value 回读证据属于不同执行项')
|
||||
observations = readback.get('value_readback', ())
|
||||
values = {value['uid']: value for value in observations}
|
||||
if len(values) != len(observations) or set(values) != set(binding['source_uids']):
|
||||
raise ValueError('Value 回读证据的器件范围不完整')
|
||||
for uid in binding['source_uids']:
|
||||
identity = {'attributes': {'Part Number': row[1], 'Part Name': row[4], 'Part Label': row[5]},
|
||||
'target_symbol': binding['target_symbol'], 'slot_count': binding['slot_count']}
|
||||
if uid in values:
|
||||
value = values[uid]
|
||||
if (value['actual_part_number'].casefold() != row[1].casefold()
|
||||
or not isinstance(value['actual_value'], str)
|
||||
or type(value['actual_value_present']) is not bool):
|
||||
raise ValueError('Value 回读证据与目标库件不符')
|
||||
identity.update(preserved_value=value['actual_value'],
|
||||
preserved_value_present=value['actual_value_present'])
|
||||
if uid in result and result[uid] != identity:
|
||||
raise ValueError('原生库件证据的 UID 对应多个目标')
|
||||
result[uid] = identity
|
||||
return result
|
||||
|
||||
|
||||
def _library_expectations(child, task_id):
|
||||
store = getattr(child, '_store', None)
|
||||
if store is None:
|
||||
return {}
|
||||
with store._lock:
|
||||
rows = tuple(store._connection.execute('''SELECT o.command_json, o.receipt_json
|
||||
FROM execution_operations o JOIN execution_rounds r
|
||||
ON r.task_id=o.task_id AND r.round_id=o.round_id
|
||||
WHERE o.task_id=? AND o.state='verified' ''', (task_id,)))
|
||||
result = {}
|
||||
for row in rows:
|
||||
identities = library_from_receipt(json.loads(row['command_json']), json.loads(row['receipt_json']))
|
||||
for uid, identity in identities.items():
|
||||
if uid in result and result[uid] != identity:
|
||||
raise ValueError('当前轮次的原生库件证据存在冲突')
|
||||
result[uid] = identity
|
||||
return result
|
||||
|
||||
|
||||
def verification_summary(reports, *, required_task_ids=()):
|
||||
"""Keep independent acceptance separate from the executor's saved receipts."""
|
||||
reports = reports or {}
|
||||
statuses = {task_id: ('verified' if report.get('status') == 'verified' and report.get('verified') is True
|
||||
else 'different' if report.get('status') == 'different' else 'unavailable')
|
||||
for task_id, report in reports.items() if report.get('status') != 'not_required'}
|
||||
for task_id in required_task_ids:
|
||||
statuses.setdefault(task_id, 'unavailable')
|
||||
status = ('not_required' if not statuses else 'different' if 'different' in statuses.values()
|
||||
else 'unavailable' if 'unavailable' in statuses.values() else 'verified')
|
||||
return {'status': status, 'verified': status == 'verified', 'tasks': statuses}
|
||||
|
||||
|
||||
def _rule_policy(command):
|
||||
return {name: str(command.get(name, default)).casefold() if name in {'old_part', 'new_part'}
|
||||
else str(command.get(name, default))
|
||||
for name, default in (('old_part', ''), ('new_part', ''), ('value_mode', 'preserve'),
|
||||
('custom_value', ''), ('sync_nc', '1'), ('target_cell', ''))}
|
||||
|
||||
|
||||
def _rule_rows(child, task_id, plan, before):
|
||||
"""Expand frozen rules only through actual operation-bound native snapshots."""
|
||||
from .path_access import canonical_path
|
||||
with child._store._lock:
|
||||
receipts = tuple(child._store._connection.execute('''SELECT o.command_json,o.receipt_json
|
||||
FROM execution_operations o JOIN execution_rounds r
|
||||
ON r.task_id=o.task_id AND r.round_id=o.round_id
|
||||
WHERE o.task_id=? AND o.state='verified' ORDER BY o.rowid''', (task_id,)))
|
||||
rows, scopes = {}, []
|
||||
for receipt in receipts:
|
||||
command, value = json.loads(receipt['command_json']), json.loads(receipt['receipt_json'])
|
||||
if value.get('native_state') not in {'saved_ok', 'restored_ok'}:
|
||||
continue
|
||||
if (canonical_path(command['project_path']) != canonical_path(plan['project_path'])
|
||||
or _rule_policy(command) not in plan['rules']):
|
||||
raise ValueError('实际执行命令不属于替换前冻结的料号规则')
|
||||
selector = None
|
||||
if command.get('target_scope', 'all') == 'all':
|
||||
if command.get('target_selectors'):
|
||||
raise ValueError('整规则执行包含不匹配的位号范围')
|
||||
elif command.get('target_scope') == 'targets' and command.get('execution_unit') == 'component':
|
||||
selectors = command.get('target_selectors', '').split('\x1e')
|
||||
selector = selectors[0].split('\x1f')
|
||||
if len(selectors) != 1 or len(selector) != 3:
|
||||
raise ValueError('规则展开缺少单个位号的完整选择器')
|
||||
else:
|
||||
raise ValueError('规则执行范围无法与原生回执绑定')
|
||||
identities = library_from_receipt(command, value)
|
||||
if not identities:
|
||||
raise ValueError('规则替换缺少绑定实际 sheet/UID 的原生事务证据')
|
||||
if selector is not None:
|
||||
original = before['graph']['components'].get(selector[0], {})
|
||||
if (set(identities) != {selector[0]} or original.get('refdes') != selector[1]
|
||||
or original.get('attributes', {}).get('Value', '') != selector[2]):
|
||||
raise ValueError('规则位号选择器与替换前器件及原生 UID 范围不一致')
|
||||
scopes.append({key: command.get(key, '') for key in
|
||||
('project_path', 'schematic_name', 'sheet_number', 'old_part', 'new_part')}
|
||||
| {'source_uids': sorted(identities)})
|
||||
for uid in identities:
|
||||
component = before['graph']['components'].get(uid)
|
||||
if component is None or component['attributes'].get('Part Number', '').casefold() != command['old_part'].casefold():
|
||||
raise ValueError('原生 UID 无法唯一对应替换前的原料号;不能按同料号猜测图页')
|
||||
row = {'enabled': True, 'target': {'uid': uid, 'old_value': component['attributes'].get('Value', '')},
|
||||
'new_part_number': command['new_part'], 'value_mode': command['value_mode'],
|
||||
'custom_value_enabled': command['value_mode'] == 'custom',
|
||||
'custom_value': command.get('custom_value', ''), 'sync_nc': command.get('sync_nc', '1') == '1',
|
||||
'target_cell': command.get('target_cell', '')}
|
||||
if uid in rows and rows[uid] != row:
|
||||
raise ValueError('同一 UID 对应多个不同规则结果,不能独立核验')
|
||||
rows[uid] = row
|
||||
if not rows:
|
||||
raise ValueError('已保存的规则替换缺少可核验的原生 UID 事务')
|
||||
return list(rows.values()), scopes
|
||||
|
||||
|
||||
class NetlistVerification:
|
||||
def __init__(self, root, run_id, stop_event):
|
||||
self.root, self.run_id, self.stop = Path(root), run_id, stop_event
|
||||
self.pool = ThreadPoolExecutor(max_workers=2, thread_name_prefix='native-netlist')
|
||||
self.tasks, self.results = {}, {}
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def before_task(self, child, task_id, *, existing_only=False):
|
||||
if task_id in self.tasks:
|
||||
return
|
||||
directory = self.root / 'tasks' / task_id / 'netlist-checks' / self.run_id
|
||||
if existing_only and not ((directory / 'before' / 'capture.json').is_file()
|
||||
and (directory / 'plan.json').is_file()):
|
||||
return
|
||||
rows = tuple(child.target_plan(task_id))
|
||||
task = child.get_task(task_id)
|
||||
rules = (tuple(rule for rule in child.rules(task_id) if rule.enabled)
|
||||
if not rows and getattr(task, 'target_plan_mode', None) is False else ())
|
||||
if not rows and not rules and not (directory / 'plan.json').is_file():
|
||||
return
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
record = {'directory': directory, 'status': 'exporting', 'verified': False, 'child': child,
|
||||
'rule_mode': bool(rules)}
|
||||
self.tasks[task_id] = record
|
||||
try:
|
||||
before = directory / 'before'
|
||||
manifest = before / 'capture.json'
|
||||
plan_path = directory / 'plan.json'
|
||||
if manifest.is_file() and not plan_path.is_file():
|
||||
raise ValueError('原始网表基准缺少替换前冻结的计划,不能事后补造')
|
||||
# Resume always retains the original baseline, including a partially
|
||||
# replaced project; never relabel the resumed input as "before".
|
||||
capture = (json.loads(manifest.read_text(encoding='utf-8')) if manifest.is_file() else
|
||||
native_netlist.capture_project(child.projects(task_id)[0].path, before))
|
||||
if plan_path.is_file():
|
||||
plan = json.loads(plan_path.read_text(encoding='utf-8'))
|
||||
else:
|
||||
plan = {'rows': json.loads(json.dumps([asdict(row) for row in rows], default=str)),
|
||||
'copy_value': task.copy_part_number_to_value}
|
||||
if rules:
|
||||
from .quick_run import _rule_command_options
|
||||
frozen = []
|
||||
for rule in rules:
|
||||
mode, custom, sync, _ = _rule_command_options(rule, 'part_label' if plan['copy_value'] else 'preserve')
|
||||
frozen.append(_rule_policy({'old_part': rule.old_part_number, 'new_part': rule.new_part_number,
|
||||
'value_mode': mode, 'custom_value': custom, 'sync_nc': '1' if sync else '0',
|
||||
'target_cell': rule.target_cell}))
|
||||
plan.update(rules=frozen, project_path=capture['project'])
|
||||
write_record(plan_path, plan)
|
||||
record.update(plan=plan, before_capture=capture)
|
||||
record['before'] = self.pool.submit(_export_saved_capture, capture,
|
||||
directory / 'before-export', stop_event=self.stop)
|
||||
except Exception as error:
|
||||
record.update(status='unavailable', reason=str(error))
|
||||
|
||||
def after_task(self, task_id, *, execution_state='completed', execution_summary=None, refresh=False):
|
||||
record = self.tasks.get(task_id)
|
||||
if record is None:
|
||||
return
|
||||
record['execution_state'] = execution_state
|
||||
record['execution_summary'] = execution_summary or {}
|
||||
if ((record.get('rule_mode') or 'rules' in record.get('plan', {}))
|
||||
and record['execution_summary'].get('saved_items') == 0):
|
||||
record['status'] = 'not_required'
|
||||
return
|
||||
if record['status'] == 'unavailable':
|
||||
return
|
||||
if 'after' in record and not refresh:
|
||||
return
|
||||
try:
|
||||
record['library'] = _library_expectations(record['child'], task_id)
|
||||
directory = record['directory']
|
||||
attempt = uuid4().hex
|
||||
capture = native_netlist.capture_project(Path(record['before_capture']['project']),
|
||||
directory / ('after-' + attempt))
|
||||
record['after_capture'] = capture
|
||||
record['after'] = self.pool.submit(_export_saved_capture, capture,
|
||||
directory / ('after-export-' + attempt), stop_event=self.stop)
|
||||
except Exception as error:
|
||||
record.update(status='unavailable', reason=str(error))
|
||||
|
||||
@staticmethod
|
||||
def _expected(plan, after, library=None):
|
||||
expected = {}
|
||||
components = after.get('graph', {}).get('components', {})
|
||||
for row in plan['rows']:
|
||||
if not row['enabled']:
|
||||
continue
|
||||
target = row['target']
|
||||
uid = target['uid']
|
||||
part = row['new_part_number'].strip()
|
||||
attrs = {'Part Number': part}
|
||||
identity = (library or {}).get(uid, {}).get('attributes', {})
|
||||
if identity:
|
||||
if identity['Part Number'].casefold() != part.casefold():
|
||||
raise ValueError('库件回执与本次位号计划的目标不一致')
|
||||
attrs.update(identity)
|
||||
mode = 'custom' if row['custom_value_enabled'] else row.get('value_mode', 'inherit')
|
||||
if mode == 'inherit':
|
||||
mode = 'part_label' if plan['copy_value'] else 'preserve'
|
||||
if mode == 'part_label':
|
||||
label = identity.get('Part Label', components.get(uid, {}).get('attributes', {}).get('Part Label'))
|
||||
if label is None:
|
||||
raise ValueError('目标 Part Label 未取得,无法独立核验 Value')
|
||||
value = label
|
||||
elif mode == 'preserve' and identity:
|
||||
if 'preserved_value' not in (library or {}).get(uid, {}):
|
||||
raise ValueError('缺少已保存 Value 回读,无法独立核验原生保留策略')
|
||||
value = library[uid]['preserved_value']
|
||||
else:
|
||||
value = {'custom': row['custom_value'], 'part_number': part,
|
||||
'preserve': target['old_value']}[mode]
|
||||
has_nc = lambda text: '/' in text and any(part.strip().casefold() == 'nc' for part in text.split('/'))
|
||||
if row['sync_nc'] and has_nc(target['old_value']):
|
||||
value = value.rstrip(' ')
|
||||
if not has_nc(value):
|
||||
value += 'NC' if value.endswith('/') else '/NC'
|
||||
attrs['Value'] = value
|
||||
if row.get('target_cell'):
|
||||
attrs['Cell Name'] = row['target_cell']
|
||||
if uid in expected and expected[uid] != attrs:
|
||||
raise ValueError('同一 UID 对应多条不同替换策略,无法独立比对')
|
||||
expected[uid] = attrs
|
||||
return expected
|
||||
|
||||
def finish(self):
|
||||
for task_id, record in self.tasks.items():
|
||||
if task_id in self.results:
|
||||
continue
|
||||
result = {'status': record['status'], 'verified': False,
|
||||
'report_path': str(record['directory'] / 'verification.json')}
|
||||
if record['status'] == 'not_required':
|
||||
result['execution'] = dict(record.get('execution_summary', {}), state=record.get('execution_state'))
|
||||
write_record(Path(result['report_path']), result)
|
||||
self.results[task_id] = result
|
||||
continue
|
||||
try:
|
||||
# Collect the original export even on pause so its evidence is
|
||||
# durable before the owning queue process exits.
|
||||
before = record['before'].result() if 'before' in record else None
|
||||
after = record['after'].result() if 'after' in record else None
|
||||
if record.get('reason'):
|
||||
result['reason'] = record['reason']
|
||||
elif self.stop.is_set():
|
||||
result.update(status='cancelled', reason='任务已暂停或取消;未宣称网表比对通过')
|
||||
elif before is None or after is None:
|
||||
result.update(status='not_completed', reason='工程尚未完整执行;保留替换前基准')
|
||||
else:
|
||||
library = record.get('library', {})
|
||||
plan = record['plan']
|
||||
if 'rules' in plan:
|
||||
rows, scopes = _rule_rows(record['child'], task_id, plan, before)
|
||||
plan = dict(plan, rows=rows)
|
||||
result['rule_scopes'] = scopes
|
||||
expected = self._expected(plan, after, library)
|
||||
symbols = {uid: {key: item[key] for key in ('target_symbol', 'slot_count')}
|
||||
for uid, item in library.items() if uid in expected}
|
||||
comparison = native_netlist.compare_netlists(before, after, expected_changes=expected,
|
||||
expected_symbols=symbols)
|
||||
result.update(comparison, expected_changes=expected, expected_symbols=symbols,
|
||||
library_expectations=library)
|
||||
if record.get('execution_state') != 'completed':
|
||||
result.update(status='not_completed', verified=False, graph_comparison=comparison,
|
||||
reason='工程执行仍有失败,网表结果单独保留')
|
||||
elif record.get('execution_summary', {}).get('no_match_items', 0):
|
||||
result.update(status='not_replaced', verified=False, graph_comparison=comparison,
|
||||
reason='存在未命中项;网表一致不代表已执行替换')
|
||||
result['execution'] = dict(record.get('execution_summary', {}), state=record.get('execution_state'))
|
||||
result['before'] = before and {key: before.get(key) for key in ('status', 'complete', 'outputs', 'reason')}
|
||||
result['after'] = after and {key: after.get(key) for key in ('status', 'complete', 'outputs', 'reason')}
|
||||
except Exception as error:
|
||||
result.update(status='unavailable', reason=str(error))
|
||||
write_record(Path(result['report_path']), result)
|
||||
self.results[task_id] = result
|
||||
return self.results
|
||||
|
||||
def __exit__(self, *_):
|
||||
try:
|
||||
self.finish()
|
||||
finally:
|
||||
self.pool.shutdown(wait=True, cancel_futures=self.stop.is_set())
|
||||
@@ -33,36 +33,15 @@ def internal_path(value):
|
||||
return Path(windows_extended_path(value)) if os.name == 'nt' else Path(value)
|
||||
|
||||
|
||||
def _sharing_denial(error, target):
|
||||
if getattr(error, 'winerror', None) in (32, 33):
|
||||
return True
|
||||
if os.name != 'nt' or getattr(error, 'winerror', None) != 5 or target is None:
|
||||
return False
|
||||
# MoveFileEx can report ACCESS_DENIED for a reader denying delete sharing.
|
||||
# Confirm that specific condition, rather than retrying arbitrary ACL errors.
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
|
||||
create = kernel.CreateFileW
|
||||
create.argtypes = (wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p,
|
||||
wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE)
|
||||
create.restype = wintypes.HANDLE
|
||||
handle = create(str(internal_path(target)), 0x10000, 7, None, 3, 0, None)
|
||||
if handle == ctypes.c_void_p(-1).value:
|
||||
return ctypes.get_last_error() in (32, 33)
|
||||
close = kernel.CloseHandle
|
||||
close.argtypes = (wintypes.HANDLE,)
|
||||
close(handle)
|
||||
return False
|
||||
|
||||
|
||||
def retry_sharing_violation(operation, *, target=None, sleep=time.sleep):
|
||||
"""At most three attempts and 150ms delay; access denial is never replayed."""
|
||||
"""Repeat a filesystem operation at most three times with 150ms total delay."""
|
||||
for attempt in range(3):
|
||||
try:
|
||||
return operation()
|
||||
except OSError as error:
|
||||
if attempt == 2 or not _sharing_denial(error, target):
|
||||
# Windows also reports transient delete-sharing conflicts as 5;
|
||||
# the lock may already be gone when an additional probe runs.
|
||||
if attempt == 2 or getattr(error, 'winerror', None) not in (5, 32, 33):
|
||||
raise
|
||||
sleep(.05 * (attempt + 1))
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ class ProblemPassResult:
|
||||
message: str = ''
|
||||
|
||||
|
||||
def run_problem_pass(service, task_ids, queue_id, *, stop_event, runtime):
|
||||
def run_problem_pass(service, task_ids, queue_id, *, stop_event, runtime, on_result=None):
|
||||
results = {}
|
||||
for task_id in task_ids:
|
||||
if stop_event.is_set():
|
||||
@@ -26,12 +26,16 @@ def run_problem_pass(service, task_ids, queue_id, *, stop_event, runtime):
|
||||
return ProblemPassResult(results, task_id, error.code, error.message)
|
||||
if result is not None:
|
||||
results[task_id] = result
|
||||
if on_result is not None:
|
||||
on_result(task_id, result)
|
||||
if result.paused:
|
||||
break
|
||||
return ProblemPassResult(results)
|
||||
|
||||
|
||||
def _run_project_problems(service, task_id, queue_id, *, stop_event, runtime):
|
||||
if hasattr(runtime, 'begin_task'):
|
||||
runtime.begin_task(task_id)
|
||||
store = service._store
|
||||
child = service.for_project_task(task_id)
|
||||
if child.has_interrupted_quick_run(task_id):
|
||||
|
||||
@@ -26,4 +26,5 @@ class ProjectTaskContext:
|
||||
has_evidence: bool
|
||||
interrupted: bool
|
||||
legacy: bool
|
||||
pending_bom: tuple = ()
|
||||
|
||||
@@ -92,6 +92,12 @@ class ProjectSessionWorker:
|
||||
raise self._error
|
||||
if self._result.returncode == 0:
|
||||
raise WorkerMonitorError('project session exited before authorized closing')
|
||||
if self._result.returncode == 74:
|
||||
pause = getattr(self._result, 'startup_pause', {})
|
||||
if (pause.get('session_token') != self.token or pause.get('job_id') != job
|
||||
or Path(pause.get('project_path', '')).resolve() != self.project.resolve()
|
||||
or pause.get('worker_tree_exited') is not True):
|
||||
raise WorkerMonitorError('startup pause belongs to a different project session')
|
||||
self._failure_delivered = True
|
||||
return self._result
|
||||
stop_control = getattr(self.runtime, 'stop_event', None)
|
||||
@@ -121,21 +127,26 @@ class ProjectSessionWorker:
|
||||
_write_control(self.root / 'project-session-next.tsv', f'{self.token}\tclose')
|
||||
from .stop_control import StopControl
|
||||
interactive = isinstance(getattr(self.runtime, 'stop_event', None), StopControl)
|
||||
close_grace = 60 if self.private_desktop else min(30, max(10, self._timeout))
|
||||
if interactive:
|
||||
# The monitor owns the safe/unsafe distinction. Do not
|
||||
# turn a GUI close or ordinary pause into a timed kill.
|
||||
# A failed close has its own deadline, separate from pause.
|
||||
force_event = getattr(getattr(self.runtime, 'stop_event', None), 'force_event', None)
|
||||
last_notice = time.monotonic()
|
||||
deadline = last_notice + close_grace
|
||||
while not self._done.wait(.1):
|
||||
if force_event is not None and force_event.is_set():
|
||||
self._abort.set()
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
self.runtime.stop_event.request_failure_cleanup(self.root,
|
||||
'project session did not acknowledge closing within its grace period')
|
||||
self._abort.set()
|
||||
break
|
||||
if time.monotonic() - last_notice >= 15:
|
||||
import logging
|
||||
logging.getLogger(__name__).warning(
|
||||
'project_session_awaiting_close token=%s', self.token)
|
||||
last_notice = time.monotonic()
|
||||
close_grace = 60 if self.private_desktop else min(30, max(10, self._timeout))
|
||||
if not self._done.wait(close_grace):
|
||||
self._abort.set()
|
||||
if not self._done.wait(30):
|
||||
|
||||
@@ -8,6 +8,7 @@ from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from functools import lru_cache
|
||||
import inspect
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -508,7 +509,8 @@ class QuickRunPreparer:
|
||||
if self._process_runner is _run_process:
|
||||
try:
|
||||
from .cell_catalog import preflight_command_target
|
||||
preflight_command_target(row, self._data_root / 'cell-catalog')
|
||||
from .native_helper import cell_catalog_evidence_root
|
||||
preflight_command_target(row, cell_catalog_evidence_root(handoff.command_path))
|
||||
except TaskCenterError as error:
|
||||
if error.code == 'target_cell_catalog':
|
||||
self._record_rejected_attempt(journal_attempt, handoff, selected_command, before,
|
||||
@@ -534,6 +536,40 @@ class QuickRunPreparer:
|
||||
completed = _run_process(command, IDLE_PROGRESS_TIMEOUT_SECONDS, runtime=runtime)
|
||||
else:
|
||||
completed = self._process_runner(command, IDLE_PROGRESS_TIMEOUT_SECONDS)
|
||||
except TaskCenterError as error:
|
||||
proof = getattr(error, 'unlaunched_worker_pause', None)
|
||||
if proof is None:
|
||||
raise
|
||||
try:
|
||||
if (runtime is None or journal_attempt is None or error.code != 'operation_cancelled'
|
||||
or proof.get('phase') != 'before_worker_launch'
|
||||
or proof.get('worker_launch_attempted') is not False or proof.get('resources_released') is not True
|
||||
or proof.get('session_id') != runtime.session_id or proof.get('generation') != runtime.generation
|
||||
or proof.get('attempt_id') != runtime.record.get('active_attempt')
|
||||
or proof.get('resource_record') != str(runtime.path)
|
||||
or _read_status_details(handoff.status_path) != before
|
||||
or not ((stop_event is not None and stop_event.is_set())
|
||||
or (runtime.stop_event is not None and runtime.stop_event.is_set()))):
|
||||
raise ValueError('unlaunched pause ownership or unchanged status is missing')
|
||||
for name, key in (('command.tsv', 'command_sha256'), ('current-command.tsv', 'current_command_sha256'),
|
||||
('status.tsv', 'status_sha256'), ('project-session.request', 'request_sha256')):
|
||||
path = _io_path(handoff.command_path.parent / name)
|
||||
digest = hashlib.sha256(path.read_bytes()).hexdigest() if path.exists() else None
|
||||
if digest != proof.get(key):
|
||||
raise ValueError('unlaunched pause input binding changed')
|
||||
if current_command_stamp is not None and _file_stamp(
|
||||
handoff.command_path.with_name('current-command.tsv')) != current_command_stamp:
|
||||
raise ValueError('unlaunched pause current command changed')
|
||||
journal.pause_before_dispatch(journal_attempt, row, proof)
|
||||
try:
|
||||
journal.finalize_startup_pause(task_id, handoff.command_path.parent)
|
||||
except OSError:
|
||||
_append_log(handoff.log_path, 'unlaunched_pause_marker_retirement_pending')
|
||||
except Exception as proof_error:
|
||||
_write_uncertain_flag(uncertain_path, 'unproven_unlaunched_pause')
|
||||
raise TaskCenterError('quick_run_uncertain', '启动前暂停缺少完整的未启动证明;保留保护并核验。') from proof_error
|
||||
_append_log(handoff.log_path, 'quick_run_paused worker_launch_not_attempted')
|
||||
raise
|
||||
except subprocess.TimeoutExpired as error:
|
||||
_write_uncertain_flag(uncertain_path, "worker_timeout")
|
||||
_append_log(handoff.log_path, "quick_run_uncertain worker_timeout")
|
||||
@@ -598,6 +634,36 @@ class QuickRunPreparer:
|
||||
_write_uncertain_flag(uncertain_path, "malformed_status_after_worker")
|
||||
_append_log(handoff.log_path, "quick_run_uncertain malformed_status_after_worker")
|
||||
raise TaskCenterError("quick_run_uncertain", "quick-run worker left an unreadable status; reconcile the project before retrying") from error
|
||||
if completed.returncode == 74:
|
||||
try:
|
||||
proof = getattr(completed, 'startup_pause', {})
|
||||
if (runtime is None or journal_attempt is None or after != before
|
||||
or proof.get('session_id') != runtime.session_id or proof.get('generation') != runtime.generation
|
||||
or proof.get('attempt_id') != runtime.record.get('active_attempt')
|
||||
or proof.get('resource_record') != str(runtime.path)
|
||||
or proof.get('request_sha256') != hashlib.sha256(
|
||||
_io_path(handoff.command_path.with_name('project-session.request')).read_bytes()).hexdigest()
|
||||
or (current_command_stamp is not None and proof.get('current_command_sha256') != hashlib.sha256(
|
||||
_io_path(handoff.command_path.with_name('current-command.tsv')).read_bytes()).hexdigest())
|
||||
or not ((stop_event is not None and stop_event.is_set())
|
||||
or (runtime.stop_event is not None and runtime.stop_event.is_set()))):
|
||||
raise ValueError('startup pause binding or unchanged status is missing')
|
||||
journal.pause_before_dispatch(journal_attempt, row, proof)
|
||||
if current_command_stamp is not None:
|
||||
# This marker means "dispatched with no outcome" to the
|
||||
# handoff guard. Only the certified no-dispatch transaction
|
||||
# above may return it to the pending plan.
|
||||
try:
|
||||
journal.finalize_startup_pause(task_id, handoff.command_path.parent)
|
||||
except OSError:
|
||||
# The SQL receipt already proves no dispatch. A later
|
||||
# snapshot retries this exact marker retirement.
|
||||
_append_log(handoff.log_path, 'startup_pause_marker_retirement_pending')
|
||||
except Exception as error:
|
||||
_write_uncertain_flag(uncertain_path, 'unproven_startup_pause')
|
||||
raise TaskCenterError('quick_run_uncertain', '启动暂停缺少完整的未派发证明;保留保护并核验。') from error
|
||||
_append_log(handoff.log_path, 'quick_run_paused startup_no_native_dispatch')
|
||||
raise TaskCenterError('operation_cancelled', '启动阶段安全暂停;原执行项保留待执行,未进行替换。')
|
||||
if completed.returncode == 2 and after == before:
|
||||
_append_log(handoff.log_path, "quick_run_attach_failure exit_code=2")
|
||||
detail = completed.stderr.strip() or completed.stdout.strip() or "DxDesigner attachment failed"
|
||||
@@ -784,7 +850,7 @@ class QuickRunPreparer:
|
||||
from .discovery_cache import project_fingerprint
|
||||
source_before = project_fingerprint(Path(command[2]), self._data_root)
|
||||
if runtime is not None and runtime.cad is not None:
|
||||
runtime.reset_project_after_safe_failure(Path(command[2]), runtime._active_evidence,
|
||||
runtime.reset_project_after_safe_failure(Path(runtime.record['active_project']), runtime._active_evidence,
|
||||
job_id=runtime.record.get('active_job'))
|
||||
completion = synchronous_completion(self._data_root, row, attempt, outcome[1:], source_before, runtime=runtime)
|
||||
proof = {'files': completion['files'], 'failure_health': completion}
|
||||
@@ -955,13 +1021,14 @@ class QuickRunPreparer:
|
||||
from .project_discovery import DiscoveryRuntime, discover_project
|
||||
from .operation_control import control_options
|
||||
|
||||
if collect_components and self._process_runner is _run_process:
|
||||
if self._process_runner is _run_process:
|
||||
from .native_inventory import NativeInventoryReader
|
||||
native = NativeInventoryReader(self._data_root).read(
|
||||
project_path, old_part_numbers, stop_event=stop_event, on_progress=on_progress,
|
||||
**({'runtime': runtime} if runtime is not None else {}))
|
||||
if native is not None:
|
||||
return native
|
||||
raise TaskCenterError('native_inventory', '原生清单未能完整核对,请检查已保存工程和原生导出工具')
|
||||
|
||||
process_runner = self._process_runner
|
||||
if (stop_event is not None or runtime is not None) and process_runner is _run_process:
|
||||
|
||||
@@ -152,8 +152,10 @@ def _read_snapshot_once(preparer, task_id, projects, rules, *, copy_part_number_
|
||||
progress=replace(progress,next_project_path=None,next_old_part_number=None,next_new_part_number=None)
|
||||
return QuickRunSnapshot(progress,True,current,True,'retry')
|
||||
try:
|
||||
assert_handoff_intact(current, task_id, files=files)
|
||||
except TaskCenterError:
|
||||
journal = getattr(preparer, 'journal', None)
|
||||
paused_marker = journal.finalize_startup_pause(task_id, current) if journal is not None else None
|
||||
assert_handoff_intact(current, task_id, files=files, startup_pause_marker=paused_marker)
|
||||
except (TaskCenterError, OSError, ValueError):
|
||||
progress = replace(progress, next_project_path=None, next_old_part_number=None,
|
||||
next_new_part_number=None)
|
||||
return QuickRunSnapshot(progress, True, current, True, 'selection')
|
||||
|
||||
@@ -172,15 +172,27 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
|
||||
raise ValueError('snapshot target selector mismatch')
|
||||
elif len(metadata) == 10:
|
||||
raise ValueError('snapshot target scope missing from command')
|
||||
report = json.loads(snapshot.with_suffix('.tsv.native.json').read_text(encoding='utf-8'))
|
||||
binding = require_resumable_transaction(snapshot, report, metadata, components)
|
||||
source_only = False
|
||||
try:
|
||||
report = json.loads(snapshot.with_suffix('.tsv.native.json').read_text(encoding='utf-8'))
|
||||
if not isinstance(report, dict):
|
||||
raise ValueError('invalid native report')
|
||||
except FileNotFoundError:
|
||||
source_only = True
|
||||
selected_cell = _read_command_cells(root / 'command.tsv').get(job_id) or None
|
||||
if selected_cell != snapshot_target_cell(snapshot, required=False):
|
||||
raise ValueError('snapshot target Cell mismatch')
|
||||
cell_proof = require_current_cell_binding(snapshot, binding, Path(selected[2]), metadata)
|
||||
identity = binding['library_row'][4:6]
|
||||
if any(not value or any(character in value for character in '\t\r\n') for value in identity):
|
||||
raise ValueError('invalid library identity')
|
||||
if source_only:
|
||||
snapshot_digest = hashlib.sha256(snapshot.read_bytes()).hexdigest()
|
||||
identity = ('', '')
|
||||
cell_proof = None
|
||||
else:
|
||||
binding = require_resumable_transaction(snapshot, report, metadata, components)
|
||||
snapshot_digest = binding['snapshot_sha256']
|
||||
cell_proof = require_current_cell_binding(snapshot, binding, Path(selected[2]), metadata)
|
||||
identity = binding['library_row'][4:6]
|
||||
if any(not value or any(character in value for character in '\t\r\n') for value in identity):
|
||||
raise ValueError('invalid library identity')
|
||||
except (OSError, ValueError, KeyError, TypeError, TaskCenterError) as error:
|
||||
raise TaskCenterError('quick_run_recovery', '快照或原生替换证据无法与此任务绑定,保护状态保持不变。') from error
|
||||
if not uncertain.is_file():
|
||||
@@ -228,8 +240,14 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
|
||||
header += '\ttarget_scope\ttarget_selectors'
|
||||
row = (*row, 'targets', selectors)
|
||||
if selected_cell is not None:
|
||||
header += '\ttarget_cell\trecovery_library_path'
|
||||
row = (*row, _encode_vbs_field(selected_cell), _encode_vbs_field(cell_proof['library_path']))
|
||||
header += '\ttarget_cell'
|
||||
row = (*row, _encode_vbs_field(selected_cell))
|
||||
if not source_only:
|
||||
header += '\trecovery_library_path'
|
||||
row = (*row, _encode_vbs_field(cell_proof['library_path']))
|
||||
if source_only:
|
||||
header += '\trecovery_source_only'
|
||||
row = (*row, '1')
|
||||
(worker / 'command.tsv').write_text(header + '\n' + '\t'.join(row) + '\n', encoding='utf-8')
|
||||
_write_status_details(worker / 'status.tsv', ())
|
||||
from .quick_run import _vbs_worker_paths
|
||||
@@ -246,14 +264,16 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
|
||||
raise TaskCenterError('quick_run_recovery', '恢复执行未能确认结束,原保护锁仍在;不要重新替换或删除证据。') from error
|
||||
(audit / 'worker-output.txt').write_text(result.stdout + '\n' + result.stderr, encoding='utf-8')
|
||||
after = _read_status_details(worker / 'status.tsv')
|
||||
if result.returncode != 0 or len(after) != 1 or after[0][0] != job_id or after[0][1] not in {'restored_ok', 'retry_ready'}:
|
||||
allowed_states = {'retry_ready'} if source_only else {'restored_ok', 'retry_ready'}
|
||||
if result.returncode != 0 or len(after) != 1 or after[0][0] != job_id or after[0][1] not in allowed_states:
|
||||
detail = result.stderr.strip() or result.stdout.strip() or (after[-1][3] if after else '没有返回匹配的核验结果')
|
||||
raise TaskCenterError('quick_run_recovery', '恢复未通过,保护状态保留:' + detail[-2000:])
|
||||
if _recovery_hashes(root) != evidence_before or (worker / snapshot.name).read_bytes() != snapshot.read_bytes():
|
||||
raise TaskCenterError('quick_run_recovery', '核验期间原始证据变化,未提交恢复结果。')
|
||||
state = after[0][1]
|
||||
recovery_record = {'task_id': task_id, 'job_id': job_id, 'state': state, 'worker_result': after[0],
|
||||
'snapshot_sha256': binding['snapshot_sha256'], 'evidence_before': evidence_before,
|
||||
'snapshot_sha256': snapshot_digest, 'evidence_before': evidence_before,
|
||||
'mode': 'source_only' if source_only else 'native_transaction',
|
||||
'project_before': project_before, 'native_replacement_called': False}
|
||||
from .batch_resources import write_record
|
||||
write_record(audit/'recovery.json',recovery_record)
|
||||
|
||||
@@ -47,6 +47,9 @@ def publish(preparer, task_id, projects, rules, copy_part_number_to_value):
|
||||
recovery=json.loads((audit/'recovery.json').read_text(encoding='utf8'))
|
||||
if recovery['task_id']!=task_id or recovery['native_replacement_called'] is not False:
|
||||
raise ValueError('invalid recovery proof')
|
||||
if recovery.get('mode')=='source_only' and (
|
||||
recovery['state']!='retry_ready' or recovery['worker_result'][1]!='retry_ready'):
|
||||
raise ValueError('source-only recovery cannot publish target success')
|
||||
root=preparer.data_root/'quick-run'
|
||||
# Reject edits to either original or published files during the handoff.
|
||||
from .quick_run import _encode_vbs_field
|
||||
|
||||
@@ -197,6 +197,24 @@ class TaskCenterService:
|
||||
lambda: preview_batch(self, task_id, path, **control_options(stop_event, on_progress),
|
||||
**({'runtime': runtime} if runtime is not None else {})))
|
||||
|
||||
def pending_bom(self, task_id: str):
|
||||
from .bom_pending import pending_requests
|
||||
return pending_requests(self._store, task_id)
|
||||
|
||||
def bom_resolution(self, task_id: str):
|
||||
from .bom_pending import resolution_binding
|
||||
return resolution_binding(self._store, task_id)
|
||||
|
||||
def import_bom_drafts(self, task_id, sources, *, stop_event=None, on_progress=None, on_phase=None, allow_partial=False):
|
||||
from .bom_pending import import_drafts
|
||||
return self._operation('import_bom_drafts', task_id, lambda: import_drafts(self, task_id, sources,
|
||||
stop_event=stop_event, on_progress=on_progress, on_phase=on_phase, allow_partial=allow_partial))
|
||||
|
||||
def resolve_pending_bom(self, task_id, *, stop_event=None, on_progress=None, runtime=None):
|
||||
from .bom_pending import resolve_pending
|
||||
return self._operation('resolve_pending_bom', task_id, lambda: resolve_pending(self, task_id,
|
||||
stop_event=stop_event, on_progress=on_progress, runtime=runtime))
|
||||
|
||||
def preview_bom_sources(self, task_id: str, sources, *, stop_event=None, on_progress=None,
|
||||
on_phase=None, runtime=None, allow_partial=False):
|
||||
"""Normalize several BOM files and exact-name migrated project paths before CAD reads."""
|
||||
@@ -396,7 +414,7 @@ class TaskCenterService:
|
||||
and any(project.status is ProjectStatus.FAILED for project in projects)):
|
||||
phase = 'retry'
|
||||
context = ProjectTaskContext(task, bound, tuple(rules), tuple(targets), progress,
|
||||
phase, has_evidence, interrupted, legacy)
|
||||
phase, has_evidence, interrupted, legacy, self.pending_bom(task_id))
|
||||
return context
|
||||
return self._operation("refresh_bound_project", task_id, refresh)
|
||||
|
||||
@@ -1063,7 +1081,7 @@ class TaskCenterService:
|
||||
assert_task_queue_idle(self._logging.root)
|
||||
with _quick_run_lease(self._logging.root):
|
||||
return self._operation('cleanup_batch_resources', None,
|
||||
lambda: cleanup_pending_resources(self._logging.root, logging_context=self._logging))
|
||||
lambda: cleanup_pending_resources(self._logging.root, logging_context=self._logging, retry_failed=True))
|
||||
|
||||
def inspect_bom_batch(self, task_id: str, path: Path, *, stop_event=None, on_progress=None, on_phase=None, runtime=None):
|
||||
if runtime is None and self._supervised:
|
||||
@@ -1381,10 +1399,13 @@ class TaskCenterService:
|
||||
task = self._store.get_task(task_id)
|
||||
projects = self._store.list_projects(task_id)
|
||||
if progress is None:
|
||||
rules = (compile_target_rules(self._store.list_target_plan(task_id),
|
||||
default_value_mode='part_label' if task.copy_part_number_to_value else 'preserve')
|
||||
if task.target_plan_mode else self._execution_rules(task_id))
|
||||
progress = self._quick_run_preparer.progress(
|
||||
task_id,
|
||||
projects,
|
||||
self._execution_rules(task_id),
|
||||
rules,
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
)
|
||||
if self._supervised:
|
||||
|
||||
@@ -4,6 +4,14 @@ import json
|
||||
import os
|
||||
|
||||
from .path_access import internal_path
|
||||
from .worker_monitor import WorkerMonitorError
|
||||
|
||||
|
||||
MENTOR_RELEASE_REQUIRED = 'mentor_release_required'
|
||||
|
||||
|
||||
class MentorReleaseRequired(WorkerMonitorError):
|
||||
code = MENTOR_RELEASE_REQUIRED
|
||||
|
||||
|
||||
class StopControl(Event):
|
||||
@@ -13,12 +21,21 @@ class StopControl(Event):
|
||||
self.control_error = ''
|
||||
self.waiting_for_resolution = False
|
||||
self.resolution_error = ''
|
||||
self.cleanup_mode = None
|
||||
self.cleanup_reason = ''
|
||||
|
||||
def request_force(self):
|
||||
self.set()
|
||||
self.control_error = ''
|
||||
self.force_event.set()
|
||||
|
||||
def request_failure_cleanup(self, root, error):
|
||||
protect_interruption(root, MENTOR_RELEASE_REQUIRED + ': ' + str(error))
|
||||
self.cleanup_mode = MENTOR_RELEASE_REQUIRED
|
||||
self.cleanup_reason = self.cleanup_reason or str(error)
|
||||
self.set()
|
||||
self.force_event.set()
|
||||
|
||||
|
||||
def protect_interruption(root, reason):
|
||||
"""Create or re-sync a marker without overwriting prior protection evidence."""
|
||||
@@ -42,12 +59,11 @@ def protect_interruption(root, reason):
|
||||
os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def wait_for_resolution(control, root, error, *, resolved=None):
|
||||
"""Retain uncertain work until explicit force or an owned-exit proof.
|
||||
def wait_for_resolution(control, root, error, *, resolved=None, release_on_failure=False):
|
||||
"""Protect uncertainty, then admit failure cleanup or wait for manual release.
|
||||
|
||||
The GUI-side supervisor can also terminate its own Job after durable force
|
||||
evidence. Ordinary cancellation never releases this wait; an optional
|
||||
observer may prove all retained processes exited without clearing uncertainty.
|
||||
Ordinary pause does not grant termination. Failure cleanup uses the same
|
||||
owned-Job release path after durable protection, retaining result uncertainty.
|
||||
"""
|
||||
if not isinstance(control, StopControl):
|
||||
return
|
||||
@@ -62,6 +78,11 @@ def wait_for_resolution(control, root, error, *, resolved=None):
|
||||
protect()
|
||||
except OSError as failure:
|
||||
control.control_error = '保护记录写入失败,保留应用等待处理:' + str(failure)
|
||||
if release_on_failure:
|
||||
try:
|
||||
control.request_failure_cleanup(root, error)
|
||||
except OSError as failure:
|
||||
control.control_error = '失败收尾保护记录无法保存,保留资源等待重试:' + str(failure)
|
||||
try:
|
||||
record = json.loads((root / 'worker-progress.json').read_text(encoding='utf-8'))
|
||||
if not isinstance(record, dict):
|
||||
@@ -69,7 +90,8 @@ def wait_for_resolution(control, root, error, *, resolved=None):
|
||||
except (OSError, ValueError):
|
||||
record = {}
|
||||
record.update(stage='awaiting_reconciliation', waiting_for_safe_completion=True,
|
||||
resolution_error=str(error), stop_requested=True, safe_stop=False)
|
||||
resolution_error=str(error), stop_requested=True, safe_stop=False,
|
||||
cleanup_mode=control.cleanup_mode)
|
||||
_publish_progress(root / 'worker-progress.json', record)
|
||||
while True:
|
||||
if resolved is not None and resolved():
|
||||
@@ -82,4 +104,7 @@ def wait_for_resolution(control, root, error, *, resolved=None):
|
||||
control.force_event.clear()
|
||||
control.control_error = '强制结束未执行,保护记录无法保存:' + str(failure)
|
||||
continue
|
||||
control.waiting_for_resolution = False
|
||||
if control.cleanup_mode == MENTOR_RELEASE_REQUIRED:
|
||||
raise MentorReleaseRequired('Mentor failure cleanup; reconciliation required: ' + control.cleanup_reason)
|
||||
raise WorkerMonitorError('user forced stop of uncertain operation; reconciliation required')
|
||||
@@ -52,6 +52,11 @@ class StoreSchema:
|
||||
self._store._ensure_task_columns()
|
||||
self._store._ensure_rule_columns()
|
||||
self._store._create_target_plan_schema()
|
||||
self._store._connection.execute('''CREATE TABLE IF NOT EXISTS pending_bom (
|
||||
task_id TEXT PRIMARY KEY REFERENCES tasks(task_id) ON DELETE CASCADE, payload_json TEXT NOT NULL)''')
|
||||
self._store._connection.execute('''CREATE TABLE IF NOT EXISTS bom_resolution (
|
||||
task_id TEXT PRIMARY KEY REFERENCES tasks(task_id) ON DELETE CASCADE, confirmed_hash TEXT NOT NULL,
|
||||
resolved_hash TEXT NOT NULL)''')
|
||||
self._store._connection.execute('''CREATE TABLE IF NOT EXISTS assistant_task_creations (
|
||||
request_id TEXT PRIMARY KEY, request_hash TEXT NOT NULL, result_json TEXT NOT NULL)''')
|
||||
self._store._connection.execute('''CREATE TABLE IF NOT EXISTS assistant_task_operations (
|
||||
|
||||
@@ -16,9 +16,7 @@ from .quick_run import _write_atomic_queue_text
|
||||
|
||||
_QUEUE_LOCK = Lock()
|
||||
_QUEUE_OWNER: int | None = None
|
||||
_SAFE_FAILURES = frozenset({'quick_run_preflight', 'quick_run_session', 'quick_run_backup',
|
||||
'target_identity', 'empty_target_scope', 'enabled_rule_required',
|
||||
'quick_run_retry_required'})
|
||||
from .execution_problems import classify_execution_failure
|
||||
_TERMINAL = frozenset({'completed', 'failed', 'skipped'})
|
||||
|
||||
|
||||
@@ -35,6 +33,7 @@ class TaskQueueResult:
|
||||
entries: tuple[TaskQueueEntry, ...]
|
||||
paused: bool
|
||||
current_task_id: str | None = None
|
||||
netlist_verification: dict | None = None
|
||||
|
||||
|
||||
def _os_lock(handle, acquire):
|
||||
@@ -110,7 +109,7 @@ def _record(value):
|
||||
return vars(value)
|
||||
|
||||
|
||||
def _plan_hash(child, task_id: str) -> str:
|
||||
def _plan_hash(child, task_id: str, *, resolve_alias=True) -> str:
|
||||
task = child.get_task(task_id)
|
||||
payload = {
|
||||
'projects': [(str(project.path.resolve(strict=False)).casefold(), project.selected, project.available)
|
||||
@@ -120,8 +119,19 @@ def _plan_hash(child, task_id: str) -> str:
|
||||
'copy_value': task.copy_part_number_to_value,
|
||||
'target_plan_mode': getattr(task, 'target_plan_mode', False),
|
||||
}
|
||||
return hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=False,
|
||||
pending = getattr(child, 'pending_bom', None)
|
||||
requests = pending(task_id) if callable(pending) else ()
|
||||
if requests:
|
||||
payload['pending_bom'] = [asdict(item) if is_dataclass(item) else item for item in requests]
|
||||
digest = hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=False,
|
||||
default=str).encode('utf-8')).hexdigest()
|
||||
resolution = getattr(child, 'bom_resolution', None)
|
||||
binding = resolution(task_id) if resolve_alias and callable(resolution) else None
|
||||
# Materializing real UIDs preserves the confirmed request, but subsequent
|
||||
# plan edits must still change the digest and invalidate confirmation.
|
||||
if binding and binding.get('resolved_hash') == digest:
|
||||
return binding['confirmed_hash']
|
||||
return digest
|
||||
|
||||
|
||||
def _save(path: Path, state: dict) -> None:
|
||||
@@ -129,15 +139,64 @@ def _save(path: Path, state: dict) -> None:
|
||||
'task_queue_state', '不能保存任务队列检查点。')
|
||||
|
||||
|
||||
def reconcile_interrupted_queue(root, journal):
|
||||
"""After confirmed supervisor exit, retire only its persisted running entries."""
|
||||
import hashlib
|
||||
from .supervisor_protocol import decode
|
||||
from .path_access import canonical_path, internal_path
|
||||
if journal.get('operation') != 'execute_task_queue':
|
||||
return
|
||||
try:
|
||||
request_path = internal_path(Path(root) / 'batch-resources' / journal['batch_id'] / 'request.json')
|
||||
raw = request_path.read_bytes()
|
||||
if hashlib.sha256(raw).hexdigest() != journal.get('request_sha256'):
|
||||
return
|
||||
request = json.loads(raw)
|
||||
arguments = decode(request['arguments'])
|
||||
if (request['batch_id'] != journal['batch_id'] or request['attempt_id'] != journal['attempt_id'] or
|
||||
request['operation'] != 'execute_task_queue' or canonical_path(request['root']) != canonical_path(root) or
|
||||
list(arguments['task_ids']) != journal['task_ids']):
|
||||
return
|
||||
token = arguments.get('queue_id') or arguments.get('checkpoint_id')
|
||||
if not isinstance(token, str) or len(token) != 32 or any(c not in '0123456789abcdef' for c in token):
|
||||
return
|
||||
path = internal_path(Path(root) / 'task-queues' / (token + '.json'))
|
||||
state = json.loads(path.read_text(encoding='utf-8'))
|
||||
ids = journal['task_ids']
|
||||
if (state['version'] != 1 or state['task_ids'] != ids or set(state['entries']) != set(ids) or
|
||||
arguments.get('expected_plan_hashes') is not None and
|
||||
state['plan_hashes'] != arguments['expected_plan_hashes']):
|
||||
return
|
||||
if any(not isinstance(row, dict) or row.get('state') not in
|
||||
{'pending', 'running', 'paused', 'blocked', *_TERMINAL} for row in state['entries'].values()):
|
||||
return
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return
|
||||
changed = False
|
||||
for row in state['entries'].values():
|
||||
if row['state'] == 'running':
|
||||
row.update(state='blocked', message='执行进程已退出,结果待核验;请先核验恢复。')
|
||||
changed = True
|
||||
if changed:
|
||||
_save(path, state)
|
||||
|
||||
|
||||
def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
queue_id: str | None = None, runtime=None, expected_plan_hashes=None, checkpoint_id=None,
|
||||
defer_problem_pass=False) -> TaskQueueResult:
|
||||
"""Execute the frozen order; uncertain state stops before the next project."""
|
||||
if runtime is None and getattr(service, '_supervised', False):
|
||||
from .workspace_execution import execute_workspace_projects
|
||||
return execute_workspace_projects(service, task_ids, queue_id=queue_id, stop_event=stop_event,
|
||||
expected_plan_hashes=expected_plan_hashes, checkpoint_id=checkpoint_id,
|
||||
defer_problem_pass=defer_problem_pass)
|
||||
# Existing per-project checkpoints keep their original resume owner.
|
||||
if (isinstance(queue_id, str) and len(queue_id) == 32
|
||||
and all(char in '0123456789abcdef' for char in queue_id)
|
||||
and (service._logging.root / 'workspace-queues' / (queue_id + '.json')).is_file()):
|
||||
from .workspace_execution import execute_workspace_projects
|
||||
return execute_workspace_projects(service, task_ids, queue_id=queue_id, stop_event=stop_event,
|
||||
expected_plan_hashes=expected_plan_hashes, checkpoint_id=checkpoint_id,
|
||||
defer_problem_pass=defer_problem_pass)
|
||||
return service._supervise('execute_task_queue', {'task_ids': tuple(task_ids),
|
||||
'queue_id': queue_id, 'expected_plan_hashes': expected_plan_hashes,
|
||||
'checkpoint_id': checkpoint_id, 'defer_problem_pass': defer_problem_pass}, stop_event=stop_event)
|
||||
if runtime is None:
|
||||
from .batch_runtime import BatchCadRuntime
|
||||
with BatchCadRuntime(service._logging.root, 'task_queue', stop_event) as owned_runtime:
|
||||
@@ -192,9 +251,13 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
_save(path, state)
|
||||
paused = False
|
||||
current = None
|
||||
from .netlist_verification import NetlistVerification
|
||||
checks = NetlistVerification(root, token, stop_event)
|
||||
try:
|
||||
for task_id in ids:
|
||||
if state['entries'][task_id]['state'] in _TERMINAL:
|
||||
if state['entries'][task_id]['state'] == 'completed':
|
||||
checks.before_task(children[task_id], task_id, existing_only=True)
|
||||
continue
|
||||
if stop_event.is_set():
|
||||
paused = True
|
||||
@@ -202,13 +265,30 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
current = task_id
|
||||
child = children[task_id]
|
||||
service._task_queue_feedback = (token, task_id, ids.index(task_id) + 1, len(ids))
|
||||
resolving_bom = False
|
||||
execution_dispatched = False
|
||||
try:
|
||||
if hasattr(runtime, 'begin_task'):
|
||||
runtime.begin_task(task_id)
|
||||
if child.has_interrupted_quick_run(task_id):
|
||||
raise TaskCenterError('quick_run_uncertain', '该任务有待核验步骤。')
|
||||
pending = getattr(child, 'pending_bom', None)
|
||||
if callable(pending) and pending(task_id):
|
||||
if _plan_hash(child, task_id) != hashes[task_id]:
|
||||
raise TaskCenterError('assistant_stale', '待执行 BOM 已变化,请重新确认。')
|
||||
resolving_bom = True
|
||||
resolved = child.resolve_pending_bom(task_id, stop_event=stop_event)
|
||||
resolving_bom = False
|
||||
if not any(row.enabled for row in resolved):
|
||||
state['entries'][task_id] = {'state': 'skipped',
|
||||
'message': 'BOM 核验通过,所有启用位号无需替换;已跳过执行,未进行网表比对。'}
|
||||
_save(path, state)
|
||||
continue
|
||||
if hasattr(child, '_quick_run_preparer'):
|
||||
child._quick_run_preparer.reconcile_terminal_receipts(task_id)
|
||||
progress = child.quick_run_progress(task_id)
|
||||
if progress.queue_complete:
|
||||
checks.before_task(child, task_id, existing_only=True)
|
||||
entry = {'state': 'failed' if getattr(progress, 'failed_items', 0) else 'completed',
|
||||
'message': '该任务队列已有完整执行结果。'}
|
||||
else:
|
||||
@@ -222,6 +302,8 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
runtime_options = ({'runtime': runtime} if any(
|
||||
parameter.name == 'runtime' or parameter.kind is inspect.Parameter.VAR_KEYWORD
|
||||
for parameter in parameters) else {})
|
||||
checks.before_task(child, task_id)
|
||||
execution_dispatched = True
|
||||
result = execute(task_id, expected_item=expected, stop_event=stop_event,
|
||||
**runtime_options)
|
||||
if child.has_interrupted_quick_run(task_id) or (
|
||||
@@ -237,26 +319,58 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
if incomplete:
|
||||
paused = True
|
||||
except TaskCenterError as error:
|
||||
safe = error.code in _SAFE_FAILURES and not child.has_interrupted_quick_run(task_id)
|
||||
if safe and hasattr(child, '_record_safe_queue_failure'):
|
||||
from .execution_problems import ExecutionProblems
|
||||
try:
|
||||
certified = (execution_dispatched and hasattr(child, '_store')
|
||||
and ExecutionProblems(child._store).certified_failures(task_id))
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
certified = False
|
||||
policy = classify_execution_failure(error.code, 'failed',
|
||||
phase='read' if resolving_bom else 'unknown' if execution_dispatched else 'not_dispatched',
|
||||
certified=certified,
|
||||
interrupted=child.has_interrupted_quick_run(task_id))
|
||||
safe = policy['continue_allowed']
|
||||
if error.code == 'operation_cancelled':
|
||||
safe = False
|
||||
if safe and not resolving_bom and hasattr(child, '_record_safe_queue_failure'):
|
||||
try:
|
||||
child._record_safe_queue_failure(task_id, error.message)
|
||||
except Exception:
|
||||
safe = False # Failure admission must itself be durable before proceeding.
|
||||
entry = {'state': 'failed' if safe else 'blocked', 'message': error.message}
|
||||
entry = {'state': 'failed' if safe else 'paused' if error.code == 'operation_cancelled' else 'blocked',
|
||||
'message': f'{error.code}: {error.message}' if resolving_bom else error.message}
|
||||
paused = not safe
|
||||
except Exception as error:
|
||||
entry = {'state': 'blocked', 'message': str(error)}
|
||||
paused = True
|
||||
state['entries'][task_id] = entry
|
||||
_save(path, state)
|
||||
if (entry['state'] in {'completed', 'failed'} and task_id in checks.tasks
|
||||
and not child.has_interrupted_quick_run(task_id)):
|
||||
progress = child.quick_run_progress(task_id)
|
||||
checks.after_task(task_id, execution_state=entry['state'],
|
||||
execution_summary={key: getattr(progress, key, None)
|
||||
for key in ('saved_items', 'failed_items', 'no_match_items')})
|
||||
if paused:
|
||||
break
|
||||
if (not paused and stop_event.is_set() and state.get('phase') != 'finished'
|
||||
and any(entry['state'] == 'failed' for entry in state['entries'].values())):
|
||||
paused = True # Preserve deferred problems when pause lands after the last primary item.
|
||||
if not paused and not defer_problem_pass and not stop_event.is_set() and state.get('phase') != 'finished' and hasattr(service, 'reserve_problem_retry'):
|
||||
state['phase'] = 'problems'
|
||||
_save(path, state)
|
||||
for task_id in ids:
|
||||
if (state['entries'][task_id]['state'] == 'failed' and task_id not in checks.tasks
|
||||
and not children[task_id].has_interrupted_quick_run(task_id)):
|
||||
checks.before_task(children[task_id], task_id)
|
||||
from .problem_pass import run_problem_pass
|
||||
retried = run_problem_pass(service, ids, token, stop_event=stop_event, runtime=runtime)
|
||||
def capture_retry(task_id, result):
|
||||
if not result.paused and not children[task_id].has_interrupted_quick_run(task_id):
|
||||
checks.after_task(task_id, execution_state='failed' if result.progress.failed_items else 'completed',
|
||||
refresh=True, execution_summary={key: getattr(result.progress, key, None)
|
||||
for key in ('saved_items', 'failed_items', 'no_match_items')})
|
||||
retried = run_problem_pass(service, ids, token, stop_event=stop_event, runtime=runtime,
|
||||
on_result=capture_retry)
|
||||
for task_id, result in retried.results.items():
|
||||
state['entries'][task_id] = {'state': 'paused' if result.paused else 'failed' if result.progress.failed_items else 'completed',
|
||||
'message': '问题轮次暂停。' if result.paused else '问题轮次已收尾,保留所有真实回执。'}
|
||||
@@ -266,10 +380,39 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
paused, current = True, retried.blocked_task_id
|
||||
state['entries'][current] = {'state': 'blocked',
|
||||
'message': f'{retried.error_code}: {retried.message}'}
|
||||
if stop_event.is_set():
|
||||
paused = True
|
||||
current = current or ids[-1]
|
||||
if not paused and not stop_event.is_set():
|
||||
state['phase'] = 'finished'
|
||||
_save(path, state)
|
||||
for task_id in checks.tasks:
|
||||
if (state['entries'][task_id]['state'] in {'completed', 'failed'}
|
||||
and not children[task_id].has_interrupted_quick_run(task_id)):
|
||||
progress = children[task_id].quick_run_progress(task_id)
|
||||
checks.after_task(task_id, execution_state=state['entries'][task_id]['state'],
|
||||
execution_summary={key: getattr(progress, key, None)
|
||||
for key in ('saved_items', 'failed_items', 'no_match_items')})
|
||||
verification = dict(state.get('netlist_verification', {}))
|
||||
for task_id, report in checks.finish().items():
|
||||
verification[task_id] = report
|
||||
label = {'verified': '通过', 'different': '发现差异', 'unavailable': '未完成',
|
||||
'not_completed': '等待执行完成', 'not_replaced': '含未命中项,需核对',
|
||||
'cancelled': '已取消'}.get(report['status'], report['status'])
|
||||
state['entries'][task_id]['message'] += f";独立网表比对{label}:{report['report_path']}"
|
||||
if hasattr(service._logging, 'logger'):
|
||||
from .logging_setup import append_task_event
|
||||
append_task_event(service._logging, task_id=task_id,
|
||||
level='INFO' if report.get('verified') else 'WARNING', operation='native_netlist_verification',
|
||||
message=f'独立网表比对{label}', details=report)
|
||||
if verification:
|
||||
state['netlist_verification'] = verification
|
||||
_save(path, state)
|
||||
return TaskQueueResult(token, tuple(TaskQueueEntry(task_id, **state['entries'][task_id])
|
||||
for task_id in ids), paused, current if paused else None)
|
||||
for task_id in ids), paused, current if paused else None,
|
||||
verification or None)
|
||||
finally:
|
||||
service._task_queue_feedback = None
|
||||
try:
|
||||
checks.__exit__(None, None, None)
|
||||
finally:
|
||||
service._task_queue_feedback = None
|
||||
@@ -463,7 +463,7 @@ class DshAutomation(QObject):
|
||||
w._resource_status.refresh()
|
||||
w._update_gates()
|
||||
if w._close_pending:
|
||||
QTimer.singleShot(0, w.close)
|
||||
QTimer.singleShot(0, w, w.close)
|
||||
else:
|
||||
QTimer.singleShot(0, self._drain)
|
||||
|
||||
|
||||
@@ -134,6 +134,8 @@ class DshTaskCreationController(QObject):
|
||||
self._respond({'request_id': request_id, **result})
|
||||
self.window.task_list.recycle_button.setChecked(False)
|
||||
if result['task_ids']:
|
||||
self.window.task_list.search.clear()
|
||||
self.window.task_list.filter.setCurrentIndex(self.window.task_list.filter.findData('all'))
|
||||
self.window._task_id = result['task_ids'][0]
|
||||
self.window._load_task_data()
|
||||
self.window._refresh_task_list()
|
||||
|
||||
@@ -35,16 +35,23 @@ def execution_state(context, *, busy=False, dirty=False):
|
||||
return ExecutionState(message='任务已删除,可从已删除列表恢复。')
|
||||
editable = task.status in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.FAILED} and not context.has_evidence and not busy
|
||||
retry = context.phase == 'retry' and not context.interrupted and not busy and not dirty
|
||||
pending = bool(context.progress.next_project_path) and not context.progress.queue_complete
|
||||
requests = getattr(context, 'pending_bom', ())
|
||||
deferred = bool(requests)
|
||||
from ..bom_pending import retained_bom_rows
|
||||
retained = retained_bom_rows(requests, context.targets) if deferred else ()
|
||||
pending = (any(item.record.enabled for item in requests) or bool(retained) if deferred else
|
||||
bool(context.progress.next_project_path) and not context.progress.queue_complete)
|
||||
execute = (pending and task.status in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.PAUSED}
|
||||
and project.available and not context.interrupted and not busy and not dirty)
|
||||
text = '继续当前任务' if task.status is TaskStatus.PAUSED else '执行当前任务'
|
||||
text = '核验并执行' if deferred else '继续当前任务' if task.status is TaskStatus.PAUSED else '执行当前任务'
|
||||
message = ('结果待核验,请先恢复中断步骤。' if context.interrupted else
|
||||
'位号计划有未保存编辑,请先保存。' if dirty else
|
||||
'正在处理当前步骤,暂停会等待安全收尾。' if busy else
|
||||
'任务已完成。可查看原计划和日志;点击“开始新一轮”归档本批已完成任务,再采集当前料号。' if task.status is TaskStatus.COMPLETED else
|
||||
'有失败项,可核对原因后重试。' if retry else
|
||||
'工程不可用,请检查路径。' if not project.available else
|
||||
'BOM 和保留计划都没有启用的替换行,请修改表格后重新导入。' if deferred and not pending else
|
||||
'BOM 表格已保存;确认后仅核验当前工程位号,再执行替换。' if deferred else
|
||||
'先填写旧、新料号,再采集并勾选位号。' if not pending else
|
||||
'配置就绪,可执行当前任务或按顺序执行本批任务。')
|
||||
return ExecutionState(editable, execute, retry, context.interrupted and not busy and not dirty, text, message,
|
||||
|
||||
@@ -119,6 +119,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._batch_stop = None
|
||||
self._active_quick_run_task_id = None
|
||||
self._project_queues = {}
|
||||
self._execution_after_save = None
|
||||
self._generation = 0
|
||||
self._message = ''
|
||||
self._context_phase = ContextReadPhase.IDLE
|
||||
@@ -396,7 +397,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
event.ignore()
|
||||
if not self._dsh_stopping:
|
||||
self._dsh_stopping = True
|
||||
self._dsh_view.stopped.connect(lambda: QTimer.singleShot(0, self.close))
|
||||
self._dsh_view.stopped.connect(lambda: QTimer.singleShot(0, self, self.close))
|
||||
self._dsh_view.shutdown()
|
||||
return
|
||||
self._cancel_dsh_diagnosis()
|
||||
@@ -444,6 +445,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
if self._workers and self._batch_stop is None:
|
||||
return
|
||||
if self._task_id != task_id:
|
||||
self._execution_after_save = None
|
||||
self.plan_panel.bind_task(None)
|
||||
self.project_summary.populate(None)
|
||||
self.mapping_table.populate(())
|
||||
@@ -469,6 +471,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
lambda error: self._task_context_failed(error, auto_intervene=auto_intervene), cancellable=True)
|
||||
|
||||
def _task_context_failed(self, error, *, auto_intervene=True):
|
||||
self._execution_after_save = None
|
||||
self._context_phase = ContextReadPhase.FAILED
|
||||
self._context = None
|
||||
self.project_summary.state.setText('任务读取失败,请点击“重试读取任务”。')
|
||||
@@ -496,6 +499,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._refresh_live_task_log()
|
||||
self._update_gates()
|
||||
self._bind_dsh_context()
|
||||
self._resume_saved_execution()
|
||||
except Exception as error:
|
||||
self._task_context_failed(error, auto_intervene=auto_intervene)
|
||||
|
||||
@@ -505,11 +509,12 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self.ai_cancel_action.setEnabled(cancellable)
|
||||
if self._dsh_status is not None:
|
||||
self._dsh_status.update()
|
||||
busy = bool(self._workers) or self._loading or self.history_panel._worker is not None
|
||||
busy = bool(self._workers) or self._loading
|
||||
resources_pending = self._resource_status.blocked
|
||||
dialog_state = getattr(self.service, '_supervisor_dialog_state', None) or {}
|
||||
modal_pending = bool((dialog_state.get('supervision') or {}).get('blocked'))
|
||||
self.history_panel.set_mutations_enabled(not busy and not resources_pending and self._batch_stop is None)
|
||||
self.history_panel.set_mutations_enabled(not busy and self.history_panel._worker is None
|
||||
and not resources_pending and self._batch_stop is None)
|
||||
self.run_panel.cleanup_resources_button.setText('处理阻塞弹窗' if modal_pending else '重试释放资源')
|
||||
self.run_panel.cleanup_resources_button.setVisible(modal_pending or resources_pending and self._resource_status.known)
|
||||
self.run_panel.cleanup_resources_button.setEnabled(modal_pending or resources_pending and self._resource_status.known and not busy)
|
||||
@@ -517,8 +522,10 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
dirty=self.plan_panel.table.dirty or self.plan_panel.table.has_pending_editor())
|
||||
group_unsaved = self._group_has_unsaved_plans() if state.editable or state.new_round else False
|
||||
context = self._context
|
||||
self.run_panel.quick_run_button.setText(state.execute_text)
|
||||
self.run_panel.quick_run_button.setEnabled(state.execute and not resources_pending)
|
||||
save_pending = bool(context and state.editable and
|
||||
(self.plan_panel.table.dirty or self.plan_panel.table.has_pending_editor() or self.plan_panel._active_bom_batch()))
|
||||
self.run_panel.quick_run_button.setText('保存计划以执行' if save_pending else state.execute_text)
|
||||
self.run_panel.quick_run_button.setEnabled((state.execute or save_pending) and not resources_pending)
|
||||
self.run_panel.retry_button.setVisible(bool(context and context.phase == 'retry'))
|
||||
self.run_panel.retry_button.setEnabled(state.retry and not resources_pending)
|
||||
self.run_panel.problems_button.setEnabled(bool(context and not busy))
|
||||
@@ -544,7 +551,6 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self.plan_panel.set_plan_editable(state.editable, busy=busy)
|
||||
if resources_pending:
|
||||
self.plan_panel.collect_button.setEnabled(False)
|
||||
self.plan_panel.import_bom_button.setEnabled(False)
|
||||
self.add_mapping_button.setEnabled(rule_editable)
|
||||
selected = self.mapping_table.current_rule_id() is not None
|
||||
for button in (self.edit_mapping_button, self.delete_mapping_button,
|
||||
@@ -739,17 +745,51 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._run_async(lambda: self.service.set_copy_part_number_to_value(task_id, enabled),
|
||||
lambda _: self._load_task_data(), self.run_panel.copy_value_check, expected_task_id=task_id)
|
||||
|
||||
def _save_plans_before_execution(self, task_ids, *, batch=False):
|
||||
owner = self._task_id
|
||||
def saved(rows):
|
||||
self.plan_panel._saved_bom_batch(rows)
|
||||
self._execution_after_save = (owner, batch)
|
||||
self._run_async(self.plan_panel.prepare_save_all(task_ids), saved,
|
||||
expected_task_id=owner, on_finished=self._resume_saved_execution)
|
||||
|
||||
def _resume_saved_execution(self):
|
||||
pending = self._execution_after_save
|
||||
if pending is None or self._workers or self._loading:
|
||||
return
|
||||
self._execution_after_save = None
|
||||
if self._closed or self._close_pending or pending[0] != self._task_id or self._context is None:
|
||||
return
|
||||
(self._execute_project_tasks if pending[1] else self._prepare_quick_run)()
|
||||
|
||||
def _execution_report_ready(self, report):
|
||||
if report.get('ready'):
|
||||
return True
|
||||
reasons = dict.fromkeys(reason for task in report.get('tasks', ()) for reason in task.get('blockers', ()))
|
||||
self._set_operator_message('当前范围无法执行:' + ';'.join(reasons), 'warning')
|
||||
return False
|
||||
|
||||
def _prepare_quick_run(self):
|
||||
if not self.run_panel.quick_run_button.isEnabled():
|
||||
return
|
||||
if (self.plan_panel.table.dirty or self.plan_panel.table.has_pending_editor()
|
||||
or self.plan_panel._active_bom_batch()):
|
||||
self._save_plans_before_execution((self._task_id,))
|
||||
return
|
||||
context = self._context
|
||||
enabled = sum(row.enabled for row in context.targets) if context.task.target_plan_mode else sum(r.enabled for r in context.rules)
|
||||
pending = getattr(context, 'pending_bom', ())
|
||||
from ..bom_pending import retained_bom_rows
|
||||
retained = retained_bom_rows(pending, context.targets) if pending else ()
|
||||
enabled = (sum(len(item.refs) for item in pending if item.record.enabled) + len(retained) if pending else
|
||||
sum(row.enabled for row in context.targets) if context.task.target_plan_mode else sum(r.enabled for r in context.rules))
|
||||
from ...dsh import task_lifecycle as lifecycle
|
||||
try:
|
||||
report = lifecycle.preflight(self.service, [context.task.task_id])
|
||||
except Exception as error:
|
||||
self._show_error(error, owner_task_id=context.task.task_id)
|
||||
return
|
||||
if not self._execution_report_ready(report):
|
||||
return
|
||||
self._dsh_confirmation_impact = report.get('impact', {})
|
||||
if not self._quick_run_confirmer('current', 1, enabled):
|
||||
return
|
||||
@@ -772,7 +812,17 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
[task_id], report, stop, run_id)
|
||||
def done(receipt):
|
||||
from ..batch import BatchRunResult
|
||||
self._show_batch_result(BatchRunResult(self.service.quick_run_progress(task_id), receipt['paused']))
|
||||
progress = self.service.quick_run_progress(task_id)
|
||||
self._show_batch_result(BatchRunResult(progress, receipt['paused']))
|
||||
failures = tuple(entry for entry in receipt.get('entries', ()) if entry['state'] in {'failed', 'blocked'})
|
||||
if failures:
|
||||
self._close_pending = False
|
||||
details = '\n'.join(entry['message'] for entry in failures)
|
||||
self._set_operator_message(f'任务执行失败:已保存 {progress.saved_items},失败/阻断 {len(failures)} 项。\n{details}', 'warning')
|
||||
if not progress.failed_items:
|
||||
for entry in failures:
|
||||
self._queue_dsh_incident(entry['task_id'], 'execution_failed', entry['message'])
|
||||
self._show_receipt_verification(receipt)
|
||||
self._dsh_last_execution = receipt
|
||||
self._bind_dsh_context()
|
||||
self._run_async(execute, done, self.run_panel.quick_run_button, expected_task_id=task_id)
|
||||
@@ -786,25 +836,25 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
return
|
||||
token, ids = self._project_queues.get(group, (None, tuple(t.task_id for t in tasks)))
|
||||
if self.plan_panel.has_unsaved_plan(ids):
|
||||
self._set_operator_message('本批任务有未保存计划,请先逐个保存。', 'warning')
|
||||
self._save_plans_before_execution(ids, batch=True)
|
||||
return
|
||||
report = None
|
||||
if len(ids) <= 20:
|
||||
from ...dsh import task_lifecycle as lifecycle
|
||||
try:
|
||||
if token:
|
||||
from ...dsh.run_journal import resume_preflight
|
||||
report = resume_preflight(self.service, self._dsh_operations.runs.inspect(self.service, token))
|
||||
else:
|
||||
report = lifecycle.preflight(self.service, list(ids), allow_completed=True)
|
||||
except Exception as error:
|
||||
self._show_error(error, owner_task_id=ids[0])
|
||||
return
|
||||
self._dsh_confirmation_impact = report.get('impact', {}) if report else {}
|
||||
if not self._quick_run_confirmer('batch', len(ids), 0):
|
||||
from ...dsh import task_lifecycle as lifecycle
|
||||
try:
|
||||
if token:
|
||||
from ...dsh.run_journal import resume_preflight
|
||||
report = resume_preflight(self.service, self._dsh_operations.runs.inspect(self.service, token))
|
||||
else:
|
||||
report = lifecycle.preflight(self.service, list(ids), allow_completed=True)
|
||||
except Exception as error:
|
||||
self._show_error(error, owner_task_id=ids[0])
|
||||
return
|
||||
if not self._execution_report_ready(report):
|
||||
return
|
||||
self._dsh_confirmation_impact = report.get('impact', {})
|
||||
enabled = report.get('impact', {}).get('enabled_scope', 0)
|
||||
if not self._quick_run_confirmer('batch', len(ids), enabled):
|
||||
return
|
||||
self._dsh_authorized_tasks.update(ids)
|
||||
from ..task_queue import execute_task_queue
|
||||
self._begin_run(ids[0])
|
||||
self._dsh_live_run['task_ids'] = list(ids)
|
||||
run_id = token or self._dsh_run_id
|
||||
@@ -829,8 +879,6 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._set_operator_message(f'本批任务已暂停。失败/阻断 {failures} 项。' if result.paused else f'本批任务已结束。失败 {failures} 项。',
|
||||
'warning' if result.paused or failures else 'success')
|
||||
def execute():
|
||||
if report is None:
|
||||
return execute_task_queue(self.service, ids, stop_event=stop, queue_id=token)
|
||||
from ...dsh.execution_runs import execute_confirmed_run
|
||||
from ..task_queue import TaskQueueEntry, TaskQueueResult
|
||||
resume = None
|
||||
@@ -845,6 +893,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
if isinstance(value, tuple):
|
||||
result, receipt = value
|
||||
done(result)
|
||||
self._show_receipt_verification(receipt)
|
||||
self._dsh_last_execution = receipt
|
||||
self._bind_dsh_context()
|
||||
else:
|
||||
@@ -924,6 +973,20 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._set_operator_message(f"任务「{name}」{'已暂停' if result.paused else '已结束'}:已保存 {p.saved_items},失败 {p.failed_items},未命中 {p.no_match_items}。",
|
||||
'warning' if result.paused or p.failed_items else 'success')
|
||||
|
||||
def _show_receipt_verification(self, receipt):
|
||||
pending = tuple(report for report in (receipt.get('netlist_verification') or {}).values()
|
||||
if report.get('status') != 'verified' or not report.get('verified'))
|
||||
acceptance = receipt.get('acceptance', {})
|
||||
if not pending and acceptance.get('status') not in {'different', 'unavailable'}:
|
||||
return
|
||||
labels = {'different': '发现差异', 'unavailable': '未完成', 'not_completed': '未完成', 'cancelled': '已取消'}
|
||||
details = '\n'.join(f"独立网表比对{labels.get(report.get('status'), '未完成')}:{report.get('report_path', '')}"
|
||||
for report in pending)
|
||||
if not details:
|
||||
details = '独立网表验收未完成:缺少完整比对报告;已保存结果保留,不能据此认定验收通过。'
|
||||
self._close_pending = False
|
||||
self._set_operator_message(self.run_panel.operator_band.text() + '\n' + details, 'warning')
|
||||
|
||||
def _cleanup_batch_resources(self):
|
||||
if not self.run_panel.cleanup_resources_button.isEnabled():
|
||||
return
|
||||
@@ -1115,14 +1178,18 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
context = self._context
|
||||
names = context.project.path if scope == 'current' else '\n'.join(
|
||||
f'{t.group_position+1}. {t.name}' for t in pending_batch_tasks(self._tasks, context.task.group_id))
|
||||
text = (f'执行范围:{names}\n\n' + (f'勾选目标/规则:{enabled_rules}\n' if scope == 'current' else f'按顺序处理 {selected_projects} 个工程任务。\n')
|
||||
text = (f'执行范围:{names}\n\n' + ('' if scope == 'current' else f'按顺序处理 {selected_projects} 个工程任务。\n')
|
||||
+ f'勾选目标/规则:{enabled_rules}\n'
|
||||
+ '逐项执行原生 Replace Part + Library Wins,保留每行 Value/NC 策略;创建备份并自动保存、关闭、重开核验。'
|
||||
+ '\n默认在受监督的私有桌面执行,结束后释放自有 CAD 会话;主桌面可继续查看其他文件。请确保待处理工程未在其他 CAD 会话中打开。'
|
||||
+ '\n确认后连续执行,暂停等待当前步骤收尾;状态不确定时停止。')
|
||||
impact = getattr(self, '_dsh_confirmation_impact', {})
|
||||
if impact:
|
||||
text += '\n\n执行影响:' + ('器件数量未知,执行时按实际命中核验。' if impact['component_count'] is None else f"已选中 {impact['component_count']} 个器件。")
|
||||
text += '\n' + '\n'.join(f"{row.get('refdes') or '映射'}:{row['old_part_number']} → {row['new_part_number']} · Value {row.get('value_policy')} · Cell {row.get('target_cell') or '自动匹配'} · NC {row.get('sync_nc')}" for row in impact['rows'])
|
||||
text += '\n' + '\n'.join(
|
||||
('原计划保留 · ' if row.get('retained_from_saved_plan') else 'BOM 待核验 · ' if row.get('verification_pending') else '')
|
||||
+ f"{row.get('refdes') or ', '.join(row.get('requested_refdes', ())) or '映射'}:{row['old_part_number']} → {row['new_part_number']} · Value {row.get('value_policy')} · Cell {row.get('target_cell') or '自动匹配'} · NC {row.get('sync_nc')}"
|
||||
for row in impact['rows'])
|
||||
return QMessageBox.question(self, '确认执行当前任务' if scope == 'current' else '确认顺序执行本批任务', text,
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
QMessageBox.StandardButton.No) == QMessageBox.StandardButton.Yes
|
||||
|
||||
@@ -9,7 +9,8 @@ from PySide6.QtCore import Qt, QThreadPool, QObject, Signal, QSignalBlocker
|
||||
from PySide6.QtGui import QAction,QKeySequence
|
||||
from PySide6.QtWidgets import (QCheckBox, QDialog, QDialogButtonBox, QFileDialog, QHBoxLayout, QLabel,
|
||||
QLineEdit, QListWidget, QListWidgetItem, QMessageBox, QPushButton,
|
||||
QVBoxLayout, QWidget, QToolButton, QMenu)
|
||||
QVBoxLayout, QWidget, QToolButton, QMenu, QTableWidget, QTableWidgetItem,
|
||||
QAbstractItemView, QHeaderView)
|
||||
from shiboken6 import isValid
|
||||
|
||||
from .detail_windows import BomReportDialog
|
||||
@@ -19,6 +20,7 @@ from .operation_state import OperationPhase
|
||||
from .command_menu import CommandMenu
|
||||
from .icons import icon
|
||||
from ..bom_import_state import BomImportMachine, BomImportPhase, BomImportState
|
||||
from ..bom_pending import retained_bom_rows
|
||||
|
||||
|
||||
class _OperationProgress(QObject):
|
||||
@@ -190,6 +192,15 @@ class ProjectPlanPanel(QWidget):
|
||||
self.stop_button.hide()
|
||||
self.stop_button.clicked.connect(self.cancel_operation)
|
||||
self.table = TargetTable(self)
|
||||
self._pending_bom = ()
|
||||
self._retained_bom = ()
|
||||
self.pending_table = QTableWidget(0, 10, self)
|
||||
self.pending_table.setObjectName('pendingBomRequests')
|
||||
self.pending_table.setHorizontalHeaderLabels(('旧料号', '新料号', '位号', '图页', 'Value 策略', '同步 NC', '替换', '来源', 'UID', 'Cell'))
|
||||
self.pending_table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||
self.pending_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)
|
||||
self.pending_table.horizontalHeader().setStretchLastSection(True)
|
||||
self.pending_table.hide()
|
||||
self.collect_button = QPushButton('采集位号', objectName='collectTargetInventory')
|
||||
self.save_button = QPushButton('保存位号计划', objectName='saveTargetPlan')
|
||||
self.import_button = QPushButton('导入位号计划', objectName='importTargetPlan')
|
||||
@@ -222,8 +233,8 @@ class ProjectPlanPanel(QWidget):
|
||||
self.report_toggle.hide()
|
||||
self.report_toggle.toggled.connect(self._toggle_report)
|
||||
self.last_bom_report = None
|
||||
self.partial_bom = QCheckBox('允许部分导入通过工程', objectName='allowPartialBom')
|
||||
self.partial_bom.setToolTip('仅核验前置检查通过的工程;报告返回后仍需选择工程并确认。')
|
||||
self.partial_bom = QCheckBox('仅导入表格有效的工程', objectName='allowPartialBom')
|
||||
self.partial_bom.setToolTip('同一工程有任意无效行时整工程不导入;有效工程保存为待核验清单。')
|
||||
self.partial_bom_button = QPushButton('选择通过工程…', objectName='selectPassedBomProjects')
|
||||
self.partial_bom_button.hide()
|
||||
self.partial_bom_button.clicked.connect(self._choose_passed_projects)
|
||||
@@ -272,6 +283,7 @@ class ProjectPlanPanel(QWidget):
|
||||
layout.addWidget(self.partial_bom)
|
||||
layout.addWidget(self.partial_bom_button)
|
||||
layout.addWidget(self.table, 1)
|
||||
layout.addWidget(self.pending_table, 1)
|
||||
layout.addLayout(selection)
|
||||
self.collect_button.clicked.connect(self.collect)
|
||||
self.save_button.clicked.connect(self.save)
|
||||
@@ -311,14 +323,41 @@ class ProjectPlanPanel(QWidget):
|
||||
if self.task_id and self.table.dirty:
|
||||
self._drafts[self.task_id] = self.table.rows()
|
||||
self.task_id = task_id
|
||||
if rows is None:
|
||||
rows = self.window.service.target_plan(task_id) if task_id else ()
|
||||
reader = getattr(self.window.service, 'pending_bom', None)
|
||||
self._pending_bom = reader(task_id) if task_id and reader else ()
|
||||
self._retained_bom = retained_bom_rows(self._pending_bom, rows) if self._pending_bom else ()
|
||||
self.pending_table.setRowCount(len(self._pending_bom) + len(self._retained_bom))
|
||||
for index, request in enumerate(self._pending_bom):
|
||||
record = request.record
|
||||
values = (record.old, record.new, ', '.join(record.refs),
|
||||
'/'.join(filter(None, (record.schematic, record.sheet))), record.value_mode +
|
||||
(' · ' + record.custom if record.value_mode == 'custom' else ''),
|
||||
'是' if record.sync_nc else '否', '启用' if record.enabled else '保留',
|
||||
f'{request.source_file} 第 {request.source_row} 行', record.uid or '待核验', '')
|
||||
for column, value in enumerate(values):
|
||||
item = QTableWidgetItem(value)
|
||||
if not record.enabled:
|
||||
item.setToolTip('本行未启用替换')
|
||||
self.pending_table.setItem(index, column, item)
|
||||
for index, row in enumerate(self._retained_bom, len(self._pending_bom)):
|
||||
target = row.target
|
||||
mode = 'custom' if row.custom_value_enabled else row.value_mode
|
||||
values = (target.old_part_number, row.new_part_number, target.refdes,
|
||||
'/'.join(filter(None, (target.schematic_name, target.sheet_number))),
|
||||
mode + (' · ' + row.custom_value if mode == 'custom' else ''), '是' if row.sync_nc else '否',
|
||||
'启用', '原计划保留(本次 BOM 未覆盖)', target.uid, row.target_cell)
|
||||
for column, value in enumerate(values):
|
||||
self.pending_table.setItem(index, column, QTableWidgetItem(value))
|
||||
self.pending_table.setVisible(bool(self._pending_bom))
|
||||
self.table.setVisible(not self._pending_bom)
|
||||
self.clear_find()
|
||||
if task_id in self._drafts:
|
||||
self.table.populate(self._drafts[task_id])
|
||||
self.table.dirty = True
|
||||
self._summary()
|
||||
return
|
||||
if rows is None:
|
||||
rows = self.window.service.target_plan(task_id) if task_id else ()
|
||||
self.table.populate(rows)
|
||||
self._summary()
|
||||
|
||||
@@ -366,7 +405,7 @@ class ProjectPlanPanel(QWidget):
|
||||
selected=len(self.table.selectionModel().selectedRows())
|
||||
self.bulk_apply.setText(f'填入 {selected} 行'if selected else'填入选中行')
|
||||
self.bulk_apply.setToolTip('先选中表格行,再输入新料号;行选中与替换勾选是两种操作。')
|
||||
self.bulk_apply.setEnabled(self._editable and bool(self.task_id) and selected>0 and bool(self.bulk_part.text().strip()))
|
||||
self.bulk_apply.setEnabled(self._editable and not self._pending_bom and bool(self.task_id) and selected>0 and bool(self.bulk_part.text().strip()))
|
||||
query=bool(self.find_text.text().strip())
|
||||
visible=self.table.rowCount()
|
||||
self.find_result.setVisible(query)
|
||||
@@ -382,13 +421,18 @@ class ProjectPlanPanel(QWidget):
|
||||
def has_unsaved_plans(self):
|
||||
return bool(self._drafts or self._bom_batches or self._orphaned_bom_batches or self.table.dirty or self.table.has_pending_editor())
|
||||
|
||||
def prepare_save_all(self):
|
||||
def prepare_save_all(self, task_ids=None):
|
||||
# Snapshot widgets only on the GUI thread; the returned operation uses plain data.
|
||||
if self.table.has_pending_editor():self.table.setFocus(Qt.FocusReason.ShortcutFocusReason)
|
||||
drafts = dict(self._drafts)
|
||||
if self.task_id and self.table.dirty:
|
||||
drafts[self.task_id] = self.table.rows()
|
||||
batches = tuple(self._bom_batches.values()) + tuple(self._orphaned_bom_batches.values())
|
||||
if task_ids is not None:
|
||||
scope = set(task_ids)
|
||||
batches = tuple(batch for batch in batches if any(p.task_id in scope for p in batch.projects))
|
||||
scope.update(p.task_id for batch in batches for p in batch.projects)
|
||||
drafts = {task_id: rows for task_id, rows in drafts.items() if task_id in scope}
|
||||
return lambda: self._save_all_snapshot(drafts, batches)
|
||||
|
||||
def save_all(self):
|
||||
@@ -559,6 +603,12 @@ class ProjectPlanPanel(QWidget):
|
||||
if state.message:
|
||||
self.summary.setText(state.message)
|
||||
return
|
||||
if self._pending_bom:
|
||||
count = sum(len(item.refs) for item in self._pending_bom if item.record.enabled)
|
||||
retained = len(self._retained_bom)
|
||||
self.summary.setText(f'BOM 已保存,待核验:{len(self._pending_bom)} 行、{count} 个启用位号;'
|
||||
f'原计划保留 {retained} 个,合计 {count + retained} 个;确认执行后仅核验当前工程。')
|
||||
return
|
||||
if batch:
|
||||
self.summary.setText(f'本批 BOM 已匹配 {len(batch.projects)} 个工程;表格显示当前工程,切换任务可编辑,'
|
||||
'确认后一次保存本批位号计划。')
|
||||
@@ -586,8 +636,15 @@ class ProjectPlanPanel(QWidget):
|
||||
widget.setEnabled(self._editable and bool(self.task_id))
|
||||
if self._active_bom_batch():
|
||||
self.collect_button.setEnabled(False)
|
||||
if self._pending_bom:
|
||||
self.table.set_plan_editable(False)
|
||||
for widget in (self.collect_button, self.import_button, self.select_all, self.select_none,
|
||||
self.bulk_part, self.bulk_apply):
|
||||
widget.setEnabled(False)
|
||||
self.export_button.setEnabled(self._editable and bool(self.task_id)
|
||||
and bool(self.table.plan_model.rowCount()) and not self.table.dirty)
|
||||
and bool(self.table.plan_model.rowCount()) and not self.table.dirty and not self._pending_bom)
|
||||
for widget in (self.find_text, self.find_button, self.find_next_button, self.clear_find_button):
|
||||
widget.setEnabled(not self._pending_bom)
|
||||
self.export_bom_button.setEnabled(not busy)
|
||||
self._edit_feedback()
|
||||
|
||||
@@ -658,12 +715,15 @@ class ProjectPlanPanel(QWidget):
|
||||
def import_bom(self):
|
||||
if not self.task_id:
|
||||
return
|
||||
if self.has_unsaved_plans():
|
||||
self.window._set_operator_message('有未保存位号计划,请先保存或放弃编辑后导入 BOM。', 'warning')
|
||||
return
|
||||
paths, _ = QFileDialog.getOpenFileNames(self, '导入 BOM 模板(可多选)', '', 'BOM Excel (*.xlsx)')
|
||||
if paths:
|
||||
task_id = self.task_id
|
||||
scope = self._report_scope(task_id)
|
||||
partial = {'allow_partial': True} if self.partial_bom.isChecked() else {}
|
||||
self._dispatch_cancellable(lambda stop, progress, phase: self.window.service.preview_bom_sources(
|
||||
self._dispatch_cancellable(lambda stop, progress, phase: self.window.service.import_bom_drafts(
|
||||
task_id, tuple(Path(path) for path in paths), stop_event=stop, on_progress=progress, on_phase=phase, **partial),
|
||||
lambda report: self._received_bom_report(report, scope=scope, owner_task_id=task_id), self.import_bom_button,
|
||||
bom_scope=scope)
|
||||
@@ -719,6 +779,15 @@ class ProjectPlanPanel(QWidget):
|
||||
report = state.report
|
||||
if report is None:
|
||||
return '', '', ''
|
||||
if report.deferred:
|
||||
failed_paths = {row.project_path for row in report.rows if row.status == 'failed'}
|
||||
accepted = tuple(row for row in report.rows if row.project_path not in failed_paths)
|
||||
summary = (f'BOM 表格已保存,工程位号待核验:{len(accepted)} 行、'
|
||||
f'{len({row.project_path for row in accepted})} 个工程;失败 {report.failed_rows} 行。')
|
||||
details = [summary, '确认执行后仅核验当前工程;本次导入未读取工程位号。']
|
||||
details.extend(f'{row.project_name} · {Path(row.source_file).name} 第 {row.source_row} 行:{row.reason}'
|
||||
for row in report.rows)
|
||||
return summary, '\n'.join(details), 'BOM 已保存 · 待核验 · 详情'
|
||||
outcome = '校验通过' if state.phase is BomImportPhase.PREVIEW_READY else '校验未通过'
|
||||
summary = (f'BOM {outcome}:共 {report.total_rows} 行,通过 {report.passed_rows} 行、'
|
||||
f'失败 {report.failed_rows} 行、未检查 {report.unchecked_rows} 行;'
|
||||
@@ -757,17 +826,20 @@ class ProjectPlanPanel(QWidget):
|
||||
if scope == self._report_scope(self.task_id):
|
||||
if hasattr(self.window, '_set_operator_message'):
|
||||
summary, _, _ = self._format_bom_report(machine.state)
|
||||
self.window._set_operator_message(summary, 'error' if report.preview is None else 'info')
|
||||
self.window._set_operator_message(summary, 'error' if report.preview is None and not report.deferred else 'info')
|
||||
self._restore_bom_report(scope)
|
||||
if report.preview is not None:
|
||||
self._preview_bom(report.preview)
|
||||
elif report.deferred:
|
||||
self.bind_task(self.task_id)
|
||||
self.window._load_task_data()
|
||||
elif scope == self._report_scope(self.task_id):
|
||||
self._summary()
|
||||
self.window._update_gates()
|
||||
|
||||
def _report_bom_blocker(self, report, scope, owner_task_id, *, error=None):
|
||||
source = self._bom_blocker_source(scope)
|
||||
if report.preview is None:
|
||||
if report.preview is None and not report.deferred:
|
||||
summary, _, _ = self._format_bom_report(self._bom_imports[scope].state)
|
||||
details = {name: getattr(report, name) for name in (
|
||||
'total_rows', 'passed_rows', 'failed_rows', 'unchecked_rows',
|
||||
|
||||
@@ -58,7 +58,7 @@ def _validated(root, row, outcome):
|
||||
raise ValueError('Value report version, command or current snapshot differs')
|
||||
components, old_values, source_nc = {}, {}, set()
|
||||
def has_nc(value):
|
||||
return any(part.strip().casefold() == 'nc' for part in value.split('/')[1:])
|
||||
return '/' in value and any(part.strip().casefold() == 'nc' for part in value.split('/'))
|
||||
for line in snapshot.splitlines():
|
||||
fields = _fields(line)
|
||||
if fields[0] == 'C':
|
||||
|
||||
@@ -13,9 +13,9 @@ import time
|
||||
import threading
|
||||
from uuid import uuid4
|
||||
|
||||
PROJECT_OPEN_IDLE_TIMEOUT_SECONDS = 45
|
||||
READ_ONLY_CANCEL_GRACE_SECONDS = 5
|
||||
READ_ONLY_IDLE_TIMEOUT_SECONDS = 45
|
||||
FAILURE_COMPLETION_GRACE_SECONDS = 30
|
||||
|
||||
|
||||
class WorkerMonitorError(subprocess.SubprocessError):
|
||||
@@ -207,12 +207,13 @@ class ProgressWatch:
|
||||
def action(self, now: float) -> str | None:
|
||||
idle = now - self.last_business_progress
|
||||
idle_timeout = self.idle_timeout
|
||||
if self.stage == 'open_project' and self.safe_stop:
|
||||
idle_timeout = min(idle_timeout, PROJECT_OPEN_IDLE_TIMEOUT_SECONDS)
|
||||
if not self.stop_requested and idle >= idle_timeout:
|
||||
self.stop_requested = True
|
||||
return 'request_stop'
|
||||
if self.stop_requested and idle >= idle_timeout * 2:
|
||||
if (self.waiting_for_safe_completion
|
||||
and idle >= idle_timeout * 2 + FAILURE_COMPLETION_GRACE_SECONDS):
|
||||
return 'failure_cleanup'
|
||||
if not self.safe_stop:
|
||||
if not self.waiting_for_safe_completion:
|
||||
self.waiting_for_safe_completion = True
|
||||
@@ -285,13 +286,14 @@ class _OwnedWorkers:
|
||||
import pywintypes
|
||||
import win32api
|
||||
import win32job
|
||||
from .isolated_desktop import _job_process_ids
|
||||
|
||||
failures = []
|
||||
query_name = ctypes.WinDLL('kernel32', use_last_error=True).QueryFullProcessImageNameW
|
||||
query_name.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_wchar_p, ctypes.POINTER(ctypes.c_ulong)]
|
||||
query_name.restype = ctypes.c_int
|
||||
try:
|
||||
process_ids = win32job.QueryInformationJobObject(self.job, win32job.JobObjectBasicProcessIdList)
|
||||
process_ids = _job_process_ids(self.job)
|
||||
for process_id in process_ids:
|
||||
if process_id == process.pid:
|
||||
continue
|
||||
@@ -337,6 +339,10 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
progress_path = root / 'worker-progress.json'
|
||||
native_progress_path = root / f'monitor-{token}.native-progress'
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
session_request = (root / 'project-session.request').read_bytes()
|
||||
except FileNotFoundError:
|
||||
session_request = None
|
||||
watch = ProgressWatch(token, job_id,
|
||||
min(idle_timeout, READ_ONLY_IDLE_TIMEOUT_SECONDS) if cooperative_abort else idle_timeout,
|
||||
time.monotonic())
|
||||
@@ -354,6 +360,7 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
messages = queue.Queue(maxsize=1024)
|
||||
stop_readers = threading.Event()
|
||||
output = [bytearray(), bytearray()]
|
||||
startup_pause = None
|
||||
|
||||
def read_stream(stream, channel):
|
||||
try:
|
||||
@@ -371,8 +378,26 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
stream.close()
|
||||
|
||||
def receive(channel, line):
|
||||
nonlocal startup_pause
|
||||
if channel == 0 and watch.accept(line, time.monotonic()):
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
elif channel == 0 and line.startswith(b'DX_STARTUP_PAUSED\t'):
|
||||
try:
|
||||
fields = line.decode('ascii').strip().split('\t')
|
||||
request_data = (root / 'project-session.request').read_bytes()
|
||||
request = request_data.decode('utf-8-sig').strip().split('\t')
|
||||
if (len(fields) == 6 and fields[:3] == ['DX_STARTUP_PAUSED', token, job_id]
|
||||
and session_request is not None and request_data == session_request
|
||||
and len(request) == 3 and fields[3:5] == [request[0], request[2]]
|
||||
and request[2] == job_id and re.fullmatch('[0-9a-f]{32}', request[0])
|
||||
and int(fields[5]) == watch.sequence and watch.sequence == 1
|
||||
and watch.stage == 'session_startup' and watch.current_job_id == job_id
|
||||
and watch.safe_stop and not watch.unsafe_seen and not watch.native_progress_frames
|
||||
and abort_event is not None and abort_event.is_set() and watch.stop_requested):
|
||||
startup_pause = {'monitor_token': token, 'session_token': request[0], 'job_id': job_id,
|
||||
'project_path': request[1], 'sequence': watch.sequence}
|
||||
except (OSError, UnicodeError, ValueError):
|
||||
pass
|
||||
elif len(output[channel]) < 1024 * 1024:
|
||||
output[channel].extend(line[:1024 * 1024 - len(output[channel])])
|
||||
|
||||
@@ -433,6 +458,9 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
else:
|
||||
durable_force_accepted = True
|
||||
if getattr(force_control, 'cleanup_mode', None) == 'mentor_release_required':
|
||||
from .stop_control import MentorReleaseRequired
|
||||
raise MentorReleaseRequired('Mentor failure cleanup: ' + force_control.cleanup_reason)
|
||||
raise WorkerMonitorError('user forced stop; execution requires reconciliation')
|
||||
if stop_write_pending:
|
||||
request_stop()
|
||||
@@ -486,6 +514,8 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
if not isinstance(force_control, StopControl):
|
||||
raise WorkerMonitorError('unsafe worker stalled without an interactive controller')
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
elif action == 'failure_cleanup':
|
||||
raise WorkerMonitorError('unsafe worker made no progress after the safe-completion grace period')
|
||||
elif action == 'unresponsive':
|
||||
if stop_write_pending and not cooperative_abort:
|
||||
watch.waiting_for_safe_completion = True
|
||||
@@ -506,7 +536,15 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
# A root can exit before Job accounting confirms its descendants exited.
|
||||
if not cooperative_abort and not _wait_worker_tree_exit(process, owned, exit_deadline):
|
||||
raise WorkerMonitorError('worker root exited while owned descendants remain; reconciliation required')
|
||||
return subprocess.CompletedProcess(command, process.returncode, _decode(output[0]), _decode(output[1]))
|
||||
result = subprocess.CompletedProcess(command, process.returncode, _decode(output[0]), _decode(output[1]))
|
||||
if process.returncode == 74:
|
||||
if (startup_pause is None or watch.sequence != 1 or watch.stage != 'session_startup'
|
||||
or watch.unsafe_seen or not watch.safe_stop or watch.native_progress_frames
|
||||
or result.stderr.strip() or (root / 'project-session.request').read_bytes() != session_request
|
||||
or not _worker_tree_exited(process, owned)):
|
||||
raise WorkerMonitorError('startup pause lacks correlated no-project acknowledgement or worker exit')
|
||||
result.startup_pause = dict(startup_pause, worker_tree_exited=True)
|
||||
return result
|
||||
except Exception as error:
|
||||
if process is not None:
|
||||
if (not cooperative_abort and not durable_force_accepted
|
||||
@@ -519,10 +557,14 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
raise WorkerMonitorError('owned worker retained for explicit force or confirmed exit: ' + str(error)) from error
|
||||
try:
|
||||
wait_for_resolution(force_control, root, error,
|
||||
resolved=lambda: _worker_tree_exited(process, owned))
|
||||
except WorkerMonitorError:
|
||||
resolved=lambda: _worker_tree_exited(process, owned),
|
||||
release_on_failure=True)
|
||||
except WorkerMonitorError as release:
|
||||
if not force_event.is_set():
|
||||
raise
|
||||
if getattr(release, 'code', None) == 'mentor_release_required':
|
||||
release.primary_error = error
|
||||
error = release
|
||||
durable_force_accepted = True
|
||||
cleanup_deadline = time.monotonic() + 10
|
||||
failures = owned.stop_workers(process)
|
||||
@@ -552,6 +594,8 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
raise error
|
||||
if isinstance(error, subprocess.TimeoutExpired):
|
||||
raise
|
||||
if getattr(error, 'code', None) == 'mentor_release_required':
|
||||
raise error
|
||||
raise WorkerMonitorError(f'Worker monitoring failed after launch; execution requires reconciliation: {error}') from error
|
||||
raise
|
||||
finally:
|
||||
|
||||
@@ -138,8 +138,13 @@ def _exact_name_matches(project_name, paths):
|
||||
def resolve_project(project_path, project_name, paths, *, project_names=None):
|
||||
"""Resolve exact path first, then an exact unique migrated project name."""
|
||||
paths = tuple(Path(path) for path in paths)
|
||||
resolved_paths = {path: _path_key(path.resolve()) for path in paths}
|
||||
return _resolve_project(project_path, project_name, paths, project_names, resolved_paths)
|
||||
|
||||
|
||||
def _resolve_project(project_path, project_name, paths, project_names, resolved_paths):
|
||||
raw = _path_key(project_path)
|
||||
exact_path = tuple(path for path in paths if _path_key(path.resolve()) == raw) if raw else ()
|
||||
exact_path = tuple(path for path in paths if resolved_paths[path] == raw) if raw else ()
|
||||
if len(exact_path) == 1:
|
||||
return exact_path[0]
|
||||
if project_name:
|
||||
@@ -160,6 +165,7 @@ def resolve_project(project_path, project_name, paths, *, project_names=None):
|
||||
def route_sources(rows, paths, *, manual=None, single=False, project_names=None):
|
||||
"""Route source rows; stale paths are allowed only on exact unique names."""
|
||||
paths, manual = tuple(Path(path) for path in paths), manual or {}
|
||||
resolved_paths = {path: _path_key(path.resolve()) for path in paths}
|
||||
routes = {}
|
||||
for row in rows:
|
||||
key = row.project_key
|
||||
@@ -171,7 +177,7 @@ def route_sources(rows, paths, *, manual=None, single=False, project_names=None)
|
||||
if chosen not in paths:
|
||||
raise TaskCenterError('project_binding', '人工选择的工程不在本次工程列表中')
|
||||
else:
|
||||
chosen = resolve_project(row.project_path, row.project_name, paths, project_names=project_names)
|
||||
chosen = _resolve_project(row.project_path, row.project_name, paths, project_names, resolved_paths)
|
||||
if chosen is None and single and len(paths) == 1 and not row.project_path:
|
||||
chosen = paths[0]
|
||||
routes[key] = chosen
|
||||
|
||||
@@ -116,8 +116,10 @@ def execute_workspace_projects(service, task_ids, *, stop_event, queue_id=None,
|
||||
write_record(path, state)
|
||||
|
||||
def result(paused=False, current=None):
|
||||
verification = {item: state['entries'][item]['netlist_verification'] for item in ids
|
||||
if state['entries'][item].get('netlist_verification')}
|
||||
return TaskQueueResult(token, tuple(TaskQueueEntry(item, state['entries'][item]['state'],
|
||||
state['entries'][item]['message']) for item in ids), paused, current)
|
||||
state['entries'][item]['message']) for item in ids), paused, current, verification or None)
|
||||
|
||||
def run_project(item, *, problems=False):
|
||||
row = state['entries'][item]
|
||||
@@ -138,6 +140,9 @@ def execute_workspace_projects(service, task_ids, *, stop_event, queue_id=None,
|
||||
or outcome.entries[0].state not in {'pending', 'running', 'paused', *_TERMINAL}):
|
||||
raise TaskCenterError('task_queue_state', '工程监督进程返回了不同的队列身份。')
|
||||
row.update(state=outcome.entries[0].state, message=outcome.entries[0].message, released=True)
|
||||
verification = (outcome.netlist_verification or {}).get(item)
|
||||
if verification:
|
||||
row['netlist_verification'] = verification
|
||||
write_record(path, state)
|
||||
return outcome.paused and row['state'] != 'blocked'
|
||||
except TaskCenterError as error:
|
||||
@@ -183,6 +188,10 @@ def execute_workspace_projects(service, task_ids, *, stop_event, queue_id=None,
|
||||
if state['phase'] == 'problems':
|
||||
for item in ids:
|
||||
row = state['entries'][item]
|
||||
if row['state'] == 'completed':
|
||||
row['problems_done'] = True
|
||||
write_record(path, state)
|
||||
continue
|
||||
if row['problems_done'] or row['state'] not in {'completed', 'failed', 'paused', 'running'}:
|
||||
continue
|
||||
if stop_event.is_set():
|
||||
|
||||
Reference in new issue
Block a user