fix: close batch execution and recovery lifecycle
This commit is contained in:
1 parent
b19afc6a53
commit
d9cf6a07e9
91 files changed
+5779
-454
No files matched your search
@@ -286,7 +286,8 @@ def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, st
|
||||
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)
|
||||
from ..trial_task_center.batch_resources import resource_blockers
|
||||
checkpoint['entries'][task_id].update(released=not bool(resource_blockers(service.pending_batch_resources())), problems_done=True)
|
||||
if reports:
|
||||
checkpoint['entries'][task_id]['netlist_verification'] = reports[task_id]
|
||||
elif reports:
|
||||
|
||||
@@ -316,7 +316,8 @@ class IncidentRunner:
|
||||
remaining = tuple(self.service.pending_batch_resources())
|
||||
cleanup['remaining_resources'] = _bounded_details(remaining)
|
||||
cleanup['remaining_resources_observed'] = True
|
||||
released = not remaining
|
||||
from ..trial_task_center.batch_resources import resource_blockers
|
||||
released = not resource_blockers(remaining)
|
||||
except Exception as error:
|
||||
cleanup['verification_error'] = scrub({'type': type(error).__name__, 'detail': str(error)[:1000]})
|
||||
cleanup['remaining_resources'], released = None, None
|
||||
|
||||
@@ -402,7 +402,8 @@ class RunJournal:
|
||||
blockers.append("preflight_blocked")
|
||||
except Exception:
|
||||
blockers.append("preflight_unavailable")
|
||||
if service.pending_batch_resources():
|
||||
from ..trial_task_center.batch_resources import resource_blockers
|
||||
if resource_blockers(service.pending_batch_resources()):
|
||||
blockers.append("resources_pending")
|
||||
blockers = list(dict.fromkeys(blockers))
|
||||
value = {**row, "queue_available": queue is not None, "tasks": tasks, "counters": counters,
|
||||
|
||||
@@ -246,7 +246,8 @@ class ScheduleStore:
|
||||
with self.execution_lease(schedule_id):
|
||||
assert_task_queue_idle(self.data_root)
|
||||
with _queue_lease(self.data_root):
|
||||
if service.pending_batch_resources():
|
||||
from ..trial_task_center.batch_resources import resource_blockers
|
||||
if resource_blockers(service.pending_batch_resources()):
|
||||
raise TaskCenterError('schedule_busy', '后台资源尚未释放,请先在任务中心核验和清理。')
|
||||
with self._connect() as db:
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
|
||||
@@ -50,7 +50,8 @@ def preflight(service, task_ids, *, allow_completed=False):
|
||||
from .impact import _scope
|
||||
task_ids = _scope(task_ids)
|
||||
tasks, paths, hashes = [], set(), {}
|
||||
pending = bool(service.pending_batch_resources())
|
||||
from ..trial_task_center.batch_resources import resource_blockers
|
||||
pending = bool(resource_blockers(service.pending_batch_resources()))
|
||||
for task_id in task_ids:
|
||||
context = _context(service, task_id)
|
||||
state = execution_state(context)
|
||||
|
||||
@@ -121,6 +121,9 @@ def execute_batch(
|
||||
**({'runtime': runtime} if runtime is not None else {})) as project_session:
|
||||
while not progress.queue_complete:
|
||||
if stop_event.is_set():
|
||||
if project_session.enabled and project_session.worker is not None:
|
||||
progress = preparer.complete_project_session(task_id, project_session, session, projects)
|
||||
progress = service._synchronize_quick_run_progress(task_id, progress=progress)
|
||||
backups.commit_prefetched(progress)
|
||||
return BatchRunResult(
|
||||
progress, True, last_result, tuple(item_messages), tuple(backups.unbacked_project_paths)
|
||||
@@ -133,6 +136,9 @@ def execute_batch(
|
||||
backups.prepare(current, progress)
|
||||
service._batch_feedback = (task_id, progress, f'正在处理 {current.name}')
|
||||
if stop_event.is_set():
|
||||
if project_session.enabled and project_session.worker is not None:
|
||||
progress = preparer.complete_project_session(task_id, project_session, session, projects)
|
||||
progress = service._synchronize_quick_run_progress(task_id, progress=progress)
|
||||
backups.commit_prefetched(progress)
|
||||
return BatchRunResult(
|
||||
progress, True, last_result, tuple(item_messages), tuple(backups.unbacked_project_paths)
|
||||
@@ -197,7 +203,7 @@ def execute_batch(
|
||||
candidate = last_result.progress
|
||||
project_completed = candidate.completed_project_paths != progress.completed_project_paths
|
||||
synchronize = (
|
||||
progress.completed_items == 0
|
||||
(progress.completed_items == 0 and last_result.state != 'pending_save')
|
||||
or project_completed
|
||||
or candidate.queue_complete
|
||||
or last_result.state in {BATCH_FAILED_STATE, BATCH_SAVED_UNVERIFIED_STATE}
|
||||
@@ -208,7 +214,8 @@ def execute_batch(
|
||||
persistence['completed_units'] = 1
|
||||
else:
|
||||
updated = candidate
|
||||
if updated.completed_items <= progress.completed_items or updated.total_items != progress.total_items:
|
||||
if ((updated.completed_items <= progress.completed_items and last_result.state != 'pending_save')
|
||||
or updated.total_items != progress.total_items):
|
||||
_write_uncertain_flag(preparer.data_root / 'quick-run/uncertain.flag', 'batch_progress_mismatch')
|
||||
raise TaskCenterError('quick_run_queue_progress', '执行器返回后队列进度异常,已停止,避免重复执行。')
|
||||
# Keep every verified step: one project can contain many sheets and rules.
|
||||
@@ -266,7 +273,7 @@ def execute_batch(
|
||||
feedback = '未命中已跳过,继续下一项' if last_result.state == 'no_match' else (
|
||||
'失败已记录,继续下一项'
|
||||
if last_result.state == BATCH_FAILED_STATE
|
||||
else '已保存并校验,继续下一项'
|
||||
else '替换已暂存,等待工程统一保存回读' if last_result.state == 'pending_save' else '已保存并校验,继续下一项'
|
||||
)
|
||||
service._batch_feedback = (task_id, progress, feedback)
|
||||
return BatchRunResult(
|
||||
|
||||
@@ -31,7 +31,7 @@ def write_release_event(root, path, record, phase, *, context=None, reason='batc
|
||||
'generation': record.get('generation'), 'desktop': record.get('desktop'),
|
||||
'cad_pid': record.get('cad_pid'), 'cad_guid': record.get('cad_guid'),
|
||||
'reason': reason, 'result': 'releasing' if phase == 'started' else (
|
||||
'released' if phase == 'succeeded' else 'blocked'),
|
||||
'released' if phase == 'succeeded' else 'isolated' if phase == 'isolated' else 'blocked'),
|
||||
'elapsed_seconds': elapsed, 'record_path': str(path),
|
||||
'desktop_handle_closed': cleanup.get('desktop_handle_closed'),
|
||||
'desktop_disappeared': disappeared, 'cad_exit_code': cad.get('cad_exit_code'),
|
||||
@@ -39,7 +39,8 @@ def write_release_event(root, path, record, phase, *, context=None, reason='batc
|
||||
'cad_shutdown': cad, 'shutdown_warning': record.get('shutdown_warning'),
|
||||
'retries': record.get('retries', {}), 'cleanup': cleanup, 'error': str(error)}
|
||||
title = {'started': '开始释放后台资源', 'succeeded': '后台资源释放成功',
|
||||
'failed': '后台资源释放失败,资源释放待处理'}[phase]
|
||||
'failed': '后台资源释放失败,资源释放待处理',
|
||||
'isolated': '后台写入进程已退出,残留桌面已隔离(未确认释放)'}[phase]
|
||||
purpose = {'batch_end': '批次结束', 'rebuild': '安全重建', 'manual_retry': '重新清理',
|
||||
'restart_recheck': '重启后重新检查'}.get(reason, reason)
|
||||
cad_text = f"CAD PID={details['cad_pid']}" if details['cad_pid'] else (
|
||||
@@ -56,7 +57,7 @@ def write_release_event(root, path, record, phase, *, context=None, reason='batc
|
||||
if error:
|
||||
message += ' · 原因:' + str(error)
|
||||
message = message.replace('\r', '\\r').replace('\n', '\\n')
|
||||
level = 'ERROR' if phase == 'failed' else 'INFO'
|
||||
level = 'ERROR' if phase == 'failed' else 'WARNING' if phase == 'isolated' else 'INFO'
|
||||
timestamp = datetime.now(timezone.utc).isoformat(timespec='milliseconds')
|
||||
errors = []
|
||||
try:
|
||||
|
||||
@@ -51,7 +51,7 @@ def _valid_record(record, path):
|
||||
and type(record.get('generation')) is int and record['generation'] >= 1
|
||||
and isinstance(record.get('desktop'), str)
|
||||
and re.fullmatch('dx-[0-9a-f]{32}', record['desktop']) is not None
|
||||
and record.get('state') in {'starting', 'ready', 'recycling', 'closing', 'blocked', 'released'}
|
||||
and record.get('state') in {'starting', 'ready', 'recycling', 'closing', 'blocked', 'released', 'isolated'}
|
||||
and isinstance(processes, list) and all(isinstance(item, dict)
|
||||
and type(item.get('pid')) is int and item['pid'] > 0
|
||||
and 'creation_time' in item and (item['creation_time'] is None
|
||||
@@ -66,14 +66,17 @@ def _valid_record(record, path):
|
||||
|
||||
def pending_resources(root):
|
||||
pending = []
|
||||
for path in sorted(internal_path(canonical_path(root) / 'batch-resources').glob('*/session.json')):
|
||||
directory = internal_path(canonical_path(root) / 'batch-resources')
|
||||
paths = (*directory.glob('*/session.json'), *directory.glob('*/isolated-generation-*.json'))
|
||||
for path in sorted(paths):
|
||||
path = canonical_path(path)
|
||||
try:
|
||||
record = json.loads(internal_path(path).read_text(encoding='utf-8'))
|
||||
if not _valid_record(record, path):
|
||||
raise ValueError('invalid resource ownership record')
|
||||
if record.get('state') != 'released' or not _released_evidence(record):
|
||||
pending.append(dict(record, record_path=str(path)))
|
||||
pending.append(dict(record, record_path=str(path),
|
||||
blocking=not (record.get('state') == 'isolated' and _isolation_evidence(record))))
|
||||
except (OSError, ValueError, TypeError) as error:
|
||||
pending.append({'state': 'blocked', 'record_path': str(path), 'error': str(error)})
|
||||
import sys
|
||||
@@ -109,6 +112,57 @@ def pending_resources(root):
|
||||
return tuple(pending)
|
||||
|
||||
|
||||
def resource_blockers(records):
|
||||
"""Only a validated isolated desktop warning may leave the resource gate open."""
|
||||
return tuple(item for item in records
|
||||
if not (item.get('state') == 'isolated' and item.get('blocking') is False))
|
||||
|
||||
|
||||
def blocking_resources(root):
|
||||
return resource_blockers(pending_resources(root))
|
||||
|
||||
|
||||
def writer_identities(record):
|
||||
identities = []
|
||||
for item in [*record.get('writer_identities', ()), *record.get('processes', ()),
|
||||
*([record['cad_process']] if record.get('cad_process') else [])]:
|
||||
if item not in identities:
|
||||
identities.append(item)
|
||||
if record.get('cad_pid') is not None and not any(
|
||||
item.get('pid') == record['cad_pid'] for item in identities):
|
||||
raise ValueError('CAD process identity is missing')
|
||||
if any(type(item.get('pid')) is not int or item['pid'] <= 0
|
||||
or not isinstance(item.get('creation_time'), str) or not item['creation_time']
|
||||
for item in identities):
|
||||
raise ValueError('Exact writer process identity is missing')
|
||||
return identities
|
||||
|
||||
|
||||
def isolation_proof(record):
|
||||
"""Certify handle closure and exact writer exit, never a desktop disappearance."""
|
||||
cleanup = record.get('cleanup') or {}
|
||||
if (cleanup.get('desktop_handle_closed') is not True
|
||||
or cleanup.get('owned_cleanup_complete') is not True):
|
||||
raise ValueError('Owned resource cleanup is not proven')
|
||||
identities = writer_identities(record)
|
||||
if not all(_process_gone(item) for item in identities):
|
||||
raise ValueError('Owned writer process is still active')
|
||||
return {'session_id': record['session_id'], 'generation': record['generation'],
|
||||
'desktop': record['desktop'], 'desktop_handle_closed': True, 'desktop_released': False,
|
||||
'processes_exited': True, 'processes': identities, 'observed_at': time.time()}
|
||||
|
||||
|
||||
def _isolation_evidence(record):
|
||||
try:
|
||||
proof = record.get('isolation_proof', {})
|
||||
current = isolation_proof(record)
|
||||
return (isinstance(proof, dict) and all(proof.get(key) == current[key] for key in
|
||||
('session_id', 'generation', 'desktop', 'desktop_handle_closed', 'desktop_released',
|
||||
'processes_exited', 'processes')))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _released_evidence(record):
|
||||
"""A state label alone must never reopen the physical resource gate."""
|
||||
proof = record.get('release_proof', {})
|
||||
@@ -126,7 +180,7 @@ def _released_evidence(record):
|
||||
|
||||
|
||||
def guard_pending_resources(root):
|
||||
if pending_resources(root):
|
||||
if blocking_resources(root):
|
||||
raise BatchResourceCleanupError('上一批资源尚未确认释放;请先重试释放资源,再开始新批次。')
|
||||
|
||||
|
||||
@@ -216,7 +270,7 @@ def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False)
|
||||
if not record.get('session_id'):
|
||||
continue # Corrupt evidence cannot authorize resource actions.
|
||||
log('started')
|
||||
identities = list(record.get('processes', ()))
|
||||
identities = writer_identities(record)
|
||||
cad_identity = record.get('cad_process')
|
||||
if record.get('cad_pid') is not None:
|
||||
if (not isinstance(cad_identity, dict) or cad_identity.get('pid') != record['cad_pid']
|
||||
@@ -230,11 +284,24 @@ def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False)
|
||||
continue
|
||||
desktop = record.get('desktop')
|
||||
if desktop:
|
||||
_Win32Api().confirm_desktop_released(desktop)
|
||||
try:
|
||||
_Win32Api().confirm_desktop_released(desktop)
|
||||
except Exception as error:
|
||||
# A residual desktop name is only a warning after owned
|
||||
# handle closure and independently revalidated writer exit.
|
||||
proof = isolation_proof(record)
|
||||
record.pop('record_path', None)
|
||||
record.update(state='isolated', blocking=False, isolation_proof=proof,
|
||||
isolation_warning=str(error))
|
||||
write_record(path, record)
|
||||
log('isolated', str(error))
|
||||
continue
|
||||
# After restart only confirm disappearance. Never attach to COM,
|
||||
# close a project, or terminate a PID whose handles we no longer own.
|
||||
record.pop('record_path', None)
|
||||
record = dict(record, state='released', reconciled=True, released_at=time.time(),
|
||||
record = dict(record, state='released', blocking=False, reconciled=True, released_at=time.time(),
|
||||
release_results={'mentor_released': True, 'desktop_released': True},
|
||||
release_state={'mentor': 'released', 'desktop': 'released'}, wait_reason='',
|
||||
release_proof={'generation': record['generation'], 'desktop_released': True,
|
||||
'processes_exited': True, 'processes': identities, 'method': 'restart_observation'})
|
||||
write_record(path, record)
|
||||
|
||||
@@ -11,7 +11,8 @@ from threading import Lock
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from .batch_resources import (BatchResourceCleanupError, LIVE_RESOURCES, cleanup_pending_resources,
|
||||
guard_pending_resources, pending_resources, process_identity, project_checkpoint_released, write_record)
|
||||
guard_pending_resources, pending_resources, process_identity, project_checkpoint_released, write_record,
|
||||
isolation_proof)
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import canonical_path, internal_path, legacy_path
|
||||
from .isolated_desktop import PrivateDesktop, ProcessNotStartedError
|
||||
@@ -202,12 +203,18 @@ class BatchCadRuntime:
|
||||
def _ensure_desktop(self, abort_event=None):
|
||||
if self.record['state'] == 'blocked':
|
||||
raise BatchResourceCleanupError('当前批次资源已阻断,不能启动新的工作进程。')
|
||||
if self.record['state'] == 'isolated':
|
||||
if self.desktop is not None:
|
||||
raise BatchResourceCleanupError('隔离桌面已停止使用,请为后续工程创建新的运行会话。')
|
||||
write_record(self.path.parent / f'isolated-generation-{self.generation}.json', self.record)
|
||||
if self.desktop is None:
|
||||
check_cancelled(self.stop_event if abort_event is None else abort_event)
|
||||
self.generation += 1
|
||||
name = 'dx-' + uuid4().hex
|
||||
self._save(state='starting', generation=self.generation, desktop=name,
|
||||
processes=[], cad_pid=None, cad_guid=None, checkpoints={}, native_operations={},
|
||||
processes=[], writer_identities=[], cad_pid=None, cad_guid=None, checkpoints={}, native_operations={},
|
||||
blocking=True, isolation_proof=None,
|
||||
stopping_reason='', wait_reason='', primary_error=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
|
||||
@@ -226,6 +233,8 @@ class BatchCadRuntime:
|
||||
identity = process_identity(process)
|
||||
if identity not in self.record['processes']:
|
||||
self.record['processes'].append(identity)
|
||||
if identity not in self.record.setdefault('writer_identities', []):
|
||||
self.record['writer_identities'].append(identity)
|
||||
self._save()
|
||||
|
||||
def _release_process(self, process, *, desktop=None, generation=None):
|
||||
@@ -245,6 +254,9 @@ 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)
|
||||
for process in getattr(self.cad, '_retained_processes', ()):
|
||||
if process not in processes:
|
||||
processes.append(process)
|
||||
if not processes:
|
||||
cleanup = getattr(self.desktop, 'cleanup_record', None) or {}
|
||||
# Closing our handle follows owned-process cleanup. An external
|
||||
@@ -403,10 +415,47 @@ class BatchCadRuntime:
|
||||
key = str(root).casefold()
|
||||
self.record['checkpoints'][key] = attempt_id
|
||||
self._save(state='ready')
|
||||
write_record(root / 'project-checkpoint.json', {'version': 1, 'resource_record': str(self.path),
|
||||
checkpoint = {'version': 1, 'resource_record': str(self.path),
|
||||
'session_id': self.session_id, 'generation': self.generation, 'attempt_id': attempt_id,
|
||||
'evidence_root': str(root), 'project_path': str(project), 'project_closed': True,
|
||||
'worker_closed': True, 'cad_pid': self.record['cad_pid'], 'cad_guid': self.record['cad_guid']})
|
||||
'worker_closed': True, 'cad_pid': self.record['cad_pid'], 'cad_guid': self.record['cad_guid']}
|
||||
request_path = internal_path(root / 'project-session.request')
|
||||
if request_path.is_file():
|
||||
request = request_path.read_text(encoding='utf-8-sig').strip().split('\t')
|
||||
if (len(request) == 3 and len(request[0]) == 32
|
||||
and all(character in '0123456789abcdef' for character in request[0])
|
||||
and canonical_path(request[1]) == project):
|
||||
marker = internal_path(root / ('project-commit-' + request[0] + '.tsv'))
|
||||
if marker.is_file():
|
||||
from .execution_proof import capture_project_commit, bind_project_commit_source
|
||||
from .quick_run import _decode_vbs_field
|
||||
rows = [line.split('\t') for line in marker.read_text(encoding='utf-8-sig').splitlines() if line]
|
||||
if (not rows or len(rows[0]) != 3 or rows[0][0] != request[0] or rows[0][2] != 'project_verified'
|
||||
or canonical_path(_decode_vbs_field(rows[0][1])) != project
|
||||
or any(len(row) != 2 for row in rows[1:])):
|
||||
raise WorkerMonitorError('native project commit marker is not bound to the closed project')
|
||||
jobs = [row[0] for row in rows[1:]]
|
||||
expected_jobs = [record['job_id'] for _, record in self._current_attempts]
|
||||
expected_jobs = expected_jobs[expected_jobs.index(self.record['active_job']):]
|
||||
if not jobs or len(set(jobs)) != len(jobs) or jobs != expected_jobs[:len(jobs)]:
|
||||
raise WorkerMonitorError('native project commit marker does not cover an authorized prefix')
|
||||
proof = capture_project_commit(self.root, root, {'session_token': request[0],
|
||||
'project_path': str(project).casefold(), 'jobs_json': json.dumps(jobs)})
|
||||
proof = bind_project_commit_source(proof, self.root, root, project)
|
||||
proof['marker_sha256'] = hashlib.sha256(marker.read_bytes()).hexdigest()
|
||||
proof['files'].append({'path': str(canonical_path(marker)), 'sha256': proof['marker_sha256']})
|
||||
readback_names = []
|
||||
for job, outcome in proof['outcomes'].items():
|
||||
readback_names.append('post-state-' + job + '.tsv')
|
||||
if outcome == 'saved_ok':
|
||||
readback_names.extend(('snapshot-' + job + '.tsv', 'snapshot-' + job + '.tsv.native.json',
|
||||
'value-readback-' + job + '.tsv'))
|
||||
proof['readback_files'] = {name: hashlib.sha256(internal_path(root / name).read_bytes()).hexdigest()
|
||||
for name in readback_names}
|
||||
proof['native_attempt'] = {'session_id': self.session_id, 'generation': self.generation,
|
||||
'attempt_id': attempt_id}
|
||||
checkpoint['project_commit_source'] = proof
|
||||
write_record(root / 'project-checkpoint.json', checkpoint)
|
||||
self._active_attempts = []
|
||||
|
||||
def _certify_unlaunched_worker(self, root, project, command, attempt_id, expected, before, inputs, *, failure=None,
|
||||
@@ -514,6 +563,11 @@ class BatchCadRuntime:
|
||||
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 == 75 and not self.read_only:
|
||||
result.prewrite_pause = self._certify_prewrite_pause(
|
||||
root, project, attempt_id, expected, before, inputs,
|
||||
getattr(result, 'prewrite_pause', {}), abort_event)
|
||||
return result
|
||||
if result.returncode == 74 and not self.read_only:
|
||||
from .batch_attempt import can_retry_attempt
|
||||
pause = getattr(result, 'startup_pause', {})
|
||||
@@ -643,6 +697,87 @@ class BatchCadRuntime:
|
||||
self.close(rebuilding=True) # Prove disappearance before creating another.
|
||||
self.desktop = self.cad = None
|
||||
|
||||
def _certify_prewrite_pause(self, root, project, attempt_id, expected, before, inputs, pause, abort_event):
|
||||
from .batch_attempt import can_retry_attempt, read_attempt
|
||||
from .discovery_cache import project_fingerprint
|
||||
from .project_session_health import _source_parameters
|
||||
from .quick_run import _decode_vbs_field
|
||||
try:
|
||||
request_path = internal_path(root / 'project-session.request')
|
||||
request_bytes = request_path.read_bytes()
|
||||
request = request_bytes.decode('utf-8-sig').strip().split('\t')
|
||||
original = inputs['project-session.request'].decode('utf-8-sig').strip().split('\t')
|
||||
if (len(request) != 3 or len(original) != 3 or request[:2] != original[:2]
|
||||
or pause.get('session_token') != request[0] or len(request[0]) != 32
|
||||
or pause.get('job_id') != request[2] or canonical_path(request[1]) != project
|
||||
or canonical_path(pause.get('project_path', '')) != project
|
||||
or pause.get('worker_tree_exited') is not True
|
||||
or type(pause.get('sequence')) is not int or pause['sequence'] <= 0
|
||||
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 internal_path(root / 'command.tsv').read_bytes() != inputs['command.tsv']):
|
||||
raise ValueError('prewrite pause ownership is not bound')
|
||||
selected = [(path, record) for path, record in expected if record['job_id'] == request[2]]
|
||||
if len(selected) != 1 or not can_retry_attempt(*selected[0]):
|
||||
raise ValueError('current paused job may have mutated')
|
||||
jobs = [record['job_id'] for _, record in expected]
|
||||
prefix_jobs = set(jobs[:jobs.index(request[2])])
|
||||
mutated = set()
|
||||
for path, record in expected:
|
||||
actual = read_attempt(path)
|
||||
if any(actual.get(key) != value for key, value in record.items() if key != 'state'):
|
||||
raise ValueError('batch attempt identity changed')
|
||||
if actual['state'] == 'mutation_possible':
|
||||
mutated.add(record['job_id'])
|
||||
marker_path = root / ('project-pause-' + request[0] + '.tsv')
|
||||
marker = internal_path(marker_path).read_text(encoding='utf-8-sig').strip().split('\t')
|
||||
if (len(marker) != 4 or marker[0] != request[0] or marker[2:] != [request[2], 'prewrite_closed']
|
||||
or canonical_path(_decode_vbs_field(marker[1])) != project):
|
||||
raise ValueError('prewrite project closure marker is missing or stale')
|
||||
manifest_path = root / ('project-commit-' + request[0] + '.tsv')
|
||||
committed = {}
|
||||
files = [marker_path, *(path for path, _ in expected)]
|
||||
if internal_path(manifest_path).exists():
|
||||
rows = [line.split('\t') for line in internal_path(manifest_path).read_text(encoding='utf-8-sig').splitlines()]
|
||||
if (not rows or len(rows[0]) != 3 or rows[0][0] != request[0]
|
||||
or canonical_path(_decode_vbs_field(rows[0][1])) != project or rows[0][2] != 'project_verified'):
|
||||
raise ValueError('committed prefix manifest is not bound')
|
||||
for row in rows[1:]:
|
||||
if (len(row) != 2 or row[0] not in prefix_jobs or row[0] in committed
|
||||
or row[1] not in {'saved_ok', 'no_match'}):
|
||||
raise ValueError('committed prefix manifest contains an unrelated result')
|
||||
committed[row[0]] = row[1]
|
||||
files.append(manifest_path)
|
||||
after = project_fingerprint(project, self.root)
|
||||
if (after is None or not mutated <= committed.keys()
|
||||
or not committed and (before is None or before != after)):
|
||||
raise ValueError('source changes lack a verified committed prefix')
|
||||
self._checkpoint(root, project, attempt_id)
|
||||
files.append(root / 'project-checkpoint.json')
|
||||
current = internal_path(root / 'current-command.tsv')
|
||||
status = internal_path(root / 'status.tsv')
|
||||
proof = dict(pause, phase='before_native_dispatch', task_id=selected[0][1]['task_id'],
|
||||
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(after).encode()).hexdigest(), committed_prefix=committed,
|
||||
pause_marker_path=str(marker_path),
|
||||
pause_marker_sha256=hashlib.sha256(internal_path(marker_path).read_bytes()).hexdigest(),
|
||||
commit_manifest_path=str(manifest_path) if committed else None,
|
||||
commit_manifest_sha256=hashlib.sha256(internal_path(manifest_path).read_bytes()).hexdigest() if committed else None,
|
||||
request_sha256=hashlib.sha256(request_bytes).hexdigest(),
|
||||
status_sha256=hashlib.sha256(status.read_bytes()).hexdigest() if status.exists() else None,
|
||||
current_command_sha256=hashlib.sha256(current.read_bytes()).hexdigest() if current.exists() else None,
|
||||
batch_attempts=[{'path': str(path), 'expected': record} for path, record in selected])
|
||||
proof.update(_source_parameters(project, self.root))
|
||||
proof_path = root / ('prewrite-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, *files]]
|
||||
return proof
|
||||
except (OSError, ValueError, TypeError, KeyError, AttributeError) as error:
|
||||
raise WorkerMonitorError('prewrite pause lacks bound current-job and committed-prefix proof: ' + str(error)) from error
|
||||
|
||||
def _retain_uncertain(self, root, project, expected, error):
|
||||
if self.read_only:
|
||||
return
|
||||
@@ -747,7 +882,7 @@ class BatchCadRuntime:
|
||||
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':
|
||||
if self.record['state'] in {'released', 'isolated'}:
|
||||
return
|
||||
reason = reason or ('rebuild' if rebuilding else 'batch_end')
|
||||
if self._close_failure is not None:
|
||||
@@ -807,30 +942,41 @@ class BatchCadRuntime:
|
||||
raise
|
||||
self._close_failure = None
|
||||
self._close_failure_rebuild = False
|
||||
self._release_log('succeeded', reason=reason, elapsed=time.monotonic() - started)
|
||||
self._release_log('isolated' if self.record['state'] == 'isolated' else 'succeeded',
|
||||
reason=reason, elapsed=time.monotonic() - started)
|
||||
|
||||
def _close_resources(self, *, rebuilding=False):
|
||||
from .operation_diagnostics import record_operation
|
||||
operation_root = self._active_evidence or self.path.parent
|
||||
started = time.monotonic()
|
||||
errors = []
|
||||
shutdown_errors = []
|
||||
retained_cad = False
|
||||
phases = {'mentor': 'closing' if self.cad is not None else 'released', 'desktop': 'waiting_for_mentor'}
|
||||
try:
|
||||
self._save(state='closing', release_state=phases)
|
||||
self._save(state='closing', release_state=phases,
|
||||
wait_reason='mentor_exit' if self.cad is not None else 'desktop_release',
|
||||
stopping_reason=getattr(self.stop_event, 'stopping_reason', ''),
|
||||
primary_error=self.record.get('primary_error') or getattr(self.stop_event, 'primary_error', ''))
|
||||
except Exception as error:
|
||||
errors.append('resource journal: ' + str(error))
|
||||
if self.cad is not None:
|
||||
cad = self.cad
|
||||
try:
|
||||
failure = getattr(self, '_cad_close_error', None)
|
||||
record_operation(operation_root, 'mentor_exit', 'enter')
|
||||
cad.__exit__(type(failure) if failure is not None else None, failure, None)
|
||||
record_operation(operation_root, 'mentor_exit', 'return')
|
||||
self.cad = None
|
||||
except Exception as error:
|
||||
record_operation(operation_root, 'mentor_exit', 'error', error=str(error))
|
||||
if rebuilding:
|
||||
self.record['shutdown_warning'] = str(error)
|
||||
# A rebuild must not proceed while the previous CAD owner has
|
||||
# an unconfirmed shutdown. Keep the warning for diagnostics,
|
||||
# but retain the failure in the resource gate as well.
|
||||
errors.append(str(error))
|
||||
shutdown_errors.append(str(error))
|
||||
from .read_recovery import process_tree_exited
|
||||
process = getattr(cad, 'cad', None)
|
||||
processes = [*getattr(cad, '_retained_processes', ()),
|
||||
@@ -853,9 +999,13 @@ class BatchCadRuntime:
|
||||
phases['mentor'] = 'failed' if retained_cad else 'released'
|
||||
if self.desktop is not None and not retained_cad:
|
||||
phases['desktop'] = 'closing'
|
||||
self.record['wait_reason'] = 'desktop_release'
|
||||
try:
|
||||
record_operation(operation_root, 'desktop_release', 'enter')
|
||||
self.desktop.close()
|
||||
record_operation(operation_root, 'desktop_release', 'return')
|
||||
except Exception as error:
|
||||
record_operation(operation_root, 'desktop_release', 'error', error=str(error))
|
||||
errors.append(str(error))
|
||||
self._timing('batch_release', started)
|
||||
self.record['cleanup'] = getattr(self.desktop, 'cleanup_record', None)
|
||||
@@ -868,7 +1018,27 @@ class BatchCadRuntime:
|
||||
'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 not retained_cad and not self.record['release_results']['desktop_released']:
|
||||
try:
|
||||
proof = isolation_proof(self.record)
|
||||
if not self._other_writers_exited():
|
||||
raise ValueError('Retained writer ownership is still active')
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
phases['desktop'] = 'isolated'
|
||||
self._save(state='isolated', blocking=False, isolation_proof=proof,
|
||||
isolation_warning='; '.join(errors), release_state=phases, wait_reason='')
|
||||
LIVE_RESOURCES.pop(str(self.path), None)
|
||||
if shutdown_errors:
|
||||
raise BatchResourceCleanupError('; '.join(shutdown_errors), completed_result=self.result)
|
||||
return
|
||||
if errors:
|
||||
if (errors == shutdown_errors and not retained_cad and self.owned_processes_exited()
|
||||
and self._other_writers_exited() and self.record['release_results']['desktop_released']):
|
||||
self.record['shutdown_warning'] = '; '.join(shutdown_errors)
|
||||
self._record_release()
|
||||
raise BatchResourceCleanupError('; '.join(errors), completed_result=self.result)
|
||||
self._save(state='blocked', error='; '.join(errors))
|
||||
raise BatchResourceCleanupError('; '.join(errors), completed_result=self.result)
|
||||
self._record_release()
|
||||
@@ -879,5 +1049,57 @@ class BatchCadRuntime:
|
||||
'cad_pid': self.record['cad_pid'], 'cad_guid': self.record['cad_guid'],
|
||||
'cleanup': self.record['cleanup'], 'released_at': released_at}
|
||||
releases = [*self.record.get('generation_releases', ()), release]
|
||||
self._save(state='released', released_at=released_at, processes=[], generation_releases=releases)
|
||||
self._save(state='released', blocking=False, released_at=released_at, processes=[], generation_releases=releases,
|
||||
wait_reason='')
|
||||
LIVE_RESOURCES.pop(str(self.path), None)
|
||||
|
||||
def _other_writers_exited(self):
|
||||
from .isolated_cad import RETAINED_CAD_SESSIONS
|
||||
from .read_recovery import process_tree_exited
|
||||
from .worker_monitor import RETAINED_WORKERS, _worker_tree_exited
|
||||
return (all(all(process_tree_exited(process) for process in session._owned_processes())
|
||||
for session in tuple(RETAINED_CAD_SESSIONS.values())
|
||||
if session.root.is_relative_to(self.root))
|
||||
and all(_worker_tree_exited(entry['process'], entry['owned'])
|
||||
for entry in tuple(RETAINED_WORKERS.values()) if entry['root'].is_relative_to(self.root)))
|
||||
|
||||
def release_failed_project(self, error, evidence_root):
|
||||
"""Release proven stopped writers; the failed project's business evidence stays untouched."""
|
||||
from .stop_control import protect_interruption
|
||||
protect_interruption(evidence_root, 'project_failure: ' + str(error))
|
||||
request = getattr(self.stop_event, 'request_failure_cleanup', None)
|
||||
if request is not None:
|
||||
request(evidence_root, error)
|
||||
if self.cad is not None:
|
||||
self.cad.stop_control = self.stop_event
|
||||
self._cad_close_error = error
|
||||
cleanup_warning = None
|
||||
try:
|
||||
self.close(reason='project_failure')
|
||||
except BatchResourceCleanupError as cleanup:
|
||||
from .batch_resources import blocking_resources
|
||||
if (self.record['state'] not in {'released', 'isolated'} or blocking_resources(self.root)
|
||||
or not self.owned_processes_exited() or not self._other_writers_exited()):
|
||||
raise
|
||||
cleanup_warning = str(cleanup)
|
||||
error.shutdown_warning = cleanup_warning
|
||||
self.record.setdefault('generation_shutdown_warnings', []).append({
|
||||
'generation': self.generation, 'error': cleanup_warning, 'cad_shutdown': self.record.get('cad_shutdown')})
|
||||
self._save(shutdown_warning=cleanup_warning)
|
||||
if ((self.generation and not self.owned_processes_exited()) or not self._other_writers_exited()):
|
||||
return False
|
||||
from .batch_resources import blocking_resources
|
||||
if blocking_resources(self.root):
|
||||
return False
|
||||
write_record(canonical_path(evidence_root) / 'project-resource-release.json', {
|
||||
'version': 1, 'session_id': self.session_id, 'generation': self.generation,
|
||||
'resource_record': str(self.path), 'writers_exited': True,
|
||||
'resource_state': self.record['state'], 'desktop_released':
|
||||
self.record.get('release_results', {}).get('desktop_released') is True,
|
||||
'business_uncertainty_preserved': True})
|
||||
self.desktop = self.cad = None
|
||||
self._active_evidence = None
|
||||
self._active_attempts = []
|
||||
self._close_failure = None
|
||||
self._cad_close_error = None
|
||||
return True
|
||||
@@ -305,9 +305,9 @@ def pending_supervisors(root):
|
||||
|
||||
def reconcile_supervisors(root):
|
||||
"""Recheck orphan ownership only; this never launches or replays a job."""
|
||||
from .batch_resources import _process_gone, pending_resources, write_record
|
||||
from .batch_resources import _process_gone, blocking_resources, write_record
|
||||
from .read_recovery import process_tree_exited
|
||||
physical = pending_resources(root)
|
||||
physical = blocking_resources(root)
|
||||
for record in pending_supervisors(root):
|
||||
owner = (_LIVE_SUPERVISORS.get(canonical_path(record['record_path']))
|
||||
or _ACTIVE_SUPERVISORS.get(canonical_path(record['record_path'])))
|
||||
@@ -348,21 +348,26 @@ def _environment():
|
||||
|
||||
def _finish_response(root, journal, response, context):
|
||||
"""A supervisor exit may release its last USER reference. Never repeat work."""
|
||||
from .batch_resources import cleanup_pending_resources, write_record
|
||||
from .batch_resources import cleanup_pending_resources, resource_blockers, write_record
|
||||
from .supervisor_result import validated_outcome, resource_pending_error, application_shutdown_error
|
||||
result, error, primary = validated_outcome(journal['operation'], response)
|
||||
pending = cleanup_pending_resources(root, logging_context=context)
|
||||
related = tuple(item for item in pending if item.get('session_id') == journal['batch_id'] or not item.get('session_id'))
|
||||
journal['state'] = 'blocked' if related else 'finished'
|
||||
journal['outcome'] = ('completed_resources_pending' if related and response.get('business_succeeded')
|
||||
blockers = resource_blockers(related)
|
||||
warnings = tuple(item for item in related if item not in blockers)
|
||||
journal['state'] = 'blocked' if blockers else 'finished'
|
||||
journal['outcome'] = ('completed_resources_pending' if blockers and response.get('business_succeeded')
|
||||
else response.get('status', 'interrupted'))
|
||||
journal['resource_recheck'] = {'pending': bool(related), 'checked_at': time.time()}
|
||||
journal['resource_recheck'] = {'pending': bool(blockers), 'warnings': list(warnings),
|
||||
'desktop_released': not related, 'owned_writers_exited': not blockers, 'checked_at': time.time()}
|
||||
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
|
||||
if related:
|
||||
if blockers:
|
||||
raise resource_pending_error(journal['operation'], result, error, primary)
|
||||
for failure in (error, primary):
|
||||
if failure is not None:
|
||||
failure.resources_released = True
|
||||
failure.resources_released = not warnings
|
||||
failure.owned_writers_exited = True
|
||||
failure.resource_warnings = warnings
|
||||
resource_path = internal_path(Path(root) / 'batch-resources' / journal['batch_id'] / 'session.json')
|
||||
def preserve_shutdown_failure(detail):
|
||||
try:
|
||||
@@ -373,7 +378,9 @@ def _finish_response(root, journal, response, context):
|
||||
journal['shutdown_record_error'] = str(record_error)
|
||||
def shutdown_failure():
|
||||
failure = application_shutdown_error(result, error, primary)
|
||||
failure.resources_released = True
|
||||
failure.resources_released = not warnings
|
||||
failure.owned_writers_exited = True
|
||||
failure.resource_warnings = warnings
|
||||
return failure
|
||||
try:
|
||||
resource = json.loads(resource_path.read_text(encoding='utf-8'))
|
||||
@@ -558,6 +565,7 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
on_phase(*payload)
|
||||
elif value['type'] == 'state':
|
||||
state = decode(value['payload'])
|
||||
service._supervisor_state = state
|
||||
business_watch.observe('state', state, time.monotonic())
|
||||
service._task_queue_feedback = getattr(service, '_workspace_queue_context', None) or state['queue']
|
||||
service._batch_feedback = state['batch']
|
||||
@@ -578,6 +586,7 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
service._task_queue_feedback = None
|
||||
service._batch_feedback = None
|
||||
service._supervisor_waiting = False
|
||||
service._supervisor_state = None
|
||||
service._supervisor_business_stalled = False
|
||||
service._supervisor_dialog_state = None
|
||||
try:
|
||||
@@ -616,10 +625,10 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
exit_code=getattr(process, 'returncode', None),
|
||||
stdout_chars=len(stdout_tail), stderr_chars=len(stderr_tail))
|
||||
if force_accepted:
|
||||
from .batch_resources import cleanup_pending_resources
|
||||
from .batch_resources import cleanup_pending_resources, resource_blockers
|
||||
try:
|
||||
pending = cleanup_pending_resources(root, logging_context=service._logging)
|
||||
if pending:
|
||||
if resource_blockers(pending):
|
||||
ownership_cleanup_error = TaskCenterError('batch_resources_pending', '强制结束后的资源仍待清理。')
|
||||
except Exception as error:
|
||||
ownership_cleanup_error = error
|
||||
@@ -628,7 +637,8 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
failure = TaskCenterError('mentor_release_required' if automatic else 'user_forced_stop',
|
||||
'执行失败,已自动收尾本批后台进程;已有结果保留,当前结果待核验。' if automatic else
|
||||
'已按确认强制结束;已保存的执行证据保留,当前结果待核验。请先核验恢复,不要重复替换。')
|
||||
failure.resources_released = ownership_cleanup_error is None
|
||||
failure.resources_released = ownership_cleanup_error is None and not pending
|
||||
failure.owned_writers_exited = 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))
|
||||
@@ -688,7 +698,7 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
raise failure from protection_error
|
||||
# Recheck physical resources even when final business results are
|
||||
# missing; this never authorizes repeating the interrupted job.
|
||||
from .batch_resources import cleanup_pending_resources
|
||||
from .batch_resources import cleanup_pending_resources, resource_blockers
|
||||
outstanding = cleanup_pending_resources(root, logging_context=service._logging)
|
||||
failure = cause if isinstance(cause, TaskCenterError) else TaskCenterError(
|
||||
'supervisor_interrupted', '批次监督进程未留下可信结果;保留保护记录,不自动重试。' +
|
||||
@@ -697,6 +707,8 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
from .read_recovery import process_tree_exited
|
||||
failure.resources_released = (not outstanding and ownership_cleanup_error is None
|
||||
and (process is None or process_tree_exited(process)))
|
||||
failure.owned_writers_exited = (not resource_blockers(outstanding) and ownership_cleanup_error is None
|
||||
and (process is None or process_tree_exited(process)))
|
||||
raise failure from (transport_error or error)
|
||||
if transport_error is not None:
|
||||
if response['payload']['business_succeeded']:
|
||||
@@ -705,9 +717,13 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
|
||||
else:
|
||||
_mark_interrupted(root, journal, transport_error)
|
||||
failure = resource_pending_error(operation, decoded_result, transport_error, decoded_primary)
|
||||
from .batch_resources import pending_resources
|
||||
from .batch_resources import pending_resources, resource_blockers
|
||||
from .read_recovery import process_tree_exited
|
||||
failure.resources_released = (ownership_cleanup_error is None and not pending_resources(root)
|
||||
pending = pending_resources(root)
|
||||
failure.resources_released = (ownership_cleanup_error is None and not pending
|
||||
and process is not None and process_tree_exited(process))
|
||||
failure.owned_writers_exited = (ownership_cleanup_error is None and not resource_blockers(pending)
|
||||
and process is not None and process_tree_exited(process))
|
||||
failure.resource_warnings = tuple(row for row in pending if row not in resource_blockers(pending))
|
||||
raise failure
|
||||
return _finish_response(root, journal, response['payload'], service._logging)
|
||||
@@ -14,6 +14,14 @@ from uuid import UUID
|
||||
from .path_access import internal_path, canonical_path
|
||||
from .supervisor_protocol import VERSION, OPERATIONS, valid_journal, encode, decode, encode_error
|
||||
|
||||
|
||||
def _persist_result(directory, envelope):
|
||||
from .batch_resources import write_record
|
||||
from .operation_diagnostics import operation_span
|
||||
with operation_span(directory, 'result_persistence', item_id=envelope['attempt_id']):
|
||||
write_record(directory / 'result.json', envelope)
|
||||
|
||||
|
||||
def _output_stream():
|
||||
if sys.stdout is not None:
|
||||
return sys.stdout, False
|
||||
@@ -85,7 +93,7 @@ def consume_manual_dialog_actions(directory, runtime, batch_id, attempt_id):
|
||||
write_record(claimed.with_suffix('.result'), result)
|
||||
|
||||
|
||||
def _wait_for_owned_writes(runtime, control):
|
||||
def _wait_for_owned_writes(runtime, control) -> Exception | None:
|
||||
"""Process exit would close kill-on-close Jobs, so it is also a write boundary."""
|
||||
if runtime.read_only:
|
||||
return
|
||||
@@ -103,15 +111,21 @@ def _wait_for_owned_writes(runtime, control):
|
||||
return False
|
||||
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():
|
||||
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='resource_recheck')
|
||||
try:
|
||||
if not 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='resource_recheck')
|
||||
except Exception as error:
|
||||
# Desktop references may remain after writers exit; publish that failure.
|
||||
if not exited():
|
||||
raise
|
||||
return error
|
||||
|
||||
|
||||
def run(request_path):
|
||||
@@ -154,7 +168,7 @@ def run(request_path):
|
||||
'generation': max(1, runtime.generation), 'sequence': sequence,
|
||||
'type': kind, 'payload': payload}
|
||||
if persist:
|
||||
write_record(directory / 'result.json', envelope)
|
||||
_persist_result(directory, envelope)
|
||||
try:
|
||||
output.write(json.dumps(envelope, ensure_ascii=True, allow_nan=False) + '\n')
|
||||
output.flush()
|
||||
@@ -175,9 +189,13 @@ def run(request_path):
|
||||
emit('heartbeat')
|
||||
feedback = getattr(service, '_task_queue_feedback', None)
|
||||
emit('state', encode({'phase': runtime.record['state'], 'queue': feedback,
|
||||
'release_state': runtime.record.get('release_state'),
|
||||
'batch': service.batch_feedback(),
|
||||
'active_project': runtime.record.get('active_project'),
|
||||
'business_progress': runtime.business_progress(),
|
||||
'stopping_reason': runtime.record.get('stopping_reason') or getattr(runtime.stop_event, 'stopping_reason', ''),
|
||||
'wait_reason': runtime.record.get('wait_reason') or getattr(runtime.stop_event, 'wait_reason', ''),
|
||||
'primary_error': runtime.record.get('primary_error') or getattr(runtime.stop_event, 'primary_error', ''),
|
||||
'dialog_supervision': runtime.dialog_state(),
|
||||
'dialog_binding': {'batch_id': batch_id, 'attempt_id': attempt_id,
|
||||
'generation': runtime.generation, 'session_token': getattr(runtime.cad, 'token', None)},
|
||||
@@ -249,7 +267,15 @@ def run(request_path):
|
||||
context.report_exception('batch_supervisor', error)
|
||||
response.update(status='error', error=encode_error(error))
|
||||
finally:
|
||||
_wait_for_owned_writes(runtime, stop)
|
||||
cleanup_error = _wait_for_owned_writes(runtime, stop)
|
||||
if cleanup_error is not None:
|
||||
context.report_exception('batch_supervisor_resource_recheck', cleanup_error)
|
||||
response['status'] = 'error'
|
||||
response.setdefault('error', encode_error(cleanup_error))
|
||||
if runtime.record.get('state') == 'isolated':
|
||||
response['resource_warning'] = {'state': 'isolated', 'blocking': False,
|
||||
'desktop': runtime.record['desktop'], 'desktop_released': False,
|
||||
'owned_writers_exited': True}
|
||||
evidence.try_append('worker_closing', status=response.get('status'), business_succeeded=response.get('business_succeeded'))
|
||||
finished.set()
|
||||
thread.join(3)
|
||||
|
||||
@@ -40,8 +40,9 @@ def retained_bom_rows(pending, existing_rows):
|
||||
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))
|
||||
and (not record.sheet or existing_rows[index].target.sheet_number.casefold() == record.sheet.casefold()))
|
||||
if len(candidates) > 1 and record.uid:
|
||||
candidates = tuple(index for index in candidates if 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} 行')
|
||||
|
||||
@@ -25,7 +25,7 @@ _HEADER_HELP = (
|
||||
'位号,必填。一行可填 R1,R2,R3,支持逗号、分号、空格或顿号分隔。',
|
||||
'原理图名称,可选。位号重复时用于精确匹配。',
|
||||
'图页,可选。位号跨页重复时应填写图页或 UID。',
|
||||
'器件 UID,可选;填写时必须与采集结果一致。',
|
||||
'器件 UID,可选。工程、图页和位号已唯一匹配时忽略;仅用于区分仍有多个候选的位号。',
|
||||
'是否替换:TRUE/FALSE 或 是/否;留空默认替换。未列出的位号保留。',
|
||||
'自定义 Value,可选;留空沿用工具原有 Value 策略。',
|
||||
'同步 NC:TRUE/FALSE 或 是/否;留空默认开启。',
|
||||
@@ -209,8 +209,9 @@ class BomMatcher:
|
||||
for key, target in self.by_identity.get(identity, ())
|
||||
if (not record.project_path or self.identities.project(record.project_path) == key[0])
|
||||
and (not record.schematic or target.schematic_name.casefold() == record.schematic.casefold())
|
||||
and (not record.sheet or target.sheet_number.casefold() == record.sheet.casefold())
|
||||
and (not record.uid or target.uid == record.uid)]
|
||||
and (not record.sheet or target.sheet_number.casefold() == record.sheet.casefold())]
|
||||
if len(candidates) > 1 and record.uid:
|
||||
candidates = [(key, target) for key, target in candidates if target.uid == record.uid]
|
||||
if len(candidates) != 1:
|
||||
raise TaskCenterError('bom_import', f'位号 {refdes} 无法唯一匹配当前采集清单')
|
||||
key, target = candidates[0]
|
||||
|
||||
@@ -9,16 +9,20 @@ import stat
|
||||
import zipfile
|
||||
|
||||
from .path_access import canonical_path, internal_path
|
||||
from .operation_diagnostics import summarize_operations
|
||||
|
||||
MAX_FILE_BYTES = 4 * 1024 * 1024
|
||||
MAX_BUNDLE_BYTES = 32 * 1024 * 1024
|
||||
MAX_FILES = 512
|
||||
_BATCH_NAMES = {'session.json', 'supervisor.json', 'request.json', 'result.json',
|
||||
'business-result.json', 'supervisor.log', 'resource-release.log', 'cancel.json',
|
||||
'process.json', 'lifecycle.jsonl', 'owner-loss.json', 'claim.json', 'force-request.json'}
|
||||
'process.json', 'lifecycle.jsonl', 'owner-loss.json', 'claim.json', 'force-request.json',
|
||||
'operation-events.jsonl'}
|
||||
_QUICK_NAMES = {'private-desktop.json', 'checkpoint.json', 'status.json',
|
||||
'uncertain.flag', 'resolved-uncertain.flag', 'protection.json', 'cleanup.json',
|
||||
'project-session.json', 'project-checkpoint.json', 'project-read-release.json', 'status.tsv'}
|
||||
'project-session.json', 'project-checkpoint.json', 'project-read-release.json', 'status.tsv',
|
||||
'worker-progress.json', 'quick-part-replace.log', 'native-inventory.json', 'operation-events.jsonl',
|
||||
'recovery-commit.json', 'retry-preparation.json'}
|
||||
_SECRET_KEY = re.compile(r'(?:password|passwd|(?:client[_-]?)?secret|credentials?|authorization|api[_-]?key|access[_-]?token|refresh[_-]?token|token)', re.I)
|
||||
_USER_KEY = re.compile(r'(?:user(?:[_-]?name)?|login[_-]?name)', re.I)
|
||||
_SECRET_TEXT = re.compile(r'''(?ix)(\b(?:password|passwd|(?:client[_-]?)?secret|credentials?|authorization|api[_-]?key|access[_-]?token|refresh[_-]?token|token)\b["']?\s*[=:]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;}]+)''')
|
||||
@@ -52,6 +56,15 @@ def _scrub_json(value):
|
||||
|
||||
|
||||
def _allowed(parts):
|
||||
if parts[0] == 'execution-proof' or (len(parts) > 3 and parts[0] == 'tasks' and parts[2] == 'execution-proof'):
|
||||
return (parts[-1] == 'completion.json'
|
||||
or bool(re.fullmatch(r'project-(?:commit|pause)-[a-f0-9]{32}\.tsv', parts[-1]))
|
||||
or bool(re.fullmatch(r'(?:post-state|value-readback)-[A-Za-z0-9_.-]+\.(?:tsv|json)', parts[-1])))
|
||||
if (len(parts) >= 5 and parts[:1] == ('tasks',) and parts[2] == 'netlist-checks'):
|
||||
return parts[-1] in {'verification.json', 'netlist.json', 'capture.json', 'export-cache.json'}
|
||||
if (any(re.fullmatch(r'native-inventory-[A-Za-z0-9-]+', part) for part in parts)
|
||||
and len(parts) >= 3 and parts[-2] == 'output'):
|
||||
return parts[-1] in {'scope.txt', 'effective.txt'} or bool(re.fullmatch(r'icdb2ascii-(?:scope|effective)\.(?:stdout|stderr)\.txt', parts[-1], re.I))
|
||||
if re.fullmatch(r'cad-dialogs-[a-f0-9]{32}\.json', parts[-1]):
|
||||
return ((len(parts) == 4 and parts[0] == 'batch-resources' and re.fullmatch(r'generation-\d+', parts[2])) or
|
||||
any(value in parts for value in ('quick-run', 'quickrun', 'quick-run-history')))
|
||||
@@ -71,7 +84,10 @@ def _allowed(parts):
|
||||
if len(parts) >= 2 and parts[0] in {'queue', 'queues', 'task-queues', 'workspace-queues'}:
|
||||
return parts[-1].endswith('.json')
|
||||
if len(parts) >= 2 and any(value in parts for value in ('quick-run', 'quickrun', 'quick-run-history')):
|
||||
return parts[-1] in _QUICK_NAMES or bool(re.fullmatch(r'retained-worker-[a-f0-9]{32}\.json', parts[-1]))
|
||||
return (parts[-1] in _QUICK_NAMES
|
||||
or bool(re.fullmatch(r'retained-worker-[a-f0-9]{32}\.json', parts[-1]))
|
||||
or bool(re.fullmatch(r'project-(?:commit|pause)-[a-f0-9]{32}\.tsv', parts[-1]))
|
||||
or bool(re.fullmatch(r'(?:post-state|value-readback)-[A-Za-z0-9_.-]+\.(?:tsv|json)', parts[-1])))
|
||||
return False
|
||||
|
||||
|
||||
@@ -84,11 +100,13 @@ def export_diagnostic_bundle(data_root, destination: Path) -> Path:
|
||||
root, destination = canonical_path(data_root), canonical_path(destination)
|
||||
if destination.suffix.lower() != '.zip':
|
||||
raise ValueError('diagnostic destination must have a .zip suffix')
|
||||
manifest = {'version': 1, 'included': [], 'omissions': [], 'unknowns': [
|
||||
'External desktop handle holders are unknown; empty window/thread lists do not prove release.',
|
||||
manifest = {'version': 2, 'included': [], 'omissions': [], 'truncated': [], 'unknowns': [
|
||||
'Active logs and metadata are point-in-time reads; no source CAD, libraries, BOM, database or environment configuration is included.'],
|
||||
'limits': {'max_file_bytes': MAX_FILE_BYTES, 'max_bundle_bytes': MAX_BUNDLE_BYTES, 'max_files': MAX_FILES}}
|
||||
total = 0
|
||||
candidates = []
|
||||
operations = {}
|
||||
items = {}
|
||||
physical = internal_path(root)
|
||||
# os.walk does not descend symlinks; explicitly prune Windows junctions too.
|
||||
with zipfile.ZipFile(internal_path(destination), 'x', compression=zipfile.ZIP_DEFLATED) as archive:
|
||||
@@ -101,7 +119,7 @@ def export_diagnostic_bundle(data_root, destination: Path) -> Path:
|
||||
info = entry.lstat()
|
||||
if stat.S_ISLNK(info.st_mode) or getattr(info, 'st_file_attributes', 0) & 0x400:
|
||||
manifest['omissions'].append({'path': _scrub_text(relative), 'reason': 'link_or_reparse_point'})
|
||||
elif base == physical and name not in {'logs', 'batch-resources', 'attempts', 'tasks', 'queue', 'queues', 'task-queues', 'workspace-queues', 'quick-run', 'quick-run-history'}:
|
||||
elif base == physical and name not in {'logs', 'batch-resources', 'attempts', 'tasks', 'queue', 'queues', 'task-queues', 'workspace-queues', 'quick-run', 'quick-run-history', 'execution-proof'}:
|
||||
manifest['omissions'].append({'path': _scrub_text(relative), 'reason': 'outside_allowlist'})
|
||||
else:
|
||||
safe_folders.append(name)
|
||||
@@ -119,28 +137,94 @@ def export_diagnostic_bundle(data_root, destination: Path) -> Path:
|
||||
reason = 'link_or_reparse_point'
|
||||
elif not stat.S_ISREG(info.st_mode):
|
||||
reason = 'not_regular_file'
|
||||
elif info.st_size > MAX_FILE_BYTES or total + info.st_size > MAX_BUNDLE_BYTES or len(manifest['included']) >= MAX_FILES:
|
||||
reason = 'size_or_count_limit'
|
||||
else:
|
||||
with path.open('rb') as source:
|
||||
payload = source.read(MAX_FILE_BYTES + 1)
|
||||
if len(payload) > MAX_FILE_BYTES or b'\x00' in payload:
|
||||
reason = 'binary_or_size_limit'
|
||||
else:
|
||||
text = payload.decode('utf-8-sig')
|
||||
if relative.suffix == '.json':
|
||||
text = json.dumps(_scrub_json(json.loads(text)), ensure_ascii=False, indent=2)
|
||||
elif '.jsonl' in relative.name:
|
||||
text = '\n'.join(json.dumps(_scrub_json(json.loads(line)), ensure_ascii=False)
|
||||
for line in text.splitlines() if line.strip()) + '\n'
|
||||
else:
|
||||
text = _scrub_text(text)
|
||||
archive.writestr(label, text)
|
||||
total += len(payload)
|
||||
manifest['included'].append(label)
|
||||
candidates.append((info.st_mtime_ns, path, relative, label, info.st_size))
|
||||
except (OSError, UnicodeError, ValueError):
|
||||
reason = 'unreadable_or_invalid_text'
|
||||
if reason:
|
||||
manifest['omissions'].append({'path': label, 'reason': reason})
|
||||
# Current failures must survive a busy workspace's file/count budget.
|
||||
for _, path, relative, label, size in sorted(candidates, key=lambda row: (-row[0], row[3])):
|
||||
reason = None
|
||||
budget = min(MAX_FILE_BYTES, MAX_BUNDLE_BYTES - total)
|
||||
try:
|
||||
tail = bool(re.search(r'\.(?:log|jsonl)(?:\.\d+)?$', relative.name))
|
||||
truncated = size > budget
|
||||
if len(manifest['included']) >= MAX_FILES or budget <= 0 or (truncated and (not tail or budget < 64)):
|
||||
reason = 'size_or_count_limit'
|
||||
else:
|
||||
info = path.lstat()
|
||||
if stat.S_ISLNK(info.st_mode) or getattr(info, 'st_file_attributes', 0) & 0x400 or info.st_nlink != 1:
|
||||
manifest['omissions'].append({'path': label, 'reason': 'link_or_reparse_point'})
|
||||
continue
|
||||
with path.open('rb') as source:
|
||||
if truncated:
|
||||
source.seek(max(0, size - budget))
|
||||
source.readline(budget + 1) # Discard clipped credentials and UTF-8 lines.
|
||||
payload = source.read(budget + 1)
|
||||
if len(payload) > budget or b'\x00' in payload:
|
||||
reason = 'binary_or_size_limit'
|
||||
elif not payload and size:
|
||||
reason = 'no_complete_tail_line'
|
||||
else:
|
||||
try:
|
||||
content = payload.decode('utf-8-sig')
|
||||
except UnicodeDecodeError:
|
||||
if relative.name not in {'scope.txt', 'effective.txt'}:
|
||||
raise
|
||||
content = payload.decode('mbcs' if os.name == 'nt' else 'cp1252')
|
||||
if relative.suffix == '.json':
|
||||
content = json.dumps(_scrub_json(json.loads(content)), ensure_ascii=False, indent=2)
|
||||
elif '.jsonl' in relative.name:
|
||||
records, invalid = [], 0
|
||||
for line in content.splitlines():
|
||||
if not line.strip():
|
||||
continue
|
||||
try:
|
||||
records.append(_scrub_json(json.loads(line)))
|
||||
except ValueError:
|
||||
invalid += 1
|
||||
content = '\n'.join(json.dumps(record, ensure_ascii=False) for record in records) + '\n'
|
||||
if invalid:
|
||||
manifest['omissions'].append({'path': label, 'reason': 'invalid_jsonl_lines', 'lines': invalid})
|
||||
else:
|
||||
content = _scrub_text(content)
|
||||
encoded = content.encode('utf-8')
|
||||
if tail and budget >= 64 and len(encoded) > budget:
|
||||
# Redaction may grow a short secret. Trim complete oldest lines again.
|
||||
offset, remaining = 0, len(encoded)
|
||||
for line in encoded.splitlines(keepends=True):
|
||||
if remaining <= budget:
|
||||
break
|
||||
offset += len(line)
|
||||
remaining -= len(line)
|
||||
encoded = encoded[offset:]
|
||||
content = encoded.decode('utf-8')
|
||||
truncated = True
|
||||
if '.jsonl' in relative.name:
|
||||
records = [json.loads(line) for line in content.splitlines() if line.strip()]
|
||||
if len(encoded) > budget:
|
||||
reason = 'size_or_count_limit'
|
||||
else:
|
||||
archive.writestr(label, encoded)
|
||||
total += len(encoded)
|
||||
manifest['included'].append(label)
|
||||
if truncated:
|
||||
manifest['truncated'].append({'path': label, 'mode': 'tail', 'source_bytes': size})
|
||||
if relative.name == 'operation-events.jsonl':
|
||||
operations[_scrub_text(relative.parent.as_posix())] = summarize_operations(records)
|
||||
elif relative.name == 'status.tsv':
|
||||
rows = [line.split('\t') for line in content.splitlines() if line.strip()]
|
||||
rows = [row for row in rows if len(row) >= 4 and row[0] != 'job_id']
|
||||
if rows:
|
||||
saved = [row[0] for row in rows if row[1] in {'saved_ok', 'restored_ok'}]
|
||||
items[_scrub_text(relative.parent.as_posix())] = {
|
||||
'last_successful_item': saved[-1] if saved else None,
|
||||
'latest_item': {'job_id': rows[-1][0], 'state': rows[-1][1]}}
|
||||
except (OSError, UnicodeError, ValueError):
|
||||
reason = 'unreadable_or_invalid_text'
|
||||
if reason:
|
||||
manifest['omissions'].append({'path': label, 'reason': reason})
|
||||
archive.writestr('closure-summary.json', json.dumps({'operations': operations, 'items': items}, ensure_ascii=False, indent=2))
|
||||
archive.writestr('manifest.json', json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
return destination
|
||||
@@ -14,25 +14,43 @@ class ExecutionFeedback:
|
||||
stage: str = ''
|
||||
stage_seconds: float = 0.0
|
||||
waiting_for_safe_completion: bool = False
|
||||
stopping_reason: str = ''
|
||||
wait_reason: str = ''
|
||||
primary_error: str = ''
|
||||
|
||||
|
||||
def wait_reason_for_stage(stage):
|
||||
return {'save_and_close': 'save', 'verify_saved_project': 'readback',
|
||||
'native_snapshot_read': 'readback', 'capture_semantic_state': 'readback',
|
||||
'private_shutdown': 'desktop_release',
|
||||
'awaiting_reconciliation': 'reconciliation', 'mentor_exit': 'mentor_exit',
|
||||
'desktop_release': 'desktop_release'}.get(stage,
|
||||
'native_call' if stage in {'native_replace', 'restore_attributes',
|
||||
'restore_attribute_fields', 'verify_restoration', 'verify_attribute_fields'} else '')
|
||||
|
||||
|
||||
def read_feedback(task_id, position, total, message, root: Path, started_after: float):
|
||||
private_state = ''
|
||||
private_seconds = 0.0
|
||||
private = root / 'quick-run' / 'private-desktop.json'
|
||||
try:
|
||||
modified = private.stat().st_mtime
|
||||
if modified >= started_after:
|
||||
state = json.loads(private.read_text(encoding='utf-8')).get('state')
|
||||
if state in {'starting', 'closing'}:
|
||||
return ExecutionFeedback(task_id, position, total, message,
|
||||
'private_startup' if state == 'starting' else 'private_shutdown', max(0, time.time() - modified))
|
||||
private_state = 'private_startup' if state == 'starting' else 'private_shutdown'
|
||||
private_seconds = max(0, time.time() - modified)
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
pass
|
||||
path = root / 'quick-run' / 'worker-progress.json'
|
||||
stage, seconds, waiting = '', 0.0, False
|
||||
record = {}
|
||||
try:
|
||||
modified = path.stat().st_mtime
|
||||
if modified >= started_after:
|
||||
record = json.loads(path.read_text(encoding='utf-8'))
|
||||
if not isinstance(record, dict):
|
||||
record = {}
|
||||
waiting = record.get('waiting_for_safe_completion') is True
|
||||
candidate = record.get('stage', '')
|
||||
if candidate and candidate != 'finished':
|
||||
@@ -40,4 +58,14 @@ def read_feedback(task_id, position, total, message, root: Path, started_after:
|
||||
stage = candidate
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
pass # Display feedback is optional; it never changes execution state.
|
||||
return ExecutionFeedback(task_id, position, total, message, stage, seconds, waiting)
|
||||
if private_state:
|
||||
stage, seconds = private_state, private_seconds
|
||||
stopping_reason = record.get('stopping_reason', '')
|
||||
if not stopping_reason and record.get('stop_requested'):
|
||||
stopping_reason = 'inactivity'
|
||||
wait_reason = record.get('wait_reason') or wait_reason_for_stage(stage)
|
||||
if private_state and wait_reason not in {'mentor_exit', 'desktop_release'}:
|
||||
wait_reason = wait_reason_for_stage(stage)
|
||||
return ExecutionFeedback(task_id, position, total, message, stage, seconds, waiting,
|
||||
stopping_reason, wait_reason,
|
||||
record.get('primary_error') or record.get('resolution_error') or '')
|
||||
@@ -33,6 +33,11 @@ def create_execution_schema(connection):
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS execution_target_claims (
|
||||
task_id TEXT NOT NULL, round_id TEXT NOT NULL, target_key TEXT NOT NULL,
|
||||
operation_key TEXT NOT NULL, PRIMARY KEY(task_id,round_id,target_key))''')
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS execution_project_commits (
|
||||
task_id TEXT NOT NULL, round_id TEXT NOT NULL, session_token TEXT NOT NULL,
|
||||
project_path TEXT NOT NULL, evidence_root TEXT NOT NULL, state TEXT NOT NULL,
|
||||
jobs_json TEXT NOT NULL, proof_json TEXT,
|
||||
PRIMARY KEY(task_id,round_id,session_token))''')
|
||||
|
||||
|
||||
def _json(value):
|
||||
@@ -115,7 +120,7 @@ class ExecutionJournal:
|
||||
current=self._round(task_id)
|
||||
if current:
|
||||
unsafe=self.store._connection.execute('''SELECT 1 FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND state IN ('prepared','uncertain') LIMIT 1''',
|
||||
WHERE task_id=? AND round_id=? AND state IN ('prepared','uncertain','pending_save') LIMIT 1''',
|
||||
(task_id,current['round_id'])).fetchone()
|
||||
if unsafe:raise TaskCenterError('quick_run_uncertain','原执行项尚待核验,不能准备重试。')
|
||||
self.store._connection.execute('DELETE FROM execution_retry_selections WHERE task_id=?',(task_id,))
|
||||
@@ -154,7 +159,7 @@ class ExecutionJournal:
|
||||
(task_id, current['round_id']))}
|
||||
for key in json.loads(current['plan_json']):
|
||||
record = records.get(key)
|
||||
if record is None or record['state'] in {'prepared', 'uncertain'}:return False
|
||||
if record is None or record['state'] in {'prepared', 'uncertain', 'pending_save'}:return False
|
||||
if record['state'] == 'pending':
|
||||
command = json.loads(record['command_json'])
|
||||
return bool(self.can_continue_component(task_id, command))
|
||||
@@ -430,7 +435,7 @@ class ExecutionJournal:
|
||||
with self.store._lock:
|
||||
current=self._round(task_id)
|
||||
return bool(current and self.store._connection.execute('''SELECT 1 FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND state='prepared' LIMIT 1''',
|
||||
WHERE task_id=? AND round_id=? AND state IN ('prepared','pending_save') LIMIT 1''',
|
||||
(task_id,current['round_id'])).fetchone())
|
||||
|
||||
def unresolved_jobs(self,task_id,rows):
|
||||
@@ -438,7 +443,7 @@ class ExecutionJournal:
|
||||
current=self._round(task_id)
|
||||
if current is None:return ()
|
||||
keys={record[0] for record in self.store._connection.execute('''SELECT operation_key
|
||||
FROM execution_operations WHERE task_id=? AND round_id=? AND state IN ('prepared','uncertain')''',
|
||||
FROM execution_operations WHERE task_id=? AND round_id=? AND state IN ('prepared','uncertain','pending_save')''',
|
||||
(task_id,current['round_id']))}
|
||||
return tuple(row['job_id'] for row in rows if _hash(command_identity(row)) in keys)
|
||||
|
||||
@@ -506,6 +511,8 @@ class ExecutionJournal:
|
||||
elif record['state']=='failed':
|
||||
restored[row['job_id']]=tuple(json.loads(record['receipt_json'])[name] for name in ('native_state','code','message'))
|
||||
continue
|
||||
elif record['state']=='pending_save':
|
||||
raise TaskCenterError('quick_run_uncertain','工程替换尚待统一保存回读,禁止重放;请先核验工程提交记录。')
|
||||
outcome=latest.get(row['job_id'])
|
||||
if outcome and outcome[0] in _TERMINAL:
|
||||
record=connection.execute('''SELECT * FROM execution_operations
|
||||
@@ -546,6 +553,136 @@ class ExecutionJournal:
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''',(identifier,generation,task_id,current['round_id'],key))
|
||||
return JournalAttempt(task_id,current['round_id'],key,identifier,generation,row['job_id'])
|
||||
|
||||
def stage_project_result(self, attempt, row, *, session_token, root, proof):
|
||||
"""Retain an applied operation without granting a saved receipt or retry."""
|
||||
from .execution_proof import proof_intact
|
||||
if not session_token or not proof_intact(proof):
|
||||
raise TaskCenterError('quick_run_uncertain', '工程暂存证据不完整。')
|
||||
with self.store.transaction():
|
||||
connection = self.store._connection
|
||||
record = 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 (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', '工程暂存结果不属于当前执行声明。')
|
||||
project = command_identity(row)['project_path']
|
||||
commit = connection.execute('''SELECT * FROM execution_project_commits
|
||||
WHERE task_id=? AND round_id=? AND session_token=?''',
|
||||
(attempt.task_id, attempt.round_id, session_token)).fetchone()
|
||||
if commit and (commit['state'] != 'pending_save' or commit['project_path'] != project
|
||||
or commit['evidence_root'] != str(canonical_path(root))):
|
||||
raise TaskCenterError('quick_run_uncertain', '工程提交身份发生变化。')
|
||||
jobs = json.loads(commit['jobs_json']) if commit else []
|
||||
if row['job_id'] in jobs:
|
||||
raise TaskCenterError('quick_run_uncertain', '工程暂存操作重复。')
|
||||
jobs.append(row['job_id'])
|
||||
connection.execute('''INSERT INTO execution_project_commits VALUES (?,?,?,?,?, 'pending_save',?,NULL)
|
||||
ON CONFLICT(task_id,round_id,session_token) DO UPDATE SET jobs_json=excluded.jobs_json''',
|
||||
(attempt.task_id, attempt.round_id, session_token, project, str(canonical_path(root)), _json(jobs)))
|
||||
receipt = dict(native_state='pending_save', code='session_staged', message='替换已暂存,等待工程统一保存回读。',
|
||||
job_id=row['job_id'], session_token=session_token, row=row, proof=proof,
|
||||
operation_attempt=[attempt.operation_key, attempt.attempt_id, attempt.generation])
|
||||
connection.execute('''UPDATE execution_operations SET state='pending_save',receipt_json=?
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''',
|
||||
(_json(receipt), attempt.task_id, attempt.round_id, attempt.operation_key))
|
||||
|
||||
def pending_project_commits(self, task_id):
|
||||
with self.store._lock:
|
||||
current = self._round(task_id)
|
||||
if not current:return ()
|
||||
return tuple(dict(row) for row in self.store._connection.execute('''SELECT * FROM execution_project_commits
|
||||
WHERE task_id=? AND round_id=? AND state='pending_save' ''', (task_id, current['round_id'])))
|
||||
|
||||
def project_commit_records(self, task_id):
|
||||
with self.store._lock:
|
||||
current = self._round(task_id)
|
||||
return tuple(dict(row) for row in self.store._connection.execute('''SELECT * FROM execution_project_commits
|
||||
WHERE task_id=? AND round_id=?''', (task_id, current['round_id']))) if current else ()
|
||||
|
||||
def project_commit_attempts(self, task_id, session_token):
|
||||
with self.store._lock:
|
||||
current = self._round(task_id)
|
||||
if not current:return {}
|
||||
result = {}
|
||||
for row in self.store._connection.execute('''SELECT * FROM execution_operations
|
||||
WHERE task_id=? AND round_id=?''', (task_id, current['round_id'])):
|
||||
receipt = json.loads(row['receipt_json'] or '{}')
|
||||
token = receipt.get('session_token') or receipt.get('proof', {}).get('project_commit', {}).get('session_token')
|
||||
if token == session_token:
|
||||
actual = [row['operation_key'], row['attempt_id'], row['generation']]
|
||||
original = receipt.get('operation_attempt') or receipt.get('proof', {}).get('project_commit', {}).get('operation_attempts', {}).get(receipt['job_id'])
|
||||
if original is not None and original != actual:
|
||||
raise TaskCenterError('quick_run_uncertain', '原工程暂存尝试与当前执行记录不同。')
|
||||
result[receipt['job_id']] = actual
|
||||
return result
|
||||
|
||||
def project_commit_recovery_attempts(self, task_id):
|
||||
"""Include actual attempts outside the frozen command rows as well."""
|
||||
with self.store._lock:
|
||||
current = self._round(task_id)
|
||||
if not current:return ()
|
||||
return tuple([row['operation_key'], row['attempt_id'], row['generation']]
|
||||
for row in self.store._connection.execute('''SELECT operation_key,attempt_id,generation
|
||||
FROM execution_operations WHERE task_id=? AND round_id=?
|
||||
AND (attempt_id IS NOT NULL OR generation>0)''', (task_id, current['round_id'])))
|
||||
|
||||
def bind_project_commit_proof(self, task_id, session_token, proof):
|
||||
with self.store.transaction():
|
||||
current = self._round(task_id)
|
||||
self.store._connection.execute('''UPDATE execution_project_commits SET proof_json=?
|
||||
WHERE task_id=? AND round_id=? AND session_token=? AND state='pending_save' AND proof_json IS NULL''',
|
||||
(_json(proof), task_id, current['round_id'], session_token))
|
||||
|
||||
def staged_project_rows(self, task_id, session_token):
|
||||
with self.store._lock:
|
||||
current = self._round(task_id)
|
||||
if not current:return ()
|
||||
records = self.store._connection.execute('''SELECT receipt_json FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND state='pending_save' ''', (task_id, current['round_id']))
|
||||
return tuple(receipt for record in records
|
||||
if (receipt := json.loads(record[0])).get('session_token') == session_token)
|
||||
|
||||
def commit_project_results(self, task_id, session_token, proofs, commit_proof):
|
||||
"""Commit a whole staged prefix and its history in one SQL transaction."""
|
||||
from .execution_proof import proof_intact
|
||||
with self.store.transaction():
|
||||
connection = self.store._connection
|
||||
current = self._round(task_id)
|
||||
commit = connection.execute('''SELECT * FROM execution_project_commits
|
||||
WHERE task_id=? AND round_id=? AND session_token=?''', (task_id, current['round_id'], session_token)).fetchone() if current else None
|
||||
if commit is None:
|
||||
raise TaskCenterError('quick_run_uncertain', '缺少原工程暂存提交记录。')
|
||||
if commit['state'] == 'verified':return
|
||||
jobs = json.loads(commit['jobs_json'])
|
||||
if (commit_proof.get('session_token') != session_token
|
||||
or str(canonical_path(commit_proof.get('project_path', ''))).casefold() != commit['project_path']
|
||||
or commit_proof.get('jobs') != jobs or set(proofs) != set(jobs)
|
||||
or not commit_proof.get('files') or not proof_intact(commit_proof)
|
||||
or any(not proof.get('files') or not proof_intact(proof) for proof in proofs.values())):
|
||||
raise TaskCenterError('quick_run_uncertain', '工程保存回读证明未覆盖全部暂存项。')
|
||||
records = connection.execute('''SELECT * FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND state='pending_save' ''', (task_id, current['round_id'])).fetchall()
|
||||
records = [record for record in records if json.loads(record['receipt_json']).get('session_token') == session_token]
|
||||
if {json.loads(record['receipt_json'])['job_id'] for record in records} != set(jobs):
|
||||
raise TaskCenterError('quick_run_uncertain', '工程暂存前缀与提交证明不一致。')
|
||||
for record in records:
|
||||
receipt = json.loads(record['receipt_json'])
|
||||
job = receipt['job_id']
|
||||
proof = dict(proofs[job])
|
||||
if proof.get('native_attempt') != receipt.get('proof', {}).get('native_attempt'):
|
||||
raise TaskCenterError('quick_run_uncertain', '保存回读与原暂存原生尝试不一致。')
|
||||
proof['project_commit'] = commit_proof
|
||||
proof['files'] = list(proof['files']) + list(commit_proof['files'])
|
||||
attempt = JournalAttempt(task_id, current['round_id'], record['operation_key'],
|
||||
record['attempt_id'], record['generation'], job)
|
||||
connection.execute('''UPDATE execution_operations SET state='prepared'
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''', (task_id, current['round_id'], record['operation_key']))
|
||||
native_state = commit_proof.get('outcomes', {}).get(job, 'saved_ok')
|
||||
self.finish(attempt, native_state, 'project_committed', '工程统一保存、关闭重开及回读校验通过。', proof=proof)
|
||||
connection.execute('''UPDATE execution_project_commits SET state='verified',proof_json=?
|
||||
WHERE task_id=? AND round_id=? AND session_token=?''', (_json(commit_proof), task_id, current['round_id'], session_token))
|
||||
|
||||
def finish(self,attempt,native_state,code,message,*,progress=None,proof=None):
|
||||
if native_state not in _TERMINAL:raise TaskCenterError('quick_run_uncertain','不能提交未知的执行结果。')
|
||||
state=({'saved_ok':'verified','no_match':'no_match','restored_ok':'restored',
|
||||
@@ -682,7 +819,7 @@ class ExecutionJournal:
|
||||
from .execution_proof import proof_intact
|
||||
if not proof_intact(receipt.get('proof',{})):return True
|
||||
if not outcome or tuple(outcome[:2])!=(receipt['native_state'],receipt['code']):return True
|
||||
elif record['state']=='uncertain':return True
|
||||
elif record['state'] in {'uncertain','pending_save'}:return True
|
||||
elif record['state']=='prepared' and (not outcome or outcome[0] not in _TERMINAL):return True
|
||||
return False
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ def capture_result(data_root,root,row,outcome,*,strict=False,persist=True):
|
||||
checked_manifest = manifest.read_bytes()
|
||||
paths.append(manifest)
|
||||
proof['inventory_empty'] = True
|
||||
if strict and state in {'saved_ok','no_match'} and code not in {'batch_closed','session_verified'}:
|
||||
if strict and state in {'saved_ok','no_match'} and code not in {'batch_closed','session_verified','project_committed'}:
|
||||
raise ValueError('save/close was not verified')
|
||||
checked={}
|
||||
if row.get('execution_unit') == 'inventory_empty':
|
||||
@@ -55,7 +55,7 @@ def capture_result(data_root,root,row,outcome,*,strict=False,persist=True):
|
||||
paths.append(baseline)
|
||||
elif strict and state in {'saved_ok','no_match','restored_ok','recovery_readback'}:
|
||||
raise ValueError('missing verified semantic state')
|
||||
if state=='saved_ok' or (state=='restored_ok' and code in {'recovery_verified','recovery_saved_verified'}):
|
||||
if state=='saved_ok' or (state=='pending_save' and code == 'session_staged') or (state=='restored_ok' and code in {'recovery_verified','recovery_saved_verified'}):
|
||||
snapshot=internal_path(root/f'snapshot-{row["job_id"]}.tsv')
|
||||
report_path=Path(str(snapshot)+'.native.json')
|
||||
if strict or snapshot.is_file() or report_path.is_file():
|
||||
@@ -101,6 +101,59 @@ def capture_result(data_root,root,row,outcome,*,strict=False,persist=True):
|
||||
raise TaskCenterError('quick_run_uncertain','原生回执、尝试身份或工程语义基线无法核验,已停止以避免重复替换。') from error
|
||||
|
||||
|
||||
def capture_project_commit(data_root, root, commit):
|
||||
"""Bind a durable project marker to the exact staged prefix before SQL commit."""
|
||||
from .quick_run import _decode_vbs_field
|
||||
try:
|
||||
path = internal_path(Path(root) / f'project-commit-{commit["session_token"]}.tsv')
|
||||
data = path.read_bytes()
|
||||
lines = data.decode('utf-8-sig').splitlines()
|
||||
token, project, state = lines[0].split('\t')
|
||||
outcomes = [line.split('\t') for line in lines[1:] if line]
|
||||
jobs = json.loads(commit['jobs_json'])
|
||||
if (token != commit['session_token'] or state != 'project_verified'
|
||||
or str(canonical_path(_decode_vbs_field(project))).casefold() != commit['project_path']
|
||||
or [outcome[0] for outcome in outcomes] != jobs
|
||||
or any(len(outcome) != 2 or outcome[1] not in {'saved_ok', 'no_match'} for outcome in outcomes)):
|
||||
raise ValueError('project commit does not cover staged prefix')
|
||||
destination = internal_path(data_root / 'execution-proof' / uuid4().hex)
|
||||
destination.mkdir(parents=True, exist_ok=False)
|
||||
target = destination / path.name
|
||||
with target.open('xb') as stream:
|
||||
stream.write(data); stream.flush(); os.fsync(stream.fileno())
|
||||
if path.read_bytes() != data:
|
||||
raise ValueError('project marker changed during binding')
|
||||
return dict(session_token=token, project_path=commit['project_path'], jobs=jobs,
|
||||
outcomes=dict(outcomes), files=[dict(path=str(canonical_path(target)), sha256=hashlib.sha256(data).hexdigest())])
|
||||
except (OSError, UnicodeError, ValueError, KeyError, TypeError, IndexError) as error:
|
||||
raise TaskCenterError('quick_run_uncertain', '工程统一保存或回读尚未得到完整证明,保留全部暂存项待核验。') from error
|
||||
|
||||
|
||||
def bind_project_commit_source(proof, data_root, root, project):
|
||||
"""Capture saved bytes only at the completed native-close callback."""
|
||||
from .project_session_health import _source_parameters, _source_digest
|
||||
from .project_isolation import write_sources
|
||||
value = dict(proof, **_source_parameters(Path(project), data_root))
|
||||
value['source_sha256'] = _source_digest(value)
|
||||
value['command_sha256'] = hashlib.sha256(internal_path(root / 'command.tsv').read_bytes()).hexdigest()
|
||||
value['saved_sources'] = {source: hashlib.sha256(internal_path(source).read_bytes()).hexdigest()
|
||||
for source in write_sources(project)}
|
||||
if not value['source_sha256']:
|
||||
raise TaskCenterError('quick_run_uncertain', '已保存工程源文件无法稳定绑定,保留待核验。')
|
||||
return value
|
||||
|
||||
|
||||
def validate_project_commit_source(proof, root):
|
||||
from .project_session_health import _source_digest
|
||||
try:
|
||||
return (proof.get('source_sha256') and _source_digest(proof) == proof['source_sha256']
|
||||
and proof.get('command_sha256') == hashlib.sha256(internal_path(root / 'command.tsv').read_bytes()).hexdigest()
|
||||
and bool(proof.get('saved_sources')) and all(
|
||||
hashlib.sha256(internal_path(source).read_bytes()).hexdigest() == digest
|
||||
for source, digest in proof['saved_sources'].items()) and proof_intact(proof))
|
||||
except (OSError, KeyError, TypeError, ValueError):return False
|
||||
|
||||
|
||||
def capture_recovery(data_root,audit,row,outcome,*,strict=False):
|
||||
"""The recovery audit proves readback; it never asserts a second replacement."""
|
||||
worker=audit/'worker'
|
||||
|
||||
@@ -689,6 +689,7 @@ class PrivateDesktop:
|
||||
close_pending()
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
self.cleanup_record['owned_cleanup_complete'] = not errors and not self._processes
|
||||
try:
|
||||
self.release_desktop()
|
||||
except Exception as error:
|
||||
|
||||
@@ -15,6 +15,7 @@ class TaskStatus(str, Enum):
|
||||
PAUSED = "paused"
|
||||
COMPLETED = "completed"
|
||||
FAILED = "failed"
|
||||
BLOCKED = "blocked"
|
||||
DELETED = "deleted"
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
"""Native current-sheet replacement adapter for the existing QuickPartReplace runner."""
|
||||
import argparse
|
||||
from collections import Counter
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
from functools import wraps
|
||||
import faulthandler
|
||||
import ctypes
|
||||
import csv
|
||||
@@ -15,6 +18,46 @@ import time
|
||||
import traceback
|
||||
|
||||
|
||||
_SNAPSHOT_REFERENCE_KEYS = ContextVar('snapshot_reference_keys', default={})
|
||||
|
||||
|
||||
@contextmanager
|
||||
def snapshot_identity_scope(snapshot):
|
||||
"""Keep original receipt keys while resolving live COM objects by reference."""
|
||||
rows = [line.split('\t') for line in Path(snapshot).read_text(encoding='utf-8-sig').splitlines()]
|
||||
references, owners, spelling = {}, {}, {}
|
||||
for row in rows:
|
||||
if len(row) >= 3 and row[0] in {'C', 'U'}:
|
||||
uid, ref = decode(row[1]), decode(row[2]).strip().casefold()
|
||||
spelling[ref] = decode(row[2]).strip()
|
||||
transform = tuple(decode(value) for value in row[3:7]) if row[0] == 'C' and len(row) == 8 else None
|
||||
references.setdefault(ref, []).append((uid, transform))
|
||||
owners.setdefault(uid, set()).add(ref)
|
||||
for row in rows:
|
||||
if len(row) == 3 and row[0] == 'G':
|
||||
headers = [line.split('\t') for line in decode(row[2]).splitlines() if line.startswith('C\t')]
|
||||
if len(headers) == 1 and len(headers[0]) == 8:
|
||||
header = [decode(value) for value in headers[0]]
|
||||
ref = header[2].strip().casefold()
|
||||
references[ref] = [(uid, tuple(header[3:7]) if uid == header[1] else transform)
|
||||
for uid, transform in references.get(ref, ())]
|
||||
keys = {ref: [(uid if len(owners[uid]) == 1 else '@REFDES|' + spelling[ref], transform)
|
||||
for uid, transform in values] for ref, values in references.items() if ref}
|
||||
token = _SNAPSHOT_REFERENCE_KEYS.set(keys)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_SNAPSHOT_REFERENCE_KEYS.reset(token)
|
||||
|
||||
|
||||
def _bound_snapshot_identity(action):
|
||||
@wraps(action)
|
||||
def bound(snapshot, *args, **kwargs):
|
||||
with snapshot_identity_scope(snapshot):
|
||||
return action(snapshot, *args, **kwargs)
|
||||
return bound
|
||||
|
||||
|
||||
def snapshot_attempt(snapshot):
|
||||
"""Bind batch evidence to the actual snapshot and its confirmed queue row."""
|
||||
from .batch_attempt import _bound_attempt
|
||||
@@ -392,16 +435,35 @@ def components_on_sheet(app, api):
|
||||
|
||||
|
||||
def _component_uid(component):
|
||||
value = getattr(component, 'UID', None)
|
||||
refdes = str(getattr(component, 'Refdes', '') or '').strip()
|
||||
identities = _SNAPSHOT_REFERENCE_KEYS.get().get(refdes.casefold(), ())
|
||||
if len(identities) == 1:
|
||||
return identities[0][0]
|
||||
if identities:
|
||||
matches = [uid for uid, transform in identities if transform and _same_unit(component, transform)]
|
||||
if len(matches) != 1:
|
||||
raise ValueError('Snapshot physical unit association is missing or ambiguous')
|
||||
return matches[0]
|
||||
try:
|
||||
value = getattr(component, 'UID', None)
|
||||
except Exception:
|
||||
value = None
|
||||
uid = '' if value is None else str(value).strip()
|
||||
if uid:
|
||||
return uid
|
||||
refdes = str(getattr(component, 'Refdes', '') or '').strip()
|
||||
if not refdes:
|
||||
raise ValueError("Component UID and Refdes are empty; cannot safely identify the target")
|
||||
return '@REFDES|' + refdes
|
||||
|
||||
|
||||
def _same_unit(component, transform):
|
||||
point = component.GetLocation()
|
||||
return (abs(float(point.X) - float(transform[0])) <= 10
|
||||
and abs(float(point.Y) - float(transform[1])) <= 10
|
||||
and float(component.Orientation) == float(transform[2])
|
||||
and float(component.Scale) == float(transform[3]))
|
||||
|
||||
|
||||
def check_active_context(app, metadata):
|
||||
from .cad_identity import verify_application, project_file_path
|
||||
verify_application(app)
|
||||
@@ -418,15 +480,20 @@ def check_context(app, api, metadata, records, require_selection=True):
|
||||
by_uid = {_component_uid(component): component for component in components}
|
||||
if len(by_uid) != len(components):
|
||||
raise ValueError("Duplicate component UID on sheet")
|
||||
for record in records:
|
||||
component = by_uid.get(record[1])
|
||||
if component is None or str(component.Refdes).strip().casefold() != record[2].strip().casefold():
|
||||
raise ValueError('Snapshot reference differs from the selected live component')
|
||||
if len(metadata) == 10:
|
||||
selectors = _target_selectors(metadata[9])
|
||||
if set(selectors) != wanted:
|
||||
selected_refs = {ref.strip().casefold() for ref, _ in selectors.values()}
|
||||
if selected_refs != {record[2].strip().casefold() for record in records}:
|
||||
raise ValueError("Target selector differs from snapshot components")
|
||||
for uid, (refdes, old_value) in selectors.items():
|
||||
component = by_uid.get(uid)
|
||||
if (component is None or str(component.Refdes) != refdes or
|
||||
attribute_value(component, "Part Number", required=True).casefold() != metadata[2].casefold() or
|
||||
attribute_value(component, "Value") != old_value):
|
||||
candidates = [component for component in components if str(component.Refdes).strip().casefold() == refdes.strip().casefold()]
|
||||
if (not candidates or any(_component_uid(component) not in wanted
|
||||
or attribute_value(component, "Part Number", required=True).casefold() != metadata[2].casefold()
|
||||
or attribute_value(component, "Value") != old_value for component in candidates)):
|
||||
raise ValueError("Selected target changed since inventory")
|
||||
else:
|
||||
actual = {_component_uid(component) for component in components if attribute_value(component, "Part Number", required=True).casefold() == metadata[2].casefold()}
|
||||
@@ -591,20 +658,26 @@ def _promotion_phase(snapshot, report, phase):
|
||||
|
||||
|
||||
def replacement_matches(components, records, target, require_part_label, *, library_row=None):
|
||||
current_by_uid = {_component_uid(component): component for component in components}
|
||||
if len(current_by_uid) != len(components):
|
||||
raise ValueError('Duplicate component UID on sheet')
|
||||
current_by_ref = {}
|
||||
for component in components:
|
||||
current_by_ref.setdefault(str(component.Refdes).strip().casefold(), []).append(component)
|
||||
expected_name = expected_label = None
|
||||
if library_row is not None:
|
||||
if (len(library_row) < 6 or str(library_row[1]).casefold() != target.casefold()
|
||||
or not str(library_row[4]).strip()):
|
||||
raise ValueError('Recorded target library identity is incomplete or inconsistent')
|
||||
expected_name, expected_label = str(library_row[4]), str(library_row[5])
|
||||
matches = []
|
||||
matches, used = [], set()
|
||||
for record in records:
|
||||
candidate = current_by_uid.get(record[1])
|
||||
if candidate is None:
|
||||
raise ValueError('Native replacement lost component UID identity')
|
||||
candidates = current_by_ref.get(str(record[2]).strip().casefold(), [])
|
||||
if len(candidates) > 1:
|
||||
candidates = [candidate for candidate in candidates if len(record) >= 7 and _same_unit(candidate, record[3:7])]
|
||||
if len(candidates) != 1:
|
||||
raise ValueError('Native replacement reference is missing or ambiguous')
|
||||
candidate = candidates[0]
|
||||
if id(candidate) in used:
|
||||
raise ValueError('Duplicate physical unit association')
|
||||
used.add(id(candidate))
|
||||
if attribute_value(candidate, "Part Number", required=True).casefold() != target.casefold():
|
||||
return None
|
||||
identity = str(candidate.Refdes).strip() or f"UID={candidate.UID}"
|
||||
@@ -622,7 +695,7 @@ def replacement_matches(components, records, target, require_part_label, *, libr
|
||||
if expected_name is not None and (part_name != expected_name
|
||||
or (expected_label and part_label != expected_label)):
|
||||
raise ValueError(f'Native replacement does not match the selected target library identity; uid={candidate.UID}')
|
||||
matches.append(_component_uid(candidate))
|
||||
matches.append(record[1])
|
||||
if len(set(matches)) != len(records):
|
||||
raise ValueError("Duplicate replacement association")
|
||||
return matches
|
||||
@@ -651,6 +724,7 @@ def verify_replacement_readback(snapshot, components, metadata, records, before_
|
||||
return verified
|
||||
|
||||
|
||||
@_bound_snapshot_identity
|
||||
def run_native(snapshot, report):
|
||||
import win32api
|
||||
import win32con
|
||||
@@ -854,7 +928,9 @@ def run_native(snapshot, report):
|
||||
report["stage"] = "native_replace_started"
|
||||
save_report(snapshot, report)
|
||||
mark_snapshot_mutation(snapshot)
|
||||
click(dlg_item(dialog, 1695))
|
||||
from .operation_diagnostics import operation_span
|
||||
with operation_span(Path(snapshot).parent, 'native_replace', item_id=Path(snapshot).stem):
|
||||
click(dlg_item(dialog, 1695))
|
||||
|
||||
replacement_poll_count = 0
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections import Counter
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
@@ -38,38 +38,45 @@ def _require_report(text, mode):
|
||||
|
||||
|
||||
def _effective_properties(text):
|
||||
from .native_netlist import _is_pcb
|
||||
_require_report(text, 'FLAT BLOCKS')
|
||||
if len(re.findall(r'^Config .+', text, re.MULTILINE)) != 1:
|
||||
raise NativeInventoryUnsupported('展开报告必须具有唯一配置')
|
||||
result, attributes, paths = {}, {}, []
|
||||
inconsistent_refs = set()
|
||||
symbol = None
|
||||
symbol = symbol_type = None
|
||||
|
||||
def finish():
|
||||
if symbol is None:
|
||||
return
|
||||
uid, ref = symbol
|
||||
if not _UID.fullmatch(uid):
|
||||
if attributes.get('Part Number'):
|
||||
raise NativeInventoryUnsupported('展开报告的物料缺少唯一 UID')
|
||||
if symbol_type is not None and not _is_pcb({'symbol': symbol_type, 'attributes': attributes}):
|
||||
return
|
||||
if uid in result or paths != ['']:
|
||||
raise NativeInventoryUnsupported('展开报告含重复或嵌套实例,需由 CAD 核验')
|
||||
uid, ref, page = symbol
|
||||
if not ref:
|
||||
if attributes.get('Part Number') and symbol_type and _is_pcb({'symbol': symbol_type,'attributes':attributes}):
|
||||
raise NativeInventoryUnsupported('展开报告的请求物料缺少位号')
|
||||
return
|
||||
unit = symbol_type.split(' type ', 1)[0] if symbol_type else ''
|
||||
key = (ref.strip().casefold(), page.strip(), unit)
|
||||
if key in result or paths != ['']:
|
||||
raise NativeInventoryUnsupported('展开报告含重复位号或嵌套实例,无法明确定位')
|
||||
if ref != attributes.get('Ref Designator', ''):
|
||||
inconsistent_refs.add(uid)
|
||||
result[uid] = dict(attributes)
|
||||
inconsistent_refs.add(key)
|
||||
result[key] = (uid, dict(attributes))
|
||||
if len(result) > 100000:
|
||||
raise NativeInventoryUnsupported('原生器件数量超过读取上限')
|
||||
|
||||
for line in text.splitlines():
|
||||
if line.startswith(' Symbol '):
|
||||
finish()
|
||||
match = re.fullmatch(r' Symbol (.+?)\tref des ([^\t]*)\tpage [^\t]*', line)
|
||||
match = re.fullmatch(r' Symbol (.*?)\tref des ([^\t]*)\tpage ([^\t]*)', line)
|
||||
if match is None:
|
||||
raise NativeInventoryUnsupported('展开报告含不明确的器件身份')
|
||||
symbol, attributes, paths = match.groups(), {}, []
|
||||
symbol, attributes, paths, symbol_type = match.groups(), {}, [], None
|
||||
elif symbol is not None and line.startswith('\tPath '):
|
||||
paths.append(line[6:])
|
||||
elif symbol is not None and line.startswith('\tSymbol name '):
|
||||
symbol_type = line[13:]
|
||||
elif symbol is not None:
|
||||
match = _PROPERTY.fullmatch(line)
|
||||
if match:
|
||||
@@ -82,39 +89,61 @@ def _effective_properties(text):
|
||||
|
||||
|
||||
def _parse_scope(text, requested, effective, inconsistent_refs):
|
||||
from .native_netlist import _is_pcb
|
||||
blocks, sheets, targets = set(), set(), set()
|
||||
seen_uids = set()
|
||||
block, symbol, attributes = '', None, {}
|
||||
physical_targets = {}
|
||||
by_ref = defaultdict(list)
|
||||
uid_counts = Counter(uid for uid, _ in effective.values())
|
||||
unit_counts = Counter(key[:2] for key in effective)
|
||||
for key in effective:
|
||||
by_ref[key[0]].append(key)
|
||||
block, symbol, attributes, symbol_type = '', None, {}, None
|
||||
def finish():
|
||||
if symbol is None:
|
||||
return
|
||||
uid, sheet = symbol
|
||||
if not _UID.fullmatch(uid):
|
||||
if attributes.get('Part Number'):
|
||||
raise NativeInventoryUnsupported('全工程报告中的请求物料缺少唯一身份')
|
||||
if symbol_type is not None and not _is_pcb({'symbol': symbol_type, 'attributes': attributes}):
|
||||
return
|
||||
if uid in seen_uids or uid not in effective:
|
||||
raise NativeInventoryUnsupported('分层与展开报告的 UID 不完整或重复,需由 CAD 核验')
|
||||
seen_uids.add(uid)
|
||||
values = effective[uid]
|
||||
uid, sheet = symbol
|
||||
ref = attributes.get('Ref Designator','')
|
||||
if not ref:
|
||||
if attributes.get('Part Number','').casefold() in requested:
|
||||
raise NativeInventoryUnsupported('全工程报告中的请求物料缺少位号')
|
||||
return
|
||||
unit = symbol_type.split(' type ', 1)[0] if symbol_type else ''
|
||||
candidates = [key for key in by_ref[ref.strip().casefold()]
|
||||
if (not key[1] or key[1] == sheet.strip())
|
||||
and (not key[2] or not unit or key[2] == unit)]
|
||||
if len(candidates) != 1 or candidates[0] in seen_uids:
|
||||
raise NativeInventoryUnsupported('分层与展开报告的器件范围不完整或位号重复')
|
||||
key = candidates[0]
|
||||
seen_uids.add(key)
|
||||
flat_uid, values = effective[key]
|
||||
if attributes.get('Part Number') and 'Part Number' not in values:
|
||||
raise NativeInventoryUnsupported('展开报告缺少物料生效属性')
|
||||
if 'Value' in attributes and 'Value' not in values:
|
||||
raise NativeInventoryUnsupported('展开报告缺少 Value 生效属性')
|
||||
if values.get('Part Number', '').casefold() in requested:
|
||||
# A library reference override on an unrelated part cannot affect
|
||||
# the requested identities. Still validate every UID/config/path,
|
||||
# the requested identities. Still validate every reference/config/path,
|
||||
# and require CAD whenever the ambiguous component is requested.
|
||||
if uid in inconsistent_refs:
|
||||
if key in inconsistent_refs:
|
||||
raise NativeInventoryUnsupported('展开报告的位号与属性不一致')
|
||||
ref, part = values.get('Ref Designator', ''), values['Part Number']
|
||||
if not ref or 'Ref Designator' not in attributes:
|
||||
raise NativeInventoryUnsupported('全工程报告中的请求物料缺少位号')
|
||||
target = (block, sheet, uid, ref, part, values.get('Value', ''),
|
||||
multiunit = unit_counts[key[:2]] > 1
|
||||
identity = uid if not multiunit and _UID.fullmatch(uid) and uid == flat_uid and uid_counts[uid] == 1 else '@REFDES|' + ref
|
||||
target = (block, sheet, identity, ref, part, values.get('Value', ''),
|
||||
values.get('Part Label'), values.get('Cell Name'))
|
||||
if target in targets:
|
||||
physical_key = block, sheet, ref
|
||||
prior = physical_targets.get(physical_key)
|
||||
if prior and prior[3:] != target[3:]:
|
||||
raise NativeInventoryUnsupported('Conflicting effective attributes across physical symbol units')
|
||||
if target in targets and not multiunit:
|
||||
raise NativeInventoryUnsupported('全工程报告含重复器件身份')
|
||||
targets.add(target)
|
||||
physical_targets[physical_key] = target
|
||||
if len(targets) > 100000:
|
||||
raise NativeInventoryUnsupported('原生器件数量超过读取上限')
|
||||
for line in text.splitlines():
|
||||
@@ -124,14 +153,16 @@ def _parse_scope(text, requested, effective, inconsistent_refs):
|
||||
if not name or name in blocks:
|
||||
raise NativeInventoryUnsupported('全工程报告含不明确的原理图身份')
|
||||
blocks.add(name)
|
||||
block, symbol, attributes = name, None, {}
|
||||
block, symbol, attributes, symbol_type = name, None, {}, None
|
||||
elif line.startswith(' Symbol '):
|
||||
finish()
|
||||
match = re.fullmatch(r' Symbol (.+?)\tpage (.+)', line)
|
||||
match = re.fullmatch(r' Symbol (.*?)\tpage (.+)', line)
|
||||
if not block or match is None:
|
||||
raise NativeInventoryUnsupported('全工程报告含不明确的图页身份')
|
||||
symbol, attributes = match.groups(), {}
|
||||
symbol, attributes, symbol_type = match.groups(), {}, None
|
||||
sheets.add((block, symbol[1]))
|
||||
elif symbol is not None and line.startswith('\tSymbol name '):
|
||||
symbol_type = line[13:]
|
||||
elif symbol is not None and line.startswith('\tProp '):
|
||||
# Pin properties have two tabs and must never override a component.
|
||||
match = _PROPERTY.fullmatch(line)
|
||||
@@ -149,49 +180,46 @@ def _parse_scope(text, requested, effective, inconsistent_refs):
|
||||
|
||||
|
||||
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)
|
||||
_, _, expanded = _check_hierarchy_graph(report_path, {'components': components}, root, include_rows=True)
|
||||
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():
|
||||
sheets = {(row['source_schematic'], row['source_page']) for row in expanded}
|
||||
counts = Counter(row.get('source_uid', uid) for uid, row in components.items())
|
||||
targets = {}
|
||||
for scope in expanded:
|
||||
row = components[scope['graph_key']]
|
||||
attributes = row['attributes']
|
||||
if attributes.get('Part Number', '').casefold() not in requested:
|
||||
if not _is_pcb(row) or 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')))
|
||||
if not scope.get('refdes'):
|
||||
raise NativeInventoryUnsupported('Hierarchical physical component is missing its reference observation')
|
||||
if 'Value' in scope['attributes'] and 'Value' not in attributes:
|
||||
raise NativeInventoryUnsupported('Effective physical component is missing its Value observation')
|
||||
if row.get('ambiguous_attributes'):
|
||||
raise NativeInventoryUnsupported('Requested physical component has ambiguous effective attributes')
|
||||
source_uid = row.get('source_uid', scope['source_uid'])
|
||||
identity = source_uid if (_UID.fullmatch(source_uid) and counts[source_uid] == 1
|
||||
and source_uid == scope['source_uid']) else '@REFDES|' + row['refdes']
|
||||
target = ComponentTarget(Path(project), scope['source_schematic'], scope['source_page'],
|
||||
identity, row['refdes'], attributes['Part Number'], attributes.get('Value', ''),
|
||||
attributes.get('Part Label'), attributes.get('Cell Name'))
|
||||
previous = targets.get(target.key)
|
||||
if previous and (previous.old_part_number, previous.old_value, previous.actual_part_label,
|
||||
previous.actual_cell) != (target.old_part_number, target.old_value,
|
||||
target.actual_part_label, target.actual_cell):
|
||||
raise NativeInventoryUnsupported('Conflicting effective attributes across physical symbol units')
|
||||
targets[target.key] = target
|
||||
matches = {sheet: set() for sheet in sheets}
|
||||
for target in targets:
|
||||
for target in targets.values():
|
||||
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)
|
||||
tuple(sorted(targets.values(), key=lambda target: target.key)), complete_sheet_manifest=False)
|
||||
|
||||
|
||||
def read_ascii_discovery(project, report_path, old_part_numbers, *, expected_root=None,
|
||||
|
||||
@@ -107,10 +107,11 @@ def _parse_ascii(path, *, hierarchy_boundaries=(), require_connections=True):
|
||||
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)
|
||||
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': []}
|
||||
symbol = {'uid': match[1], 'refdes': match[2], 'source_page': match[3].strip(),
|
||||
'attributes': {}, 'pins': {}, 'paths': []}
|
||||
symbols.append(symbol)
|
||||
pin = None
|
||||
elif symbol is not None:
|
||||
@@ -155,7 +156,7 @@ def _parse_ascii(path, *, hierarchy_boundaries=(), require_connections=True):
|
||||
raise ValueError('Duplicate or empty net')
|
||||
expected[net] = Counter()
|
||||
elif line.startswith('\t\tConn '):
|
||||
match = re.fullmatch(r'\t\tConn (.+?) pin (.+?) page .*', line)
|
||||
match = re.fullmatch(r'\t\tConn (.*?) pin (.+?) page .*', line)
|
||||
if net is None or not match:
|
||||
raise ValueError('Invalid net endpoint')
|
||||
conn = match.groups()
|
||||
@@ -168,12 +169,15 @@ def _parse_ascii(path, *, hierarchy_boundaries=(), require_connections=True):
|
||||
conn = None
|
||||
if conn is not None:
|
||||
raise ValueError('Endpoint missing path')
|
||||
raw_counts = Counter((row['uid'], tuple(row['paths'])) for row in symbols)
|
||||
endpoint_aliases = defaultdict(list)
|
||||
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
|
||||
symbol['source_uid'] = source_uid
|
||||
uid = _instance_identity(uid, paths[0])
|
||||
attrs = symbol['attributes']
|
||||
if paths[0]:
|
||||
@@ -181,8 +185,14 @@ def _parse_ascii(path, *, hierarchy_boundaries=(), require_connections=True):
|
||||
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']):
|
||||
if _is_pcb(symbol) and (not symbol['refdes'] or attrs.get('Ref Designator') != symbol['refdes']):
|
||||
raise ValueError(f'PCB component identity is ambiguous: {uid!r} / {symbol["refdes"]!r}')
|
||||
raw_identity = uid
|
||||
if _is_pcb(symbol) and (not re.fullmatch(r'\$\d+I\d+', source_uid)
|
||||
or raw_counts[(source_uid, tuple(paths))] > 1):
|
||||
slot = re.match(r'\S+\.(\d+) type ', symbol.get('symbol', ''))
|
||||
uid = _instance_identity('@REFDES|' + symbol['refdes'] + ('|slot=' + slot[1] if slot else ''), paths[0])
|
||||
endpoint_aliases[raw_identity].append(uid)
|
||||
symbol['other_attributes'] = sorted(symbol.get('other_attributes', []))
|
||||
if uid in components:
|
||||
old = components[uid]
|
||||
@@ -203,6 +213,16 @@ def _parse_ascii(path, *, hierarchy_boundaries=(), require_connections=True):
|
||||
for net in row['nets']:
|
||||
nets[net][(uid, pin)] += 1
|
||||
for name, endpoints in expected.items():
|
||||
normalized = Counter()
|
||||
for (uid, pin), count in endpoints.items():
|
||||
candidates = [key for key in endpoint_aliases.get(uid, [uid])
|
||||
if key in components and pin in components[key]['pins']
|
||||
and name in components[key]['pins'][pin]['nets']]
|
||||
if len(set(candidates)) == 1:
|
||||
uid = candidates[0]
|
||||
normalized[(uid, pin)] += count
|
||||
endpoints.clear()
|
||||
endpoints.update(normalized)
|
||||
for (uid, port), count in list(endpoints.items()):
|
||||
if uid not in hierarchy_boundaries:
|
||||
continue
|
||||
@@ -316,18 +336,19 @@ def read_graph(ascii_path, keyin_path, *, hierarchy_path=None, root_block=None):
|
||||
return graph
|
||||
|
||||
|
||||
def _check_hierarchy_graph(path, graph, root_block):
|
||||
"""Expand native child links independently; inventory UID selectors stay root-only."""
|
||||
def _check_hierarchy_graph(path, graph, root_block, *, include_rows=False):
|
||||
"""Bind expanded instances by reference/page/unit while retaining raw UID evidence."""
|
||||
text = read_native_text(path)
|
||||
_require_report(text, 'HIER BLOCKS')
|
||||
blocks, roots, block = {}, [], None
|
||||
blocks, roots, block, symbol = {}, [], None, 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()}
|
||||
blocks[block] = {'children': {}, 'symbols': Counter(), 'rows': []}
|
||||
symbol = None
|
||||
if fields[1:] == ['Root']:
|
||||
roots.append(block)
|
||||
elif line.startswith('\tChild '):
|
||||
@@ -336,13 +357,23 @@ def _check_hierarchy_graph(path, graph, root_block):
|
||||
raise ValueError('Ambiguous native hierarchy child')
|
||||
blocks[block]['children'][match[2]] = match[1]
|
||||
elif line.startswith(' Symbol '):
|
||||
match = re.fullmatch(r' Symbol (.+?)\tpage (.+)', line)
|
||||
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
|
||||
symbol = {'source_uid': match[1], 'source_page': match[2], 'attributes': {}}
|
||||
blocks[block]['rows'].append(symbol)
|
||||
elif symbol is not None and line.startswith('\tProp Ref Designator '):
|
||||
symbol['refdes'] = line[len('\tProp Ref Designator '):]
|
||||
elif symbol is not None and line.startswith('\tProp Part Number '):
|
||||
symbol['attributes']['Part Number'] = line[len('\tProp Part Number '):]
|
||||
elif symbol is not None and (line == '\tProp Value' or line.startswith('\tProp Value ')):
|
||||
symbol['attributes']['Value'] = line[len('\tProp Value '):]
|
||||
elif symbol is not None and line.startswith('\tSymbol name '):
|
||||
symbol['symbol'] = line[len('\tSymbol name '):]
|
||||
if roots != [root_block]:
|
||||
raise ValueError('Native hierarchy root differs from captured project')
|
||||
identities, boundaries = Counter(), set()
|
||||
identities, boundaries, expanded = Counter(), set(), []
|
||||
|
||||
pending = [(root_block, '', set())]
|
||||
while pending:
|
||||
@@ -352,6 +383,10 @@ def _check_hierarchy_graph(path, graph, root_block):
|
||||
row = blocks[name]
|
||||
identities.update({_instance_identity(uid, path): count for uid, count in row['symbols'].items()
|
||||
if uid not in row['children']})
|
||||
for item in row['rows']:
|
||||
if item['source_uid'] in row['children'] and not _is_pcb(item):
|
||||
continue
|
||||
expanded.append(dict(item, instance_path=path, source_schematic=name))
|
||||
for uid, child in row['children'].items():
|
||||
if uid not in row['symbols']:
|
||||
raise ValueError('Native hierarchy child symbol missing')
|
||||
@@ -359,10 +394,39 @@ def _check_hierarchy_graph(path, graph, root_block):
|
||||
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:
|
||||
remaining = [(uid, item) for uid, row in graph['components'].items()
|
||||
for item in row.get('annotation_instances', [row])]
|
||||
indices, consumed = defaultdict(list), set()
|
||||
for index, (uid, row) in enumerate(remaining):
|
||||
instance = row.get('instance_path', uid.rsplit('/', 1)[0] if '/' in uid else '')
|
||||
ref = row.get('source_refdes', row.get('refdes', '')).strip().casefold()
|
||||
indices[(instance, 'ref', ref)].append(index)
|
||||
indices[(instance, 'uid', row.get('source_uid', uid.rsplit('/', 1)[-1]))].append(index)
|
||||
for item in expanded:
|
||||
ref = item.get('refdes', '').strip().casefold()
|
||||
key = item['instance_path'], 'ref' if ref else 'uid', ref or item['source_uid']
|
||||
candidates = [(index, remaining[index][0], remaining[index][1]) for index in indices[key]
|
||||
if index not in consumed and (not remaining[index][1].get('source_page')
|
||||
or remaining[index][1]['source_page'] == item['source_page'])]
|
||||
if len(candidates) > 1 and item.get('symbol'):
|
||||
unit = item['symbol'].split(' type ', 1)[0]
|
||||
candidates = [candidate for candidate in candidates if candidate[2].get('symbol', '').split(' type ', 1)[0] == unit]
|
||||
if len(candidates) > 1:
|
||||
exact = [candidate for candidate in candidates if candidate[2].get('source_uid') == item['source_uid']]
|
||||
if exact:
|
||||
candidates = exact
|
||||
# Identical nonphysical annotations are counted, not mistaken for devices.
|
||||
if not candidates or (len(candidates) > 1 and ref):
|
||||
raise ValueError('Hierarchical/effective instance coverage differs')
|
||||
index, uid, row = candidates[0]
|
||||
item['graph_key'] = uid
|
||||
if row:
|
||||
row['source_schematic'] = item['source_schematic']
|
||||
row['source_page'] = row.get('source_page') or item['source_page']
|
||||
consumed.add(index)
|
||||
if len(consumed) != len(remaining):
|
||||
raise ValueError('Hierarchical/effective instance coverage differs')
|
||||
return identities, boundaries
|
||||
return (identities, boundaries, expanded) if include_rows else (identities, boundaries)
|
||||
|
||||
|
||||
def export_netlist(capture: dict, output: Path, *, stop_event=None) -> dict:
|
||||
@@ -466,6 +530,80 @@ def _connections(graph):
|
||||
return sorted(nets)
|
||||
|
||||
|
||||
def reference_targets(graph, refdes, *, sheet='', schematic=''):
|
||||
"""Return every native unit for a physical reference within the requested sheet."""
|
||||
ref = refdes.strip().casefold()
|
||||
candidates = [(uid, row) for uid, row in graph['components'].items()
|
||||
if _is_pcb(row) and row.get('refdes', '').strip().casefold() == ref]
|
||||
pages_known = any(row.get('source_page') for _, row in candidates)
|
||||
blocks_known = any(row.get('source_schematic') for _, row in candidates)
|
||||
return tuple(uid for uid, row in candidates
|
||||
if (not sheet or not pages_known or row.get('source_page') == sheet)
|
||||
and (not schematic or not blocks_known or row.get('source_schematic') == schematic))
|
||||
|
||||
|
||||
def _reference_graph(graph):
|
||||
"""Normalize physical endpoints without changing the captured source evidence."""
|
||||
from copy import deepcopy
|
||||
result = deepcopy(graph)
|
||||
identities, components = {}, {}
|
||||
groups = defaultdict(list)
|
||||
for row in result['components'].values():
|
||||
if _is_pcb(row):
|
||||
groups[row.get('refdes', '').strip().casefold()].append(row)
|
||||
for uid, row in result['components'].items():
|
||||
if _is_pcb(row):
|
||||
ref = row.get('refdes', '').strip().casefold()
|
||||
if not ref:
|
||||
raise ValueError('Physical component has no reference designator')
|
||||
# Separate slots of the same physical device remain independently checked.
|
||||
peers = groups[ref]
|
||||
scopes = {(item.get('source_schematic', ''), item.get('source_page', '')) for item in peers}
|
||||
scope = (row.get('source_schematic', ''), row.get('source_page', ''))
|
||||
same_scope = sum((item.get('source_schematic', ''), item.get('source_page', '')) == scope for item in peers)
|
||||
slot = re.match(r'\S+\.(\d+) type ', row.get('symbol', ''))
|
||||
identity = '@REFDES|' + ref
|
||||
if len(scopes) > 1:
|
||||
identity += '|sheet=' + json.dumps(scope, ensure_ascii=False)
|
||||
if same_scope > 1 and slot:
|
||||
repeated_slot = sum(bool(re.match(r'\S+\.' + re.escape(slot[1]) + r' type ', item.get('symbol', '')))
|
||||
for item in peers if (item.get('source_schematic', ''), item.get('source_page', '')) == scope) > 1
|
||||
if repeated_slot:
|
||||
numbers = [pin.get('number') for pin in row.get('pins', {}).values()]
|
||||
if not numbers or any(not number for number in numbers):
|
||||
raise ValueError('Repeated symbol slots lack a unique physical pin partition')
|
||||
identity += '|pins=' + json.dumps(sorted(numbers), ensure_ascii=False)
|
||||
else:
|
||||
identity += '|slot=' + slot[1]
|
||||
row.pop('source_uid', None)
|
||||
row.pop('instance_path', None)
|
||||
else:
|
||||
identity = uid
|
||||
if identity in components:
|
||||
raise ValueError('Reference designator and symbol slot are ambiguous')
|
||||
identities[uid] = identity
|
||||
components[identity] = row
|
||||
result['components'] = components
|
||||
for net in result['nets']:
|
||||
net['endpoints'] = [[identities.get(uid, uid), pin] for uid, pin in net['endpoints']]
|
||||
return result, identities
|
||||
|
||||
|
||||
def _reference_expectations(graph, aliases, values):
|
||||
result = {}
|
||||
for uid, value in (values or {}).items():
|
||||
targets = (uid,) if uid in aliases else ()
|
||||
if not targets and uid.startswith('@REFDES|'):
|
||||
targets = reference_targets(graph, uid[len('@REFDES|'):])
|
||||
scopes = {(graph['components'][key].get('source_schematic', ''),
|
||||
graph['components'][key].get('source_page', '')) for key in targets}
|
||||
if len(scopes) > 1:
|
||||
raise ValueError('Expected reference requires a sheet-qualified native identity')
|
||||
for target in targets or (uid,):
|
||||
result[aliases.get(target, target)] = value
|
||||
return result
|
||||
|
||||
|
||||
def compare_netlists(before: dict, after: dict, *, expected_changes=None, expected_symbols=None) -> dict:
|
||||
"""Compare complete nonempty exports, allowing only declared attribute/symbol changes.
|
||||
|
||||
@@ -476,7 +614,13 @@ def compare_netlists(before: dict, after: dict, *, expected_changes=None, expect
|
||||
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']
|
||||
try:
|
||||
left, aliases = _reference_graph(before['graph'])
|
||||
right, _ = _reference_graph(after['graph'])
|
||||
expected_changes = _reference_expectations(before['graph'], aliases, expected_changes)
|
||||
expected_symbols = _reference_expectations(before['graph'], aliases, expected_symbols)
|
||||
except (KeyError, TypeError, ValueError) as error:
|
||||
return {'status': 'unavailable', 'verified': False, 'reason': str(error)}
|
||||
differences = []
|
||||
try:
|
||||
connections_changed = _connections(left) != _connections(right)
|
||||
|
||||
@@ -76,7 +76,8 @@ def library_from_receipt(command, receipt):
|
||||
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']}"):
|
||||
or metadata[4] != f"{command['schematic_name']}:{command['sheet_number']}"
|
||||
or (metadata[9] if len(metadata) == 10 else '') != command.get('target_selectors', '')):
|
||||
raise ValueError('原生库件证据属于不同执行项')
|
||||
row = binding['library_row']
|
||||
if row[1].casefold() != command['new_part'].casefold() or not row[4]:
|
||||
@@ -95,7 +96,9 @@ def library_from_receipt(command, receipt):
|
||||
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']}
|
||||
'target_symbol': binding['target_symbol'], 'slot_count': binding['slot_count'],
|
||||
'refdes': next(record[2] for record in records if record[1] == uid),
|
||||
'schematic_name': command.get('schematic_name',''), 'sheet_number': command.get('sheet_number','')}
|
||||
if uid in values:
|
||||
value = values[uid]
|
||||
if (value['actual_part_number'].casefold() != row[1].casefold()
|
||||
@@ -180,30 +183,82 @@ def _rule_rows(child, task_id, plan, before):
|
||||
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]):
|
||||
keys = native_netlist.reference_targets(before['graph'], selector[1],
|
||||
sheet=command.get('sheet_number',''),schematic=command.get('schematic_name',''))
|
||||
if ((set(identities) != {selector[0]} and not all(
|
||||
identity.get('refdes','').strip().casefold() == selector[1].strip().casefold()
|
||||
for identity in identities.values())) or not keys or any(
|
||||
before['graph']['components'][key].get('attributes', {}).get('Value', '') != selector[2]
|
||||
for key in keys)):
|
||||
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():
|
||||
identity = identities[uid]
|
||||
keys = _reference_keys(before['graph'], dict(identity, uid=uid,
|
||||
sheet_number=command.get('sheet_number',''), schematic_name=command.get('schematic_name','')))
|
||||
if not keys or any(before['graph']['components'][key]['attributes'].get('Part Number', '').casefold()
|
||||
!= command['old_part'].casefold() for key in keys):
|
||||
raise ValueError('原生 UID 无法唯一对应替换前的原料号;不能按同料号猜测图页')
|
||||
row = {'enabled': True, 'target': {'uid': uid, 'old_value': component['attributes'].get('Value', '')},
|
||||
for key in keys:
|
||||
component = before['graph']['components'][key]
|
||||
row = {'enabled': True, 'target': {'uid': key, 'refdes': component['refdes'],
|
||||
'schematic_name':command.get('schematic_name',''),'sheet_number':command.get('sheet_number',''),
|
||||
'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 key in rows and rows[key] != row:
|
||||
raise ValueError('同一位号对应多个不同规则结果,不能独立核验')
|
||||
rows[key] = row
|
||||
if not rows:
|
||||
raise ValueError('已保存的规则替换缺少可核验的原生 UID 事务')
|
||||
return list(rows.values()), scopes
|
||||
|
||||
|
||||
def _reference_keys(graph, identity):
|
||||
ref = identity.get('refdes', '').strip().casefold()
|
||||
keys = native_netlist.reference_targets(graph, ref, sheet=identity.get('sheet_number',''),
|
||||
schematic=identity.get('schematic_name','')) if ref else ()
|
||||
uid = identity.get('uid')
|
||||
if not keys and uid in graph['components']:
|
||||
component = graph['components'][uid]
|
||||
constraints = ((ref, component.get('refdes','').strip().casefold()),
|
||||
(identity.get('sheet_number',''), component.get('source_page','')),
|
||||
(identity.get('schematic_name',''), component.get('source_schematic','')))
|
||||
if not any(expected and actual and expected != actual for expected, actual in constraints):
|
||||
keys = (uid,)
|
||||
return keys
|
||||
|
||||
|
||||
def _reference_plan(plan, before, library):
|
||||
from copy import deepcopy
|
||||
result, rebound = deepcopy(plan), {}
|
||||
components = before['graph']['components']
|
||||
rows = []
|
||||
for row in result['rows']:
|
||||
target = row['target']
|
||||
keys = _reference_keys(before['graph'], target)
|
||||
if not keys and row['enabled']:
|
||||
raise ValueError('独立网表无法定位计划中的位号')
|
||||
for key in keys:
|
||||
item = deepcopy(row)
|
||||
item['target']['uid'] = key
|
||||
rows.append(item)
|
||||
if target['uid'] in library:
|
||||
rebound[key] = library[target['uid']]
|
||||
for uid, identity in library.items():
|
||||
keys = _reference_keys(before['graph'], dict(identity, uid=uid))
|
||||
if not keys:
|
||||
raise ValueError('独立网表无法定位回执中的位号或图页')
|
||||
for key in keys:
|
||||
rebound[key] = identity
|
||||
result['rows'] = rows
|
||||
return result, rebound
|
||||
|
||||
|
||||
class NetlistVerification:
|
||||
def __init__(self, root, run_id, stop_event):
|
||||
self.root, self.run_id, self.stop = Path(root), run_id, stop_event
|
||||
@@ -398,6 +453,7 @@ class NetlistVerification:
|
||||
rows, scopes = _rule_rows(record['child'], task_id, plan, before)
|
||||
plan = dict(plan, rows=rows)
|
||||
result['rule_scopes'] = scopes
|
||||
plan, library = _reference_plan(plan, before, library)
|
||||
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}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Small append-only call timeline; diagnostics never replace an execution error."""
|
||||
from datetime import datetime, timezone
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import os
|
||||
|
||||
from .path_access import internal_path
|
||||
|
||||
|
||||
def record_operation(root, operation, event, *, item_id='', error=''):
|
||||
if event not in {'enter', 'return', 'error'}:
|
||||
raise ValueError('operation event must be enter, return or error')
|
||||
try:
|
||||
record = {'timestamp_utc': datetime.now(timezone.utc).isoformat(),
|
||||
'operation': operation, 'event': event, 'item_id': item_id}
|
||||
if error:
|
||||
record['error'] = str(error)
|
||||
line = json.dumps(record, ensure_ascii=False) + '\n'
|
||||
path = internal_path(root) / 'operation-events.jsonl'
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open('a', encoding='utf-8') as stream:
|
||||
stream.write(line)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
@contextmanager
|
||||
def operation_span(root, operation, *, item_id=''):
|
||||
"""Trace a real call without letting diagnostics change its outcome."""
|
||||
def publish(event, error=''):
|
||||
try:
|
||||
record_operation(root, operation, event, item_id=item_id, error=error)
|
||||
except Exception:
|
||||
pass
|
||||
publish('enter')
|
||||
try:
|
||||
yield
|
||||
except BaseException as error:
|
||||
publish('error', error)
|
||||
raise
|
||||
else:
|
||||
publish('return')
|
||||
|
||||
|
||||
def summarize_operations(records):
|
||||
active, errors, last_item = {}, [], None
|
||||
for record in records:
|
||||
if not isinstance(record, dict) or not all(isinstance(record.get(name, ''), str)
|
||||
for name in ('operation', 'item_id', 'event')):
|
||||
continue
|
||||
key = record.get('operation'), record.get('item_id', '')
|
||||
if record.get('event') == 'enter':
|
||||
active[key] = record
|
||||
elif record.get('event') in {'return', 'error'}:
|
||||
active.pop(key, None)
|
||||
if record['event'] == 'error':
|
||||
errors.append(record)
|
||||
elif record.get('operation') == 'item' and record.get('item_id'):
|
||||
last_item = record['item_id']
|
||||
return {'last_successful_item': last_item, 'incomplete_operations': list(active.values()),
|
||||
'errors': errors}
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Keep uncertain engineering sources quarantined without stopping unrelated work."""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import re
|
||||
|
||||
from .path_access import canonical_path, internal_path
|
||||
|
||||
|
||||
def write_sources(project):
|
||||
project = canonical_path(project)
|
||||
sources = {str(project).casefold()}
|
||||
try:
|
||||
from .native_inventory_protocol import read_native_text
|
||||
text = read_native_text(internal_path(project))
|
||||
match = re.search(r'^\s*KEY\s+iCDBDir\s+"([^"\r\n]+)"', text, re.MULTILINE | re.IGNORECASE)
|
||||
if match:
|
||||
directory = Path(match[1])
|
||||
if not directory.is_absolute():
|
||||
directory = project.parent / directory
|
||||
sources.add(str(canonical_path(directory / 'icdb.dat')).casefold())
|
||||
except (OSError, UnicodeError, ValueError):
|
||||
pass
|
||||
return sources
|
||||
|
||||
|
||||
def record_task_outcome(child, task_id, state, message):
|
||||
store = getattr(child, '_store', None)
|
||||
if store is None:
|
||||
return
|
||||
from .models import TaskStatus
|
||||
target = {'blocked': TaskStatus.BLOCKED, 'failed': TaskStatus.FAILED, 'paused': TaskStatus.PAUSED}.get(state)
|
||||
if target is None:
|
||||
return # Successful completion is committed with its actual execution receipts.
|
||||
with store.transaction():
|
||||
task = store.get_task(task_id)
|
||||
if task.status not in {TaskStatus.COMPLETED, TaskStatus.DELETED}:
|
||||
store.set_task_status(task_id, target, summary=message)
|
||||
|
||||
|
||||
def isolate_project(runtime, child, task_id, error):
|
||||
release = getattr(runtime, 'release_failed_project', None)
|
||||
if release is None:
|
||||
return False
|
||||
preparer = getattr(child, '_quick_run_preparer', None)
|
||||
root = preparer.data_root / 'quick-run' if preparer is not None else runtime.root / 'tasks' / task_id / 'quick-run'
|
||||
released = release(error, root)
|
||||
return released
|
||||
|
||||
|
||||
def dependency_path(root, task_id):
|
||||
return canonical_path(root) / 'dependency-blocks' / (task_id + '.json')
|
||||
|
||||
|
||||
def dependency_block(root, task_id):
|
||||
from .errors import TaskCenterError
|
||||
try:
|
||||
value = json.loads(internal_path(dependency_path(root, task_id)).read_text(encoding='utf-8'))
|
||||
if (not isinstance(value, dict) or value.get('version') != 1 or value.get('task_id') != task_id or value.get('undispatched') is not True
|
||||
or value.get('state') not in {'blocked', 'readmission_prepared', 'readmitted'}
|
||||
or not isinstance(value.get('dependency_task_id'), str)
|
||||
or Path(value['dependency_task_id']).name != value['dependency_task_id']
|
||||
or not isinstance(value.get('sources'), list) or not value['sources']
|
||||
or not all(isinstance(source, str) and Path(source).is_absolute() for source in value['sources'])
|
||||
or not isinstance(value.get('plan_hash'), str) or not re.fullmatch('[0-9a-f]{64}', value['plan_hash'])
|
||||
or not isinstance(value.get('queue_id'), str) or not re.fullmatch('[0-9a-f]{32}', value['queue_id'])
|
||||
or not isinstance(value.get('project_path'), str) or not Path(value['project_path']).is_absolute()):
|
||||
raise ValueError('invalid dependency block')
|
||||
return value
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except (OSError, ValueError, TypeError) as error:
|
||||
raise TaskCenterError('quick_run_dependency', '共享数据源隔离记录无法核验,请保留证据。') from error
|
||||
|
||||
|
||||
def block_dependency(root, child, task_id, dependency_task_id, sources, plan_hash, queue_id):
|
||||
from .batch_resources import write_record
|
||||
projects = child.projects(task_id)
|
||||
write_record(dependency_path(root, task_id), {'version': 1, 'task_id': task_id,
|
||||
'dependency_task_id': dependency_task_id, 'sources': sorted(sources), 'plan_hash': plan_hash,
|
||||
'project_path': str(canonical_path(projects[0].path)).casefold(),
|
||||
'queue_id': queue_id, 'state': 'blocked', 'undispatched': True})
|
||||
record_task_outcome(child, task_id, 'blocked', f'共享数据源依赖 {dependency_task_id} 尚待核验;本任务未派发替换。')
|
||||
|
||||
|
||||
def _validate_dependency(service, task_id, block):
|
||||
from .batch_resources import resource_blockers
|
||||
from .errors import TaskCenterError
|
||||
from .models import TaskStatus
|
||||
from .task_queue import _plan_hash
|
||||
child = service.for_project_task(task_id)
|
||||
dependency = service.for_project_task(block['dependency_task_id'])
|
||||
projects = child.projects(task_id)
|
||||
dependency_projects = dependency.projects(block['dependency_task_id'])
|
||||
queue_path = next((path for directory in ('task-queues', 'workspace-queues')
|
||||
if internal_path(path := canonical_path(service._logging.root) / directory / (block['queue_id'] + '.json')).is_file()), None)
|
||||
try:
|
||||
queue = json.loads(internal_path(queue_path).read_text(encoding='utf-8')) if queue_path else {}
|
||||
queue_bound = (queue['plan_hashes'][task_id] == block['plan_hash']
|
||||
and queue['dependency_tasks'][task_id] == block['dependency_task_id']
|
||||
and queue['entries'][task_id]['state'] == 'blocked')
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
queue_bound = False
|
||||
store = getattr(child, '_store', None)
|
||||
with store._lock:
|
||||
dispatched = store._connection.execute('''SELECT 1 FROM execution_operations
|
||||
WHERE task_id=? AND (attempt_id IS NOT NULL OR generation>0 OR state NOT IN ('pending')) LIMIT 1''',
|
||||
(task_id,)).fetchone()
|
||||
evidence = child._quick_run_preparer.data_root / 'quick-run'
|
||||
absent_attempt = not dispatched and not any(internal_path(evidence).glob('snapshot-*'))
|
||||
if (len(projects) != 1 or len(dependency_projects) != 1
|
||||
or not queue_bound or not absent_attempt
|
||||
or str(canonical_path(projects[0].path)).casefold() != block['project_path']
|
||||
or _plan_hash(child, task_id) != block['plan_hash']
|
||||
or not set(block['sources']) <= write_sources(projects[0].path) & write_sources(dependency_projects[0].path)
|
||||
or child.has_interrupted_quick_run(task_id)
|
||||
or dependency.has_interrupted_quick_run(block['dependency_task_id'])
|
||||
or dependency.get_task(block['dependency_task_id']).status not in {TaskStatus.READY, TaskStatus.COMPLETED}
|
||||
or resource_blockers(service.pending_batch_resources())):
|
||||
raise TaskCenterError('quick_run_dependency', '原依赖工程尚未核验、写入资源未退出或冻结计划已变化,不能解除隔离。')
|
||||
|
||||
|
||||
def recover_dependency(service, task_id, *, confirmed):
|
||||
from .batch_resources import write_record
|
||||
from .errors import TaskCenterError
|
||||
from .models import TaskStatus
|
||||
from .quick_run_protocol import QuickRunStepResult
|
||||
root = service._logging.root
|
||||
block = dependency_block(root, task_id)
|
||||
if not confirmed:
|
||||
raise TaskCenterError('quick_run_dependency', '请确认核验共享数据源依赖后解除未派发任务的隔离。')
|
||||
_validate_dependency(service, task_id, block)
|
||||
path = dependency_path(root, task_id)
|
||||
write_record(path, dict(block, state='readmission_prepared'))
|
||||
with service._store.transaction():
|
||||
task = service._store.get_task(task_id)
|
||||
if task.status is TaskStatus.BLOCKED:
|
||||
service._store.set_task_status(task_id, TaskStatus.READY, summary='共享数据源依赖已核验;原计划未派发,可重新确认执行。')
|
||||
elif task.status not in {TaskStatus.READY, TaskStatus.COMPLETED}:
|
||||
raise TaskCenterError('quick_run_dependency', '当前任务状态已变化,请重新读取隔离记录。')
|
||||
write_record(path, dict(block, state='readmitted'))
|
||||
child = service.for_project_task(task_id)
|
||||
progress = child.quick_run_progress(task_id)
|
||||
handoff = child._quick_run_preparer.data_root / 'quick-run'
|
||||
return QuickRunStepResult(handoff / 'QuickPartReplace.vbs', handoff / 'command.tsv', handoff / 'status.tsv', path,
|
||||
'pending', '共享数据源依赖已核验;本任务从未派发替换,已恢复原待执行计划。',
|
||||
progress.next_project_path, progress.next_old_part_number, progress.next_new_part_number,
|
||||
progress.next_schematic_name, progress.next_sheet_number, progress)
|
||||
|
||||
|
||||
def dependency_readmitted(service, task_id, plan_hash):
|
||||
from .models import TaskStatus
|
||||
block = dependency_block(service._logging.root, task_id)
|
||||
if not block or block['state'] not in {'readmission_prepared', 'readmitted'} or block['plan_hash'] != plan_hash:
|
||||
return False
|
||||
if service.get_task(task_id).status not in {TaskStatus.READY, TaskStatus.COMPLETED}:
|
||||
return False
|
||||
_validate_dependency(service, task_id, block)
|
||||
return True
|
||||
@@ -2,12 +2,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from threading import Event, Thread
|
||||
from uuid import uuid4
|
||||
|
||||
from .worker_monitor import WorkerMonitorError, run_monitored_process
|
||||
from .operation_diagnostics import operation_span
|
||||
|
||||
|
||||
def _write_control(path: Path, value: str):
|
||||
@@ -28,7 +30,7 @@ def _write_control(path: Path, value: str):
|
||||
|
||||
|
||||
class ProjectSessionWorker:
|
||||
"""Only a saved-and-reopened checkpoint releases the caller for its next step.
|
||||
"""Retain applied steps; engineering close performs the save/readback commit.
|
||||
|
||||
The VBS worker owns CAD. This driver never attaches to COM or terminates CAD.
|
||||
A separate monitor thread retains the existing idle watchdog and worker job.
|
||||
@@ -61,6 +63,10 @@ class ProjectSessionWorker:
|
||||
self._done.set()
|
||||
|
||||
def run_step(self, command: tuple[str, ...], timeout: float):
|
||||
with operation_span(self.root, 'native_step', item_id=command[-1]):
|
||||
return self._run_step(command, timeout)
|
||||
|
||||
def _run_step(self, command: tuple[str, ...], timeout: float):
|
||||
if self._closed:
|
||||
raise WorkerMonitorError('project session is already closed')
|
||||
if Path(command[3]).resolve() != self.root.resolve():
|
||||
@@ -82,6 +88,7 @@ class ProjectSessionWorker:
|
||||
if not self._waiting:
|
||||
raise WorkerMonitorError('project session has no verified checkpoint')
|
||||
self._waiting = False
|
||||
_write_control(self.root / 'project-session.request', f'{self.token}\t{self.project}\t{job}')
|
||||
_write_control(self.root / 'project-session-next.tsv', f'{self.token}\t{job}')
|
||||
while True:
|
||||
if self._done.is_set():
|
||||
@@ -92,8 +99,8 @@ 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 self._result.returncode in {74, 75}:
|
||||
pause = getattr(self._result, 'startup_pause' if self._result.returncode == 74 else 'prewrite_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):
|
||||
@@ -110,13 +117,20 @@ class ProjectSessionWorker:
|
||||
except (FileNotFoundError, PermissionError):
|
||||
fields = ()
|
||||
if len(fields) == 4 and fields[:2] == [self.token, job]:
|
||||
if fields[2] not in {'saved_ok', 'no_match'} or fields[3] != 'session_verified':
|
||||
if (fields[2], fields[3]) not in {('saved_ok', 'session_verified'), ('no_match', 'session_verified'),
|
||||
('pending_save', 'session_staged'), ('pending_save', 'session_staged_no_match')}:
|
||||
raise WorkerMonitorError('project session returned an invalid checkpoint')
|
||||
self._waiting = True
|
||||
return subprocess.CompletedProcess(command, 0, '', '')
|
||||
self._done.wait(0.025)
|
||||
|
||||
def close(self):
|
||||
if not self._closed and self._thread is not None and not self._done.is_set():
|
||||
with operation_span(self.root, 'close_project', item_id=self.token):
|
||||
return self._close()
|
||||
return self._close()
|
||||
|
||||
def _close(self):
|
||||
if self._closed:
|
||||
return
|
||||
try:
|
||||
@@ -128,25 +142,33 @@ class ProjectSessionWorker:
|
||||
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:
|
||||
# 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:
|
||||
force_event = getattr(getattr(self.runtime, 'stop_event', None), 'force_event', None)
|
||||
last_notice = time.monotonic()
|
||||
deadline = last_notice + close_grace
|
||||
last_progress = (-1, -1)
|
||||
while not self._done.wait(.1):
|
||||
if force_event is not None and force_event.is_set():
|
||||
self._abort.set()
|
||||
break
|
||||
try:
|
||||
native = json.loads((self.root / 'worker-progress.json').read_text(encoding='utf-8'))
|
||||
progress = (native['sequence'], native.get('native_progress_frames', 0))
|
||||
if all(type(value) is int for value in progress) and progress > last_progress:
|
||||
last_progress = progress
|
||||
deadline = time.monotonic() + close_grace
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
pass
|
||||
if time.monotonic() >= deadline:
|
||||
if interactive:
|
||||
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()
|
||||
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()
|
||||
if not self._done.wait(close_grace):
|
||||
self._abort.set()
|
||||
if not self._done.wait(30):
|
||||
@@ -174,6 +196,7 @@ class ProjectSessionScope:
|
||||
self.worker = None
|
||||
self.private_desktop = private_desktop
|
||||
self.runtime = runtime
|
||||
self.on_commit = None
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
@@ -189,13 +212,25 @@ class ProjectSessionScope:
|
||||
def prepare(self, project):
|
||||
if self.worker is not None and (self.worker.project.resolve() != Path(project).resolve()
|
||||
or self.worker._done.is_set()):
|
||||
self.worker.close()
|
||||
self.worker = None
|
||||
self.close()
|
||||
|
||||
def close(self):
|
||||
if self.worker is None:return
|
||||
worker = self.worker
|
||||
worker.close()
|
||||
if self.on_commit is not None:
|
||||
self.on_commit(worker)
|
||||
self.on_commit = None
|
||||
self.worker = None
|
||||
|
||||
def __exit__(self, error_type, error, traceback):
|
||||
if self.worker is not None:
|
||||
try:
|
||||
self.worker.close()
|
||||
except Exception:
|
||||
self.close()
|
||||
except Exception as cleanup_error:
|
||||
self.worker._abort.set()
|
||||
if error is not None:
|
||||
if hasattr(error, 'add_note'):
|
||||
error.add_note('Project session cleanup: ' + str(cleanup_error))
|
||||
return False
|
||||
raise
|
||||
@@ -376,6 +376,7 @@ class QuickRunPreparer:
|
||||
from .handoff_guard import assert_handoff_intact
|
||||
assert_handoff_intact(root, task_id)
|
||||
try:
|
||||
self._commit_staged_project(task_id)
|
||||
self._bind_journal_handoff(task_id, QuickRunResult(root/'QuickPartReplace.vbs',
|
||||
root/'command.tsv', root/'status.tsv', root/'quick-part-replace.log', self.vbs_root_compatible))
|
||||
except TaskCenterError:
|
||||
@@ -387,6 +388,194 @@ class QuickRunPreparer:
|
||||
return capture_result(self._data_root,root,row,outcome,
|
||||
strict=self._process_runner is _run_process,persist=persist)
|
||||
|
||||
def _commit_staged_project(self, task_id, *, session_token=None, bind_source=False):
|
||||
journal = getattr(self, 'journal', None)
|
||||
if journal is None:return
|
||||
from .execution_proof import capture_project_commit
|
||||
from .operation_diagnostics import record_operation
|
||||
for commit in journal.pending_project_commits(task_id):
|
||||
if session_token is not None and commit['session_token'] != session_token:continue
|
||||
root = Path(commit['evidence_root'])
|
||||
record_operation(root, 'readback_proof', 'enter', item_id=commit['session_token'])
|
||||
try:
|
||||
commit_proof = capture_project_commit(self._data_root, root, commit)
|
||||
if commit.get('proof_json'):
|
||||
commit_proof = json.loads(commit['proof_json'])
|
||||
if commit_proof.get('saved_sources'):
|
||||
from .execution_proof import validate_project_commit_source
|
||||
if (not validate_project_commit_source(commit_proof, root)
|
||||
or capture_project_commit(self._data_root, root, commit)['files'][0]['sha256'] != commit_proof['files'][0]['sha256']):
|
||||
raise ValueError('saved project proof changed before receipt commit')
|
||||
elif bind_source:
|
||||
from .execution_proof import bind_project_commit_source
|
||||
commit_proof = bind_project_commit_source(commit_proof, self._data_root, root, commit['project_path'])
|
||||
commit_proof['operation_attempts'] = journal.project_commit_attempts(task_id, commit['session_token'])
|
||||
proofs = {}
|
||||
for receipt in journal.staged_project_rows(task_id, commit['session_token']):
|
||||
row = receipt['row']
|
||||
outcome = (commit_proof['outcomes'][row['job_id']], 'project_committed', '工程保存回读校验通过。')
|
||||
proof = self.result_proof(root, row, outcome)
|
||||
if outcome[0] == 'saved_ok':
|
||||
from .value_readback import capture_value_readback
|
||||
proof['value_readback'] = capture_value_readback(root, row, outcome, project_commit=commit_proof)
|
||||
proofs[row['job_id']] = proof
|
||||
if bind_source and not commit.get('proof_json'):
|
||||
commit_proof['readback_files'] = {Path(item['path']).name: item['sha256']
|
||||
for proof in proofs.values() for item in proof.get('files', ())}
|
||||
for job, outcome in commit_proof['outcomes'].items():
|
||||
if outcome == 'saved_ok':
|
||||
value_path = _io_path(root / f'value-readback-{job}.tsv')
|
||||
if value_path.is_file():commit_proof['readback_files'][value_path.name] = hashlib.sha256(value_path.read_bytes()).hexdigest()
|
||||
journal.bind_project_commit_proof(task_id, commit['session_token'], commit_proof)
|
||||
journal.commit_project_results(task_id, commit['session_token'], proofs, commit_proof)
|
||||
record_operation(root, 'readback_proof', 'return', item_id=commit['session_token'])
|
||||
for job in commit_proof['jobs']:
|
||||
record_operation(root, 'item', 'return', item_id=job)
|
||||
except Exception as error:
|
||||
record_operation(root, 'readback_proof', 'error', item_id=commit['session_token'], error=str(error))
|
||||
raise
|
||||
|
||||
def recover_project_commit(self, task_id, *, confirmed=False):
|
||||
"""Reconcile an already closed/saved project without acquiring CAD."""
|
||||
journal = getattr(self, 'journal', None)
|
||||
if journal is None:return None
|
||||
commits = journal.project_commit_records(task_id)
|
||||
root = self._data_root / 'quick-run'
|
||||
flag = _io_path(root / 'uncertain.flag')
|
||||
audit = root / 'project-commit-recovery.json'
|
||||
if not commits:return None
|
||||
protection = flag.read_bytes() if flag.is_file() else None
|
||||
allowed = {f'reason={reason}; manual reconciliation required\n'.encode() for reason in
|
||||
('receipt_commit_failed', 'project_commit_unverified', 'uncommitted_receipt_requires_verification')}
|
||||
interrupted = None
|
||||
if protection is not None:
|
||||
import re
|
||||
match = re.fullmatch(rb'reason=supervisor_interrupted; batch=([0-9a-f]{32}); manual reconciliation required\r?\n', protection)
|
||||
if match:interrupted = match[1].decode('ascii')
|
||||
if protection is None:
|
||||
try:
|
||||
completed = json.loads(_io_path(audit).read_text(encoding='utf-8'))
|
||||
if (completed.get('task_id') != task_id or completed.get('native_replacement_called') is not False
|
||||
or completed.get('session_tokens') != [commit['session_token'] for commit in commits]):return None
|
||||
except (OSError, ValueError, TypeError):return None
|
||||
elif protection not in allowed and interrupted is None:return None
|
||||
if not confirmed:
|
||||
raise TaskCenterError('quick_run_recovery_confirmation', '工程提交回执核验需要明确确认。')
|
||||
from .execution_proof import capture_project_commit, validate_project_commit_source
|
||||
from .execution_journal import read_command_rows, command_identity, _hash
|
||||
from .batch_resources import write_record
|
||||
try:
|
||||
rows = read_command_rows(root / 'command.tsv')
|
||||
if not rows or any(row['task_id'] != task_id for row in rows):raise ValueError('foreign command plan')
|
||||
current = journal._round(task_id)
|
||||
if json.loads(current['plan_json']) != [_hash(command_identity(row)) for row in rows]:
|
||||
raise ValueError('frozen command plan changed')
|
||||
covered = set()
|
||||
covered_attempts = []
|
||||
for commit in commits:
|
||||
if Path(commit['evidence_root']).resolve() != root.resolve():raise ValueError('foreign commit root')
|
||||
proof = json.loads(commit['proof_json'] or '{}')
|
||||
if proof and proof.get('operation_attempts') != journal.project_commit_attempts(task_id, commit['session_token']):
|
||||
raise ValueError('original project attempts changed')
|
||||
if not proof or interrupted is not None:
|
||||
from .batch_resources import _valid_record
|
||||
checkpoint = json.loads(_io_path(root / 'project-checkpoint.json').read_text(encoding='utf-8'))
|
||||
owner_path = Path(checkpoint['resource_record'])
|
||||
owner = json.loads(_io_path(owner_path).read_text(encoding='utf-8'))
|
||||
proof = checkpoint['project_commit_source']
|
||||
native = {key: checkpoint[key] for key in ('session_id', 'generation', 'attempt_id')}
|
||||
if (not _valid_record(owner, owner_path) or checkpoint.get('worker_closed') is not True
|
||||
or checkpoint.get('project_closed') is not True
|
||||
or Path(checkpoint['evidence_root']).resolve() != root.resolve()
|
||||
or _path_key(checkpoint['project_path']) != _path_key(commit['project_path'])
|
||||
or owner['session_id'] != native['session_id'] or owner['generation'] != native['generation']
|
||||
or owner['checkpoints'].get(str(root.resolve()).casefold()) != native['attempt_id']
|
||||
or proof.get('native_attempt') != native or proof.get('session_token') != commit['session_token']
|
||||
or proof.get('jobs') != json.loads(commit['jobs_json'])):
|
||||
raise ValueError('native close checkpoint is not bound to this project commit')
|
||||
if interrupted is not None:
|
||||
supervisor = json.loads(_io_path(owner_path.parent / 'supervisor.json').read_text(encoding='utf-8'))
|
||||
if (native['session_id'] != interrupted or supervisor.get('batch_id') != interrupted
|
||||
or supervisor.get('state') != 'blocked' or supervisor.get('business_uncertain') is not True
|
||||
or task_id not in supervisor.get('protected_task_ids', ())):
|
||||
raise ValueError('supervisor interruption is not bound to the closed native worker')
|
||||
proof = dict(proof, operation_attempts=journal.project_commit_attempts(task_id, commit['session_token']))
|
||||
if (not validate_project_commit_source(proof, root)
|
||||
or proof.get('operation_attempts') != journal.project_commit_attempts(task_id, commit['session_token'])):
|
||||
raise ValueError('saved source or original attempts changed')
|
||||
marker = capture_project_commit(self._data_root, root, commit)
|
||||
if (marker['jobs'] != proof.get('jobs') or marker['outcomes'] != proof.get('outcomes')
|
||||
or marker['files'][0]['sha256'] != proof['files'][0]['sha256']):
|
||||
raise ValueError('native project marker changed')
|
||||
covered.update(proof['jobs'])
|
||||
covered_attempts.extend(proof['operation_attempts'].values())
|
||||
for row in rows:
|
||||
if row['job_id'] not in proof['jobs']:continue
|
||||
outcome = (proof['outcomes'][row['job_id']], 'project_committed', '工程保存回读校验通过。')
|
||||
result = self.result_proof(root, row, outcome)
|
||||
if proof.get('native_attempt') and outcome[0] == 'saved_ok' and any(
|
||||
result.get('native_attempt', {}).get(key) != value for key, value in proof['native_attempt'].items()):
|
||||
raise ValueError('native result differs from the exited project worker')
|
||||
if any(proof.get('readback_files', {}).get(Path(item['path']).name) != item['sha256'] for item in result.get('files', ())):
|
||||
raise ValueError('saved native readback evidence changed')
|
||||
if outcome[0] == 'saved_ok':
|
||||
from .value_readback import capture_value_readback
|
||||
if capture_value_readback(root, row, outcome, project_commit=proof).get('value_readback_status') != 'verified':
|
||||
raise ValueError('saved target Value readback is incomplete')
|
||||
if any(Path(name).name != name or hashlib.sha256(_io_path(root / name).read_bytes()).hexdigest() != digest
|
||||
for name, digest in proof.get('readback_files', {}).items()):
|
||||
raise ValueError('native/readback files changed since project closure')
|
||||
if not commit.get('proof_json'):
|
||||
journal.bind_project_commit_proof(task_id, commit['session_token'], proof)
|
||||
commit['proof_json'] = json.dumps(proof)
|
||||
if (not set(journal.unresolved_jobs(task_id, rows)) <= covered
|
||||
or any(attempt not in covered_attempts for attempt in journal.project_commit_recovery_attempts(task_id))):
|
||||
raise ValueError('another native attempt is unresolved')
|
||||
# SQL/history may already have committed before a publication failure.
|
||||
self._commit_staged_project(task_id)
|
||||
for commit in commits:
|
||||
proof = json.loads(commit['proof_json'])
|
||||
if not validate_project_commit_source(proof, root):raise ValueError('saved source changed during recovery')
|
||||
handoff = QuickRunResult(root/'QuickPartReplace.vbs', root/'command.tsv', root/'status.tsv', root/'quick-part-replace.log', self.vbs_root_compatible)
|
||||
self._bind_journal_handoff(task_id, handoff)
|
||||
if protection is not None:
|
||||
if flag.read_bytes() != protection:raise ValueError('protection reason changed')
|
||||
write_record(audit, {'task_id': task_id, 'session_tokens': [commit['session_token'] for commit in commits],
|
||||
'native_replacement_called': False, 'original_protection_sha256': hashlib.sha256(protection).hexdigest()})
|
||||
flag.replace(root / 'project-commit-resolved-uncertain.flag')
|
||||
details = _read_status_details(root / 'status.tsv')
|
||||
projects = tuple(project for project in journal.store.list_projects(task_id) if project.selected and project.available)
|
||||
progress = _progress_from_queue(projects, _read_commands(root/'command.tsv'), details, _read_command_sheet_targets(root/'command.tsv'))
|
||||
return QuickRunStepResult(handoff.script_path, handoff.command_path, handoff.status_path, audit,
|
||||
'saved_ok', '完整工程保存回读证明已恢复原回执;未启动 CAD 或重复替换。', progress.next_project_path,
|
||||
progress.next_old_part_number, progress.next_new_part_number, progress.next_schematic_name, progress.next_sheet_number, progress)
|
||||
except (OSError, ValueError, KeyError, TypeError) as error:
|
||||
raise TaskCenterError('quick_run_uncertain', '工程提交证明、保存源或原尝试无法核验,保护记录保持。') from error
|
||||
|
||||
def complete_project_session(self, task_id, scope, session, projects):
|
||||
"""Close the retained owner before exposing saved progress to the queue."""
|
||||
from .operation_diagnostics import record_operation
|
||||
worker = scope.worker
|
||||
if worker is not None:
|
||||
record_operation(worker.root, 'save', 'enter', item_id=worker.token)
|
||||
try:
|
||||
scope.close()
|
||||
record_operation(worker.root, 'save', 'return', item_id=worker.token)
|
||||
except Exception as error:
|
||||
record_operation(worker.root, 'save', 'error', item_id=worker.token, error=str(error))
|
||||
_write_uncertain_flag(worker.root / 'uncertain.flag', 'project_commit_unverified')
|
||||
raise
|
||||
if session is not None:
|
||||
appended, offset, identity, stamp = _read_appended_status_details(session)
|
||||
session.statuses += appended
|
||||
session.status_offset, session.status_identity, session.status_stamp = offset, identity, stamp
|
||||
session.latest = {job: (state, code) for job, state, code, _ in session.statuses}
|
||||
session.next_index = _next_unfinished_index(session.commands, session.latest)
|
||||
session.progress = _progress_from_queue(tuple(project for project in projects if project.selected and project.available),
|
||||
session.commands, session.statuses, session.sheets)
|
||||
session.completed_project_keys = {_path_key(path) for path in session.progress.completed_project_paths}
|
||||
return session.progress
|
||||
|
||||
def write_expected_baselines(self, task_id, root, project_path):
|
||||
journal=getattr(self,'journal',None)
|
||||
if journal is None:return
|
||||
@@ -403,7 +592,8 @@ class QuickRunPreparer:
|
||||
from .worker_monitor import WorkerMonitorError
|
||||
try:
|
||||
with ProjectSessionScope(self._process_runner,
|
||||
enabled=enabled and self._process_runner is _run_process, private_desktop=True, runtime=runtime) as scope:
|
||||
enabled=enabled and self._process_runner is _run_process and getattr(self, 'journal', None) is not None,
|
||||
private_desktop=True, runtime=runtime) as scope:
|
||||
yield scope
|
||||
except (WorkerMonitorError, subprocess.TimeoutExpired) as error:
|
||||
_write_uncertain_flag(self._data_root / 'quick-run/uncertain.flag', 'project_session_cleanup')
|
||||
@@ -636,6 +826,38 @@ 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 == 75:
|
||||
try:
|
||||
proof = getattr(completed, 'prewrite_pause', {})
|
||||
pause_token = proof.get('session_token', '')
|
||||
marker = _io_path(handoff.command_path.parent / f'project-pause-{pause_token}.tsv')
|
||||
fields = marker.read_text(encoding='utf-8-sig').strip().split('\t')
|
||||
if (runtime is None or journal_attempt is None or project_session is None
|
||||
or project_session.worker is None or pause_token != project_session.worker.token
|
||||
or proof.get('phase') != 'before_native_dispatch'
|
||||
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 len(fields) != 4 or fields[0] != pause_token or fields[2:] != [row['job_id'], 'prewrite_closed']
|
||||
or _path_key(_decode_vbs_field(fields[1])) != _path_key(row['project_path'])
|
||||
or proof.get('request_sha256') != hashlib.sha256(
|
||||
_io_path(handoff.command_path.with_name('project-session.request')).read_bytes()).hexdigest()
|
||||
or proof.get('current_command_sha256') != hashlib.sha256(
|
||||
_io_path(handoff.command_path.with_name('current-command.tsv')).read_bytes()).hexdigest()
|
||||
or any(entry[0] == row['job_id'] and entry[1] in TERMINAL_STATES for entry in after)
|
||||
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('prewrite pause is not bound to the retained owner')
|
||||
self._commit_staged_project(task_id, session_token=pause_token)
|
||||
journal.pause_before_dispatch(journal_attempt, row, proof)
|
||||
journal.finalize_startup_pause(task_id, handoff.command_path.parent)
|
||||
_write_status_details(handoff.status_path, (*after,
|
||||
(row['job_id'], 'pending', 'prewrite_paused', '工程安全关闭;当前项确认未替换,保留待执行。')))
|
||||
except Exception as error:
|
||||
_write_uncertain_flag(uncertain_path, 'unproven_prewrite_pause')
|
||||
raise TaskCenterError('quick_run_uncertain', '暂停缺少完整的未写入与工程关闭证明;保留保护并核验。') from error
|
||||
_append_log(handoff.log_path, 'quick_run_paused prewrite_closed')
|
||||
raise TaskCenterError('operation_cancelled', '工程已安全关闭,已暂存前缀完成保存回读;当前项保留待执行。')
|
||||
if completed.returncode == 74:
|
||||
try:
|
||||
proof = getattr(completed, 'startup_pause', {})
|
||||
@@ -771,7 +993,8 @@ class QuickRunPreparer:
|
||||
_append_log(handoff.log_path, "quick_run_uncertain native_failure_after_snapshot")
|
||||
raise TaskCenterError("quick_run_uncertain", detail)
|
||||
raise TaskCenterError("quick_run_execution", detail)
|
||||
if state not in TERMINAL_STATES:
|
||||
if state not in TERMINAL_STATES and not (state == 'pending_save' and project_session is not None
|
||||
and project_session.enabled and code in {'session_staged', 'session_staged_no_match'}):
|
||||
raise TaskCenterError("quick_run_execution", f"unexpected quick-run state: {state}")
|
||||
if batch_mode and state == "saved_ok":
|
||||
try:
|
||||
@@ -804,6 +1027,22 @@ class QuickRunPreparer:
|
||||
progress = _progress_from_queue(tuple(project for project in projects if project.selected and project.available),
|
||||
commands, after, _read_command_sheet_targets(handoff.command_path))
|
||||
try:
|
||||
if state == 'pending_save':
|
||||
proof = self.result_proof(handoff.command_path.parent, row, (state, code, message))
|
||||
journal.stage_project_result(journal_attempt, row, session_token=project_session.worker.token,
|
||||
root=handoff.command_path.parent, proof=proof)
|
||||
project_session.on_commit = lambda worker: self._commit_staged_project(task_id, session_token=worker.token, bind_source=True)
|
||||
if (next_command is None or _path_key(next_command[2]) != _path_key(row['project_path'])
|
||||
or (stop_event is not None and stop_event.is_set())):
|
||||
progress = self.complete_project_session(task_id, project_session, batch_session, projects)
|
||||
state = 'no_match' if code == 'session_staged_no_match' else 'saved_ok'
|
||||
message = '工程统一保存、关闭重开及回读校验通过。'
|
||||
next_command = commands[batch_session.next_index] if batch_session is not None and batch_session.next_index < len(commands) else None
|
||||
next_sheet = batch_session.sheets.get(next_command[1], (None, None)) if batch_session is not None and next_command is not None and batch_session.sheets is not None else (None, None)
|
||||
return QuickRunStepResult(handoff.script_path, handoff.command_path, handoff.status_path, handoff.log_path,
|
||||
state, message, Path(next_command[2]) if next_command is not None else None,
|
||||
next_command[3] if next_command is not None else None, next_command[4] if next_command is not None else None,
|
||||
next_sheet[0], next_sheet[1], progress)
|
||||
verified_source_health = None
|
||||
if (state in {'saved_ok', 'restored_ok', 'no_match'} and self._process_runner is _run_process
|
||||
and journal.failure_health_references(task_id, row['project_path'])):
|
||||
@@ -1196,9 +1435,21 @@ def _advance_batch_session(
|
||||
current_index = session.next_index
|
||||
current = session.commands[current_index]
|
||||
job_id, state, code, _ = changed
|
||||
if job_id != current[1] or state not in TERMINAL_STATES:
|
||||
if job_id != current[1] or state not in TERMINAL_STATES | {'pending_save'}:
|
||||
raise TaskCenterError("quick_run_queue_progress", "batch result does not complete the expected queue item")
|
||||
session.latest[job_id] = (state, code)
|
||||
if state == 'pending_save':
|
||||
from dataclasses import replace
|
||||
next_index = current_index + 1
|
||||
while next_index < len(session.commands) and session.latest.get(session.commands[next_index][1], ('', ''))[0] in TERMINAL_STATES | {'pending_save'}:
|
||||
next_index += 1
|
||||
session.next_index = next_index
|
||||
next_command = session.commands[next_index] if next_index < len(session.commands) else None
|
||||
next_sheet = session.sheets.get(next_command[1], (None, None)) if session.sheets is not None and next_command is not None else (None, None)
|
||||
session.progress = replace(session.progress, next_project_path=Path(next_command[2]) if next_command else None,
|
||||
next_old_part_number=next_command[3] if next_command else None, next_new_part_number=next_command[4] if next_command else None,
|
||||
next_schematic_name=next_sheet[0], next_sheet_number=next_sheet[1], queue_complete=False)
|
||||
return
|
||||
current_key = session.project_keys_by_index[current_index]
|
||||
partial_failures = {
|
||||
_path_key(path): (path, summary)
|
||||
@@ -2074,10 +2325,12 @@ def _correlated_status_change(
|
||||
job_id = appended[0][0]
|
||||
prior_state = next((state for status_job_id, state, _, _ in reversed(before) if status_job_id == job_id), None)
|
||||
transitions = {
|
||||
None: {"awaiting_native_replace", "hard_failure", "batch_failed", "batch_saved_unverified", "no_match"},
|
||||
None: {"awaiting_native_replace", "hard_failure", "batch_failed", "batch_saved_unverified", "no_match", "pending_save"},
|
||||
"pending": {"awaiting_native_replace", "hard_failure", "batch_failed", "batch_saved_unverified", "no_match", "pending_save"},
|
||||
"awaiting_native_replace": {
|
||||
"restored_ok",
|
||||
"saved_ok",
|
||||
"pending_save",
|
||||
"hard_failure",
|
||||
"batch_failed",
|
||||
"batch_saved_unverified",
|
||||
|
||||
@@ -1117,8 +1117,9 @@ class TaskCenterService:
|
||||
summary='quick_run_result:failed | '+message)
|
||||
if task.status in {TaskStatus.DRAFT,TaskStatus.READY,TaskStatus.PAUSED}:
|
||||
self._store.set_task_status(task_id,TaskStatus.RUNNING,summary=summary)
|
||||
self._store.set_task_status(task_id,TaskStatus.FAILED,summary=summary)
|
||||
elif task.status is TaskStatus.RUNNING:
|
||||
self._store.set_task_status(task_id,TaskStatus.RUNNING,summary=summary)
|
||||
self._store.set_task_status(task_id,TaskStatus.FAILED,summary=summary)
|
||||
HistoryRepository(self._store).append(task_id=task_id,task_name=task.name,
|
||||
operation='工程执行收尾',state='failed',summary='本工程安全失败,剩余项暂缓;继续后续工程。',
|
||||
details={'reason':message})
|
||||
@@ -1147,7 +1148,15 @@ class TaskCenterService:
|
||||
child._quick_run_preparer.data_root, started_after)
|
||||
if getattr(self, '_supervisor_waiting', False):
|
||||
from dataclasses import replace
|
||||
value = replace(value, stage='awaiting_reconciliation', waiting_for_safe_completion=True)
|
||||
from .execution_feedback import wait_reason_for_stage
|
||||
state = getattr(self, '_supervisor_state', None) or {}
|
||||
wait_reason = state.get('wait_reason') or value.wait_reason or wait_reason_for_stage(value.stage)
|
||||
stopping_reason = state.get('stopping_reason') or value.stopping_reason
|
||||
if not stopping_reason and getattr(self, '_supervisor_business_stalled', False):
|
||||
stopping_reason = 'inactivity'
|
||||
value = replace(value, waiting_for_safe_completion=True,
|
||||
wait_reason=wait_reason, stopping_reason=stopping_reason,
|
||||
primary_error=state.get('primary_error') or value.primary_error)
|
||||
if read_control is not None:
|
||||
read_control.checkpoint()
|
||||
return value
|
||||
@@ -1175,6 +1184,35 @@ class TaskCenterService:
|
||||
return self._quick_run_preparer.has_interrupted(task_id)
|
||||
|
||||
def recover_quick_run(self, task_id: str, *, confirmed: bool = False, runtime=None, stop_event=None) -> QuickRunStepResult:
|
||||
if self._store.get_task(task_id).status is TaskStatus.DELETED:
|
||||
raise TaskCenterError("quick_run_recovery", "请先恢复已删除的任务记录,再核验其中断步骤。")
|
||||
from .project_isolation import dependency_block, recover_dependency
|
||||
dependency = dependency_block(self._logging.root, task_id)
|
||||
with self._store._lock:
|
||||
dispatched = self._store._connection.execute('''SELECT 1 FROM execution_operations
|
||||
WHERE task_id=? AND (attempt_id IS NOT NULL OR generation>0) LIMIT 1''', (task_id,)).fetchone()
|
||||
if dependency is not None and not (dependency['state'] in {'readmission_prepared', 'readmitted'} and dispatched):
|
||||
if stop_event is not None and stop_event.is_set():
|
||||
raise TaskCenterError('operation_cancelled', '共享数据源依赖核验已取消。')
|
||||
from .task_queue import assert_task_queue_idle
|
||||
assert_task_queue_idle(self._logging.root)
|
||||
with _quick_run_lease(self._logging.root):
|
||||
return self._operation('recover_quick_run', task_id,
|
||||
lambda: recover_dependency(self, task_id, confirmed=confirmed))
|
||||
commit_recovery = getattr(self._project_task_service(task_id)._quick_run_preparer, 'recover_project_commit', None)
|
||||
if commit_recovery is not None:
|
||||
from .batch_resources import guard_pending_resources
|
||||
from .task_queue import assert_task_queue_idle
|
||||
assert_task_queue_idle(self._logging.root)
|
||||
with _quick_run_lease(self._logging.root):
|
||||
guard_pending_resources(self._logging.root)
|
||||
result = self._operation('recover_project_commit', task_id,
|
||||
lambda: commit_recovery(task_id, confirmed=confirmed))
|
||||
if result is not None:
|
||||
if self._store.get_task(task_id).status in {TaskStatus.BLOCKED, TaskStatus.FAILED, TaskStatus.PAUSED}:
|
||||
self._store.set_task_status(task_id, TaskStatus.READY, summary='原工程提交已通过持久化保存回读证据核验。')
|
||||
self._synchronize_quick_run_progress(task_id)
|
||||
return result
|
||||
if runtime is None and self._supervised:
|
||||
return self._supervise('recover_quick_run', {'task_id': task_id, 'confirmed': confirmed}, stop_event=stop_event)
|
||||
if runtime is None:
|
||||
@@ -1221,7 +1259,7 @@ class TaskCenterService:
|
||||
self._quick_run_preparer._bind_journal_handoff(task_id,
|
||||
QuickRunResult(result.script_path, result.command_path, result.status_path,
|
||||
handoff_root/'quick-part-replace.log', True))
|
||||
if task.status in {TaskStatus.PAUSED, TaskStatus.FAILED}:
|
||||
if task.status in {TaskStatus.PAUSED, TaskStatus.FAILED, TaskStatus.BLOCKED}:
|
||||
self._store.set_task_status(task_id, TaskStatus.READY, summary="interrupted quick-run reconciled")
|
||||
from .recovery_commit import marker_path
|
||||
marker_path(self._quick_run_preparer).unlink(missing_ok=True)
|
||||
@@ -1409,8 +1447,8 @@ class TaskCenterService:
|
||||
rules,
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
)
|
||||
if self._supervised:
|
||||
return progress # Only the batch process persists live execution state.
|
||||
if self._supervised or task.status is TaskStatus.BLOCKED:
|
||||
return progress # BLOCKED classification changes only through explicit reconciliation.
|
||||
by_path = {_path_key(project.path): project.project_id for project in projects}
|
||||
project_by_id = {project.project_id: project for project in projects}
|
||||
summary_by_id = {
|
||||
@@ -1457,7 +1495,7 @@ class TaskCenterService:
|
||||
) or (
|
||||
progress.queue_complete
|
||||
and (
|
||||
(bool(failed_project_ids) and (task.status is not TaskStatus.RUNNING or task.summary != retry_summary))
|
||||
(bool(failed_project_ids) and (task.status is not TaskStatus.FAILED or task.summary != retry_summary))
|
||||
or (not failed_project_ids and task.status is not TaskStatus.COMPLETED)
|
||||
)
|
||||
)
|
||||
|
||||
@@ -80,7 +80,7 @@ def read_target_plan(store, task_id: str, path: Path) -> tuple[TargetPlanRow, ..
|
||||
raise ValueError("invalid or formula plan row")
|
||||
identity = tuple("" if value is None else str(value) for value in values[:8])
|
||||
key = (str(Path(identity[0]).resolve(strict=False)).casefold(),
|
||||
identity[2], identity[3], identity[4])
|
||||
identity[2], identity[3], identity[5].strip().casefold())
|
||||
original = expected.get(key)
|
||||
if original is None or key in by_key:
|
||||
raise ValueError("forged or duplicate target")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Separate ordinary stop intent from an explicitly confirmed forced interruption."""
|
||||
from threading import Event
|
||||
import time
|
||||
import json
|
||||
import os
|
||||
|
||||
@@ -23,6 +24,13 @@ class StopControl(Event):
|
||||
self.resolution_error = ''
|
||||
self.cleanup_mode = None
|
||||
self.cleanup_reason = ''
|
||||
self.stopping_reason = ''
|
||||
self.wait_reason = ''
|
||||
self.primary_error = ''
|
||||
|
||||
def set(self):
|
||||
self.stopping_reason = self.stopping_reason or 'user_pause'
|
||||
super().set()
|
||||
|
||||
def request_force(self):
|
||||
self.set()
|
||||
@@ -33,10 +41,64 @@ class StopControl(Event):
|
||||
protect_interruption(root, MENTOR_RELEASE_REQUIRED + ': ' + str(error))
|
||||
self.cleanup_mode = MENTOR_RELEASE_REQUIRED
|
||||
self.cleanup_reason = self.cleanup_reason or str(error)
|
||||
self.primary_error = self.primary_error or str(error)
|
||||
self.stopping_reason = 'failure_cleanup'
|
||||
self.set()
|
||||
self.force_event.set()
|
||||
|
||||
|
||||
class _ProjectForce:
|
||||
def __init__(self, parent):
|
||||
self.local = Event()
|
||||
self.parent = getattr(parent, 'force_event', None)
|
||||
|
||||
def is_set(self):
|
||||
return self.local.is_set() or self.parent is not None and self.parent.is_set()
|
||||
|
||||
def set(self):
|
||||
self.local.set()
|
||||
|
||||
def clear(self):
|
||||
self.local.clear()
|
||||
if self.parent is not None:
|
||||
self.parent.clear()
|
||||
|
||||
def wait(self, timeout=None):
|
||||
deadline = None if timeout is None else time.monotonic() + timeout
|
||||
while not self.is_set():
|
||||
remaining = .1 if deadline is None else min(.1, deadline - time.monotonic())
|
||||
if remaining <= 0:
|
||||
return False
|
||||
self.local.wait(remaining)
|
||||
return True
|
||||
|
||||
|
||||
class ProjectStopControl(StopControl):
|
||||
"""An engineering failure stops its owner; user pause still stops the batch."""
|
||||
def __init__(self, parent):
|
||||
super().__init__()
|
||||
self.parent = parent
|
||||
self.force_event = _ProjectForce(parent)
|
||||
|
||||
def is_set(self):
|
||||
return self.parent.is_set() or super().is_set()
|
||||
|
||||
def set(self):
|
||||
if self.stopping_reason in {'failure_cleanup','inactivity'}:
|
||||
Event.set(self)
|
||||
else:
|
||||
self.parent.set()
|
||||
|
||||
def request_failure_cleanup(self, root, error):
|
||||
protect_interruption(root, MENTOR_RELEASE_REQUIRED + ': ' + str(error))
|
||||
self.stopping_reason = 'failure_cleanup'
|
||||
self.cleanup_mode = MENTOR_RELEASE_REQUIRED
|
||||
self.cleanup_reason = self.cleanup_reason or str(error)
|
||||
self.primary_error = self.primary_error or str(error)
|
||||
Event.set(self)
|
||||
self.force_event.set()
|
||||
|
||||
|
||||
def protect_interruption(root, reason):
|
||||
"""Create or re-sync a marker without overwriting prior protection evidence."""
|
||||
root = internal_path(root)
|
||||
@@ -69,9 +131,12 @@ def wait_for_resolution(control, root, error, *, resolved=None, release_on_failu
|
||||
return
|
||||
from .worker_monitor import WorkerMonitorError, _publish_progress
|
||||
root = internal_path(root)
|
||||
control.stopping_reason = 'failure_cleanup' if release_on_failure else (control.stopping_reason or 'inactivity')
|
||||
control.wait_reason = 'reconciliation'
|
||||
control.primary_error = control.primary_error or str(error)
|
||||
control.set()
|
||||
control.waiting_for_resolution = True
|
||||
control.resolution_error = str(error)
|
||||
control.resolution_error = control.resolution_error or str(error)
|
||||
def protect():
|
||||
protect_interruption(root, 'operation_interrupted: ' + str(error))
|
||||
try:
|
||||
@@ -91,7 +156,9 @@ def wait_for_resolution(control, root, error, *, resolved=None, release_on_failu
|
||||
record = {}
|
||||
record.update(stage='awaiting_reconciliation', waiting_for_safe_completion=True,
|
||||
resolution_error=str(error), stop_requested=True, safe_stop=False,
|
||||
cleanup_mode=control.cleanup_mode)
|
||||
cleanup_mode=control.cleanup_mode, stopping_reason=control.stopping_reason,
|
||||
wait_reason=control.wait_reason,
|
||||
primary_error=record.get('primary_error') or control.primary_error)
|
||||
_publish_progress(root / 'worker-progress.json', record)
|
||||
while True:
|
||||
if resolved is not None and resolved():
|
||||
|
||||
@@ -40,7 +40,7 @@ _TASK_TRANSITIONS = {
|
||||
TaskStatus.RUNNING: {TaskStatus.PAUSED, TaskStatus.COMPLETED, TaskStatus.FAILED},
|
||||
TaskStatus.PAUSED: {TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.FAILED, TaskStatus.DELETED},
|
||||
TaskStatus.COMPLETED: {TaskStatus.DELETED},
|
||||
TaskStatus.FAILED: {TaskStatus.PAUSED, TaskStatus.READY, TaskStatus.DELETED},
|
||||
TaskStatus.FAILED: {TaskStatus.PAUSED, TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.DELETED},
|
||||
TaskStatus.DELETED: {
|
||||
TaskStatus.DRAFT,
|
||||
TaskStatus.READY,
|
||||
@@ -49,6 +49,13 @@ _TASK_TRANSITIONS = {
|
||||
TaskStatus.FAILED,
|
||||
},
|
||||
}
|
||||
for _state in (TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.PAUSED, TaskStatus.FAILED):
|
||||
_TASK_TRANSITIONS[_state].add(TaskStatus.BLOCKED)
|
||||
_TASK_TRANSITIONS[TaskStatus.DRAFT].update({TaskStatus.PAUSED, TaskStatus.FAILED})
|
||||
_TASK_TRANSITIONS[TaskStatus.READY].add(TaskStatus.PAUSED)
|
||||
_TASK_TRANSITIONS[TaskStatus.FAILED].add(TaskStatus.FAILED)
|
||||
_TASK_TRANSITIONS[TaskStatus.BLOCKED] = {TaskStatus.BLOCKED, TaskStatus.PAUSED, TaskStatus.READY, TaskStatus.DELETED}
|
||||
_TASK_TRANSITIONS[TaskStatus.DELETED].add(TaskStatus.BLOCKED)
|
||||
_PROJECT_TRANSITIONS = {
|
||||
ProjectStatus.PENDING: {ProjectStatus.CAPTURING_BEFORE, ProjectStatus.FAILED, ProjectStatus.SKIPPED},
|
||||
ProjectStatus.CAPTURING_BEFORE: {ProjectStatus.AWAITING_OPERATOR, ProjectStatus.FAILED},
|
||||
@@ -467,7 +474,8 @@ class TaskStore:
|
||||
"""Persist current-sheet quick-run progress independently of manual attempts."""
|
||||
with self.transaction():
|
||||
task = self.get_task(task_id)
|
||||
allowed_task_states = {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.PAUSED, TaskStatus.COMPLETED}
|
||||
allowed_task_states = {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.PAUSED,
|
||||
TaskStatus.COMPLETED, TaskStatus.FAILED}
|
||||
if task.status not in allowed_task_states:
|
||||
raise TaskCenterError("quick_run_task_state", "task state does not allow quick-run progress")
|
||||
for project_id in completed_project_ids:
|
||||
@@ -512,7 +520,7 @@ class TaskStore:
|
||||
"quick-run queue completed before project states were synchronized",
|
||||
)
|
||||
has_failures = any(project.status is ProjectStatus.FAILED for project in selected)
|
||||
if task.status in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.PAUSED}:
|
||||
if task.status in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.PAUSED, TaskStatus.FAILED}:
|
||||
task = self.set_task_status(
|
||||
task_id,
|
||||
TaskStatus.RUNNING,
|
||||
@@ -520,10 +528,10 @@ class TaskStore:
|
||||
if has_failures else "current-sheet quick-run queue completed",
|
||||
)
|
||||
if has_failures:
|
||||
if task.status is TaskStatus.RUNNING and task.summary != "current-sheet quick-run queue completed with retryable failures":
|
||||
if task.status is TaskStatus.RUNNING:
|
||||
task = self.set_task_status(
|
||||
task_id,
|
||||
TaskStatus.RUNNING,
|
||||
TaskStatus.FAILED,
|
||||
summary="current-sheet quick-run queue completed with retryable failures",
|
||||
)
|
||||
else:
|
||||
|
||||
@@ -20,7 +20,8 @@ class ProjectIdentityResolver:
|
||||
return self._projects[spelling]
|
||||
|
||||
def target(self, target):
|
||||
return (self.project(target.project_path), target.schematic_name, target.sheet_number, target.uid)
|
||||
return (self.project(target.project_path), target.schematic_name, target.sheet_number,
|
||||
target.refdes.strip().casefold())
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -36,6 +37,8 @@ class ComponentTarget:
|
||||
actual_cell: str | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.uid and self.refdes:
|
||||
object.__setattr__(self, 'uid', '@REFDES|' + self.refdes.strip())
|
||||
if any(value is not None and not isinstance(value, str)
|
||||
for value in (self.actual_part_label, self.actual_cell)):
|
||||
raise TaskCenterError('target_inventory', 'effective Part Label and Cell must be text or unknown')
|
||||
@@ -118,7 +121,7 @@ def compile_target_rules(rows: tuple[TargetPlanRow, ...], *, default_value_mode:
|
||||
raise TaskCenterError("target_identity", "component identity is incomplete")
|
||||
target_key = identities.target(target)
|
||||
if target_key in seen:
|
||||
raise TaskCenterError("target_overlap", "target UID appears more than once")
|
||||
raise TaskCenterError("target_overlap", "target reference appears more than once")
|
||||
seen.add(target_key)
|
||||
if not row.enabled:
|
||||
continue
|
||||
|
||||
@@ -23,7 +23,8 @@ def archive_completed_session(service):
|
||||
|
||||
def _archive(service):
|
||||
store = service._store
|
||||
pending = service.pending_batch_resources()
|
||||
from .batch_resources import resource_blockers
|
||||
pending = resource_blockers(service.pending_batch_resources())
|
||||
owned = set()
|
||||
unknown = False
|
||||
for record in pending:
|
||||
@@ -39,7 +40,7 @@ def _archive(service):
|
||||
reason = None
|
||||
if unknown or task.task_id in owned:
|
||||
reason = '后台资源尚未确认释放;重新打开后使用“重新清理资源”。'
|
||||
elif task.status is TaskStatus.RUNNING:
|
||||
elif task.status in {TaskStatus.RUNNING, TaskStatus.BLOCKED}:
|
||||
reason = '任务仍在执行状态;重新打开后暂停或核验恢复。'
|
||||
elif any(project.status in {ProjectStatus.CAPTURING_BEFORE, ProjectStatus.AWAITING_OPERATOR,
|
||||
ProjectStatus.CAPTURING_AFTER, ProjectStatus.VERIFYING}
|
||||
|
||||
@@ -12,6 +12,8 @@ from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .quick_run import _write_atomic_queue_text
|
||||
from .project_isolation import (write_sources, record_task_outcome, isolate_project,
|
||||
block_dependency, dependency_block, dependency_readmitted)
|
||||
|
||||
|
||||
_QUEUE_LOCK = Lock()
|
||||
@@ -212,12 +214,14 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
with _queue_lease(root):
|
||||
children = {task_id: service.for_project_task(task_id) for task_id in ids}
|
||||
project_paths = []
|
||||
sources = {}
|
||||
for task_id, child in children.items():
|
||||
task = child.get_task(task_id)
|
||||
projects = child.projects(task_id)
|
||||
if not getattr(task, 'primary_project_id', None) or len(projects) != 1:
|
||||
raise TaskCenterError('project_binding', '顺序执行仅支持绑定单个工程的任务。')
|
||||
project_paths.append(str(projects[0].path.resolve(strict=False)).casefold())
|
||||
sources[task_id] = write_sources(projects[0].path)
|
||||
if len(set(project_paths)) != len(ids):
|
||||
raise TaskCenterError('task_queue_selection', '不能在同一队列重复处理同一个工程。')
|
||||
runtime.bind_logs(service._logging, ids)
|
||||
@@ -251,10 +255,38 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
_save(path, state)
|
||||
paused = False
|
||||
current = None
|
||||
from .stop_control import ProjectStopControl
|
||||
parent_control = getattr(runtime, 'stop_event', None)
|
||||
isolated_tasks = state.setdefault('isolated_tasks', {})
|
||||
isolated_sources = state.setdefault('isolated_sources', {})
|
||||
dependency_tasks = state.setdefault('dependency_tasks', {})
|
||||
from .netlist_verification import NetlistVerification
|
||||
checks = NetlistVerification(root, token, stop_event)
|
||||
try:
|
||||
for task_id in ids:
|
||||
readmitted = False
|
||||
if task_id in dependency_tasks:
|
||||
try:
|
||||
readmitted = dependency_readmitted(children[task_id], task_id, hashes[task_id])
|
||||
except TaskCenterError:
|
||||
pass
|
||||
if readmitted:
|
||||
isolated_tasks.pop(task_id, None)
|
||||
dependency_tasks.pop(task_id)
|
||||
state['entries'][task_id] = {'state': 'pending', 'message': '共享依赖已核验,恢复未派发原计划。'}
|
||||
if task_id in isolated_tasks:
|
||||
continue
|
||||
conflict = next((isolated_sources[source] for source in sources[task_id]
|
||||
if source in isolated_sources), None)
|
||||
if conflict is not None and not readmitted and state['entries'][task_id]['state'] not in _TERMINAL:
|
||||
message = f'与待核验工程 {conflict} 共享写入源,已隔离;未派发替换。'
|
||||
state['entries'][task_id] = {'state': 'blocked', 'message': message}
|
||||
isolated_tasks[task_id] = message
|
||||
dependency_tasks[task_id] = conflict
|
||||
block_dependency(root, children[task_id], task_id, conflict,
|
||||
sources[task_id] & sources[conflict], hashes[task_id], token)
|
||||
_save(path, state)
|
||||
continue
|
||||
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)
|
||||
@@ -264,6 +296,10 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
break
|
||||
current = task_id
|
||||
child = children[task_id]
|
||||
project_control = ProjectStopControl(stop_event)
|
||||
runtime.stop_event = project_control
|
||||
if getattr(runtime, 'cad', None) is not None:
|
||||
runtime.cad.stop_control = project_control
|
||||
service._task_queue_feedback = (token, task_id, ids.index(task_id) + 1, len(ids))
|
||||
resolving_bom = False
|
||||
execution_dispatched = False
|
||||
@@ -277,7 +313,7 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
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)
|
||||
resolved = child.resolve_pending_bom(task_id, stop_event=project_control)
|
||||
resolving_bom = False
|
||||
if not any(row.enabled for row in resolved):
|
||||
state['entries'][task_id] = {'state': 'skipped',
|
||||
@@ -304,7 +340,7 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
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,
|
||||
result = execute(task_id, expected_item=expected, stop_event=project_control,
|
||||
**runtime_options)
|
||||
if child.has_interrupted_quick_run(task_id) or (
|
||||
result.last_result is not None and result.last_result.state == 'batch_saved_unverified'
|
||||
@@ -340,10 +376,31 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
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
|
||||
if not safe and error.code != 'operation_cancelled' and not stop_event.is_set():
|
||||
try:
|
||||
isolated = isolate_project(runtime, child, task_id, error)
|
||||
except Exception as cleanup_error:
|
||||
entry['message'] += '; 资源收尾未确认:' + str(cleanup_error)
|
||||
isolated = False
|
||||
if isolated:
|
||||
isolated_tasks[task_id] = entry['message']
|
||||
isolated_sources.update((source,task_id) for source in sources[task_id])
|
||||
paused = False
|
||||
except Exception as error:
|
||||
entry = {'state': 'blocked', 'message': str(error)}
|
||||
paused = True
|
||||
if not stop_event.is_set():
|
||||
try:
|
||||
isolated = isolate_project(runtime, child, task_id, error)
|
||||
except Exception as cleanup_error:
|
||||
entry['message'] += '; 资源收尾未确认:' + str(cleanup_error)
|
||||
isolated = False
|
||||
if isolated:
|
||||
isolated_tasks[task_id] = entry['message']
|
||||
isolated_sources.update((source,task_id) for source in sources[task_id])
|
||||
paused = False
|
||||
state['entries'][task_id] = entry
|
||||
record_task_outcome(child, task_id, entry['state'], entry['message'])
|
||||
_save(path, state)
|
||||
if (entry['state'] in {'completed', 'failed'} and task_id in checks.tasks
|
||||
and not child.has_interrupted_quick_run(task_id)):
|
||||
@@ -369,7 +426,8 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
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,
|
||||
admitted_problem_tasks = tuple(item for item in ids if item not in isolated_tasks)
|
||||
retried = run_problem_pass(service, admitted_problem_tasks, 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',
|
||||
@@ -416,3 +474,6 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
checks.__exit__(None, None, None)
|
||||
finally:
|
||||
service._task_queue_feedback = None
|
||||
runtime.stop_event = parent_control
|
||||
if getattr(runtime, 'cad', None) is not None:
|
||||
runtime.cad.stop_control = parent_control
|
||||
@@ -9,12 +9,13 @@ STAGES = {
|
||||
'snapshot_attributes': '记录原始属性', 'capture': '采集替换前快照',
|
||||
'capture_untouched': '记录未选中器件状态', 'verify_untouched': '核验未选中器件',
|
||||
'native_snapshot_read': '采集并核验器件完整状态',
|
||||
'capture_semantic_state': '采集完整图页状态',
|
||||
'before_native': '准备原生替换', 'native_replace': '执行原生替换',
|
||||
'restore_preflight': '检查属性恢复条件',
|
||||
'before_restore_transaction': '准备恢复属性',
|
||||
'restore_attribute_fields': '恢复属性字段', 'restore_attributes': '恢复属性',
|
||||
'verify_restoration': '核验恢复结果', 'verify_attribute_fields': '核验属性字段',
|
||||
'save_and_close': '保存并关闭工程', 'verify_saved_project': '回读已保存工程',
|
||||
'save_and_close': '保存并关闭工程', 'verify_saved_project': '回读工程并核对',
|
||||
'awaiting_reconciliation': '当前结果待核验,已保留工程现场',
|
||||
}
|
||||
|
||||
@@ -22,7 +23,20 @@ STAGES = {
|
||||
def format_feedback(value, task_name, elapsed, stopping):
|
||||
stage = STAGES.get(value.stage, '')
|
||||
details = f'{stage}({value.stage_seconds:.1f} 秒)' if stage else value.message
|
||||
prefix = '等待当前步骤保存核验后暂停 · ' if stopping else ''
|
||||
reason = getattr(value, 'stopping_reason', '')
|
||||
wait = getattr(value, 'wait_reason', '')
|
||||
prefix = ({'user_pause': '已请求暂停,等待当前步骤完成',
|
||||
'failure_cleanup': '执行失败,正在回收资源',
|
||||
'inactivity': '当前步骤长时间无进展'}
|
||||
.get(reason, '已请求暂停,等待当前步骤完成' if stopping else ''))
|
||||
waits = {'native_call': '等待原生调用返回', 'save': '等待工程保存完成',
|
||||
'readback': '等待工程重读核对', 'mentor_exit': '等待 Mentor 写进程退出',
|
||||
'desktop_release': '等待后台桌面释放', 'reconciliation': '等待结果核对'}
|
||||
if wait and (stopping or value.waiting_for_safe_completion):
|
||||
prefix = ','.join(filter(None, (prefix, waits.get(wait, ''))))
|
||||
if value.waiting_for_safe_completion:
|
||||
prefix = '当前保存或核验尚未确认,未自动结束应用;可继续等待、导出诊断,或确认强制结束后核验 · '
|
||||
prefix += ';最终结果尚未确认,可继续等待、导出诊断,或确认强制结束后核对'
|
||||
if getattr(value, 'primary_error', ''):
|
||||
details += ';原始错误:' + value.primary_error
|
||||
prefix = prefix + ' · ' if prefix else ''
|
||||
return f'{prefix}任务 {value.position}/{value.total}:{task_name} · {details} · 总计 {elapsed} 秒'
|
||||
@@ -3,12 +3,20 @@ from dataclasses import dataclass
|
||||
from ..models import TaskStatus
|
||||
|
||||
|
||||
def task_display_status(task):
|
||||
"""Legacy retryable failures retain running admission, but are not active work."""
|
||||
if (task.status is TaskStatus.RUNNING
|
||||
and task.summary == 'current-sheet quick-run queue completed with retryable failures'):
|
||||
return TaskStatus.FAILED
|
||||
return task.status
|
||||
|
||||
|
||||
def pending_batch_tasks(tasks, group_id):
|
||||
"""Use the persisted batch order for both execution and its UI controls."""
|
||||
if not group_id:
|
||||
return ()
|
||||
return tuple(sorted((task for task in tasks if task.group_id == group_id
|
||||
and task.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED}
|
||||
and task.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED, TaskStatus.BLOCKED}
|
||||
and getattr(task, 'summary', '') != 'current-sheet quick-run queue completed with retryable failures'),
|
||||
key=lambda task: task.group_position))
|
||||
|
||||
@@ -34,7 +42,8 @@ def execution_state(context, *, busy=False, dirty=False):
|
||||
if not project or task.status is TaskStatus.DELETED:
|
||||
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
|
||||
retry = (context.phase == 'retry' and task.status is not TaskStatus.BLOCKED
|
||||
and not context.interrupted and not busy and not dirty)
|
||||
requests = getattr(context, 'pending_bom', ())
|
||||
deferred = bool(requests)
|
||||
from ..bom_pending import retained_bom_rows
|
||||
@@ -44,7 +53,7 @@ def execution_state(context, *, busy=False, dirty=False):
|
||||
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 deferred else '继续当前任务' if task.status is TaskStatus.PAUSED else '执行当前任务'
|
||||
message = ('结果待核验,请先恢复中断步骤。' if context.interrupted else
|
||||
message = ('结果待核验,请先恢复中断步骤。' if context.interrupted or task.status is TaskStatus.BLOCKED else
|
||||
'位号计划有未保存编辑,请先保存。' if dirty else
|
||||
'正在处理当前步骤,暂停会等待安全收尾。' if busy else
|
||||
'任务已完成。可查看原计划和日志;点击“开始新一轮”归档本批已完成任务,再采集当前料号。' if task.status is TaskStatus.COMPLETED else
|
||||
@@ -54,5 +63,6 @@ def execution_state(context, *, busy=False, dirty=False):
|
||||
'BOM 表格已保存;确认后仅核验当前工程位号,再执行替换。' if deferred else
|
||||
'先填写旧、新料号,再采集并勾选位号。' if not pending else
|
||||
'配置就绪,可执行当前任务或按顺序执行本批任务。')
|
||||
return ExecutionState(editable, execute, retry, context.interrupted and not busy and not dirty, text, message,
|
||||
return ExecutionState(editable, execute, retry,
|
||||
(context.interrupted or task.status is TaskStatus.BLOCKED) and not busy and not dirty, text, message,
|
||||
task.status is TaskStatus.COMPLETED and not context.interrupted and not busy and not dirty)
|
||||
@@ -423,9 +423,10 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
def _refresh_task_list(self):
|
||||
deleted = self.task_list.recycle_button.isChecked()
|
||||
def received(tasks):
|
||||
self._known_task_groups.update((task.task_id, task.group_id) for task in tasks)
|
||||
self._tasks = tasks
|
||||
self.task_list.populate(tasks, selected_task_id=self._task_id)
|
||||
if tasks != self._tasks or not self.task_list.count.text():
|
||||
self._known_task_groups.update((task.task_id, task.group_id) for task in tasks)
|
||||
self._tasks = tasks
|
||||
self.task_list.populate(tasks, selected_task_id=self._task_id)
|
||||
self._update_gates()
|
||||
self._task_query.request(lambda control: self.service.tasks(status=TaskStatus.DELETED, read_control=control)
|
||||
if deleted else self.service.tasks(read_control=control), received, self._show_error, cancellable=True)
|
||||
@@ -529,7 +530,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
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))
|
||||
self.run_panel.recover_button.setVisible(bool(context and context.interrupted))
|
||||
self.run_panel.recover_button.setVisible(bool(context and (context.interrupted or context.task.status is TaskStatus.BLOCKED)))
|
||||
self.run_panel.recover_button.setEnabled(state.recover and not resources_pending)
|
||||
self.run_panel.new_round_button.setVisible(bool(context and context.task.status is TaskStatus.COMPLETED))
|
||||
self.run_panel.new_round_button.setEnabled(state.new_round and not group_unsaved)
|
||||
@@ -597,7 +598,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self.run_panel.execution_status.setText('正在检查后台资源' if not self._resource_status.known else
|
||||
'资源状态读取失败' if self._resource_status.error is not None else
|
||||
'资源待清理' if resources_pending else '任务读取失败' if read_failed else
|
||||
'结果待核验' if context and context.interrupted else '空闲')
|
||||
'结果待核验' if context and (context.interrupted or context.task.status is TaskStatus.BLOCKED) else
|
||||
'旧桌面已隔离,可继续执行' if self._resource_status.records else '空闲')
|
||||
|
||||
def _group_has_unsaved_plans(self):
|
||||
if not self._context:
|
||||
@@ -1037,16 +1039,22 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
cleanup_finished = True
|
||||
start_force_if_ready()
|
||||
def forced(remaining):
|
||||
from ..batch_resources import resource_blockers
|
||||
self._resource_status.refresh()
|
||||
self._set_operator_message('仍有资源未能确认释放,请保留诊断。' if remaining else
|
||||
self._set_operator_message('仍有资源未能确认释放,请保留诊断。' if resource_blockers(remaining) else
|
||||
'自有写入进程已退出,残留桌面已隔离(未确认释放);相关工程仍须核验。' if remaining else
|
||||
'自有残留资源已释放;相关工程仍须核验后恢复。', 'warning')
|
||||
self._update_gates()
|
||||
def done(pending):
|
||||
nonlocal force_confirmed
|
||||
from ..batch_resources import resource_blockers
|
||||
warnings = tuple(row for row in pending if row.get('blocking') is False)
|
||||
pending = resource_blockers(pending)
|
||||
hints = tuple(dict.fromkeys(row['resolution_hint'] for row in pending if row.get('resolution_hint')))
|
||||
self._set_operator_message(
|
||||
'\n'.join(hints) if hints else '后台资源仍待清理,请保留诊断记录后重试。' if pending else '后台资源已释放,可以继续。',
|
||||
'warning' if pending else 'success')
|
||||
'\n'.join(hints) if hints else '后台资源仍待清理,请保留诊断记录后重试。' if pending else
|
||||
'旧桌面仍存在,已隔离;自有写进程已退出,可以继续执行。' if warnings else '后台资源已释放,可以继续。',
|
||||
'warning' if pending or warnings else 'success')
|
||||
if pending:
|
||||
self._dsh_blockers.report('resource-release', '', 'batch_resources_pending',
|
||||
'后台资源清理完成后仍有资源未确认释放。', {'resources': list(pending)[:20]}, cleanup_allowed=True)
|
||||
@@ -1187,7 +1195,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
if not self.run_panel.recover_button.isEnabled():
|
||||
return
|
||||
if QMessageBox.question(self, '核验并恢复',
|
||||
'先备份工程和证据,再打开工程核验;如需补齐属性,会保存并重开回读,不会重复调用原生替换。请确保待处理工程未在其他 CAD 会话中打开。',
|
||||
'共享数据源依赖导致隔离、且从未派发的任务,将核验依赖与原计划后解除隔离,不打开 CAD。其他中断任务先备份工程和证据,再打开核验;如需补齐属性,会保存并重开回读,不会重复调用原生替换。请确保待处理工程未在其他 CAD 会话中打开。',
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes:
|
||||
return
|
||||
@@ -1223,6 +1231,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
|
||||
def _update_quick_run_elapsed(self):
|
||||
self._update_gates()
|
||||
if self._batch_stop is not None and not self._task_query.busy:
|
||||
self._refresh_task_list()
|
||||
if self._batch_stop is not None and not self._feedback_query.busy:
|
||||
task_id, started = self._active_quick_run_task_id, self._run_started_at
|
||||
run_id = self._dsh_run_id
|
||||
@@ -1459,6 +1469,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
# If it fails, release the execution controls just as
|
||||
# the service failure path does.
|
||||
self._finish_run()
|
||||
self._refresh_task_list()
|
||||
self.operation_state = self.operation_state.finish(error)
|
||||
self._show_error(error, owner_task_id=owner, operation_area=operation_area)
|
||||
def failed(error):
|
||||
@@ -1470,6 +1481,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
if self._close_saving or not (isinstance(error, TaskCenterError) and error.code == 'operation_cancelled'):
|
||||
self._close_pending = False
|
||||
self._finish_run()
|
||||
if execution:
|
||||
self._refresh_task_list()
|
||||
if isinstance(error, TaskCenterError) and error.code == 'operation_cancelled':
|
||||
self._set_operator_message(self.operation_state.message)
|
||||
return
|
||||
|
||||
@@ -29,7 +29,8 @@ class ResourceStatus(QObject):
|
||||
|
||||
@property
|
||||
def blocked(self):
|
||||
return not self.known or self.error is not None or bool(self.records)
|
||||
from ..batch_resources import resource_blockers
|
||||
return not self.known or self.error is not None or bool(resource_blockers(self.records))
|
||||
|
||||
def refresh(self):
|
||||
if self._closed:
|
||||
|
||||
@@ -12,6 +12,7 @@ from PySide6.QtWidgets import (QAbstractItemView,QComboBox,QHBoxLayout,QLabel,QL
|
||||
QListWidgetItem,QPushButton,QVBoxLayout,QWidget,QToolButton,QMenu,
|
||||
QStyledItemDelegate,QStyleOptionViewItem,QStyle,QApplication)
|
||||
from .command_menu import CommandMenu
|
||||
from .execution_state import task_display_status
|
||||
|
||||
|
||||
class TaskItemDelegate(QStyledItemDelegate):
|
||||
@@ -80,10 +81,13 @@ class TaskList(QWidget):
|
||||
self.count = QLabel(objectName='taskCount')
|
||||
self.filter = QComboBox(objectName="taskFilter")
|
||||
for label, key, picture in (('全部任务', 'all', 'grid'), ('未完成', 'unfinished', 'clock'),
|
||||
('已完成', 'completed', 'check-circle'), ('失败', 'failed', 'warning')):
|
||||
('待开始', 'pending', 'clock'), ('执行中', 'running', 'clock'),
|
||||
('已暂停', 'paused', 'clock'), ('已完成', 'completed', 'check-circle'),
|
||||
('待核验', 'blocked', 'warning'),
|
||||
('失败 / 待重试', 'failed', 'warning')):
|
||||
self.filter.addItem(icon(picture), label, key)
|
||||
self.filter.setAccessibleName('任务状态分类')
|
||||
self.filter.setToolTip('未完成包括待配置、待执行、执行中、已暂停和失败的任务;分类只筛选显示。')
|
||||
self.filter.setToolTip('待开始包括待配置和待执行;失败包括已收尾的待重试任务。未完成包括所有尚未完成的任务;分类只筛选显示。')
|
||||
self.list = QListWidget(objectName="taskList")
|
||||
self.list.setItemDelegate(TaskItemDelegate(self.list))
|
||||
self.list.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
|
||||
@@ -163,9 +167,17 @@ class TaskList(QWidget):
|
||||
return str(item.data(Qt.ItemDataRole.UserRole)) if item is not None else None
|
||||
|
||||
def populate(self, tasks: Iterable[object], *, selected_task_id: str | None = None) -> None:
|
||||
preserve_selection = selected_task_id in (None, self.current_task_id())
|
||||
selected_ids = {item.data(Qt.ItemDataRole.UserRole) for item in self.list.selectedItems()}
|
||||
self._selected_task_id = selected_task_id or self.current_task_id() or self._selected_task_id
|
||||
self._tasks = tuple(tasks)
|
||||
self._render()
|
||||
if preserve_selection:
|
||||
with QSignalBlocker(self.list):
|
||||
for row in range(self.list.count()):
|
||||
item = self.list.item(row)
|
||||
item.setSelected(item.data(Qt.ItemDataRole.UserRole) in selected_ids)
|
||||
self._update_selection_state()
|
||||
|
||||
def select_task(self, task_id: str) -> None:
|
||||
if task_id != self._selected_task_id:
|
||||
@@ -209,8 +221,9 @@ class TaskList(QWidget):
|
||||
category = self.filter.currentData()
|
||||
if not self.recycle_button.isChecked() and category != 'all':
|
||||
tasks = [task for task in tasks if
|
||||
(task.status.value not in {'completed', 'deleted'} if category == 'unfinished'
|
||||
else task.status.value == category)]
|
||||
(task_display_status(task).value not in {'completed', 'deleted'} if category == 'unfinished'
|
||||
else task_display_status(task).value in {'draft', 'ready'} if category == 'pending'
|
||||
else task_display_status(task).value == category)]
|
||||
mode = self.sort.currentData()
|
||||
if mode.startswith('name_'):
|
||||
tasks.sort(key=lambda task: tuple(int(part) if part.isdigit() else part
|
||||
@@ -230,9 +243,9 @@ class TaskList(QWidget):
|
||||
for task in tasks:
|
||||
group_id = getattr(task, "group_id", None)
|
||||
prefix = f"{getattr(task, 'group_position', 0) + 1:02d}. " if group_id else ""
|
||||
status = getattr(getattr(task, 'status', None), 'value', '')
|
||||
status = task_display_status(task).value
|
||||
labels = {'draft': '待配置', 'ready': '待执行', 'running': '执行中', 'paused': '已暂停',
|
||||
'completed': '已完成', 'failed': '失败', 'deleted': '已删除'}
|
||||
'completed': '已完成', 'failed': '失败', 'blocked': '待核验', 'deleted': '已删除'}
|
||||
item = QListWidgetItem(prefix + str(getattr(task, "name")) + f"\n{labels.get(status, status)}")
|
||||
item.setData(Qt.ItemDataRole.UserRole, str(getattr(task, "task_id")))
|
||||
item.setIcon(self._project_icon)
|
||||
|
||||
@@ -37,14 +37,28 @@ def _fields(line):
|
||||
return tuple(_decode_vbs_field(field) for field in line.split('\t'))
|
||||
|
||||
|
||||
def _validated(root, row, outcome):
|
||||
def _validated(root, row, outcome, *, project_commit=None):
|
||||
raw, _, snapshot_path = _paths(root, row)
|
||||
state, code, message = outcome
|
||||
if state not in {'saved_ok', 'restored_ok'}:
|
||||
raise ValueError('Value report requires a verified replacement terminal state')
|
||||
status_bytes = _read(internal_path(root) / 'status.tsv')
|
||||
terminal = _fields(status_bytes.decode('utf-8-sig').splitlines()[-1])
|
||||
if terminal != (row['job_id'], state, code, message):
|
||||
if project_commit is not None:
|
||||
from .execution_proof import proof_intact
|
||||
from .path_access import canonical_path
|
||||
if (code != 'project_committed' or not proof_intact(project_commit)
|
||||
or canonical_path(project_commit['project_path']) != canonical_path(row['project_path'])
|
||||
or project_commit['outcomes'].get(row['job_id']) != state):
|
||||
raise ValueError('Value report has no matching intact project commit')
|
||||
marker = internal_path(project_commit['files'][0]['path'])
|
||||
lines = [_fields(line) for line in _read(marker).decode('utf-8-sig').splitlines() if line]
|
||||
if (lines[0] != (project_commit['session_token'],row['project_path'],'project_verified')
|
||||
or [fields[0] for fields in lines[1:]] != project_commit['jobs']
|
||||
or dict(lines[1:]) != project_commit['outcomes']):
|
||||
raise ValueError('Value report project commit marker differs')
|
||||
terminal = (row['job_id'],state,code,message)
|
||||
elif terminal != (row['job_id'], state, code, message):
|
||||
raise ValueError('Value report does not belong to the current terminal job')
|
||||
raw_bytes, snapshot_bytes = _read(raw), _read(snapshot_path)
|
||||
snapshot = snapshot_bytes.decode('utf-8-sig')
|
||||
@@ -74,8 +88,10 @@ def _validated(root, row, outcome):
|
||||
if row.get('target_scope') == 'targets':
|
||||
selected = {parts[0]: parts[1] for selector in selectors.split('\x1e')
|
||||
if len(parts := selector.split('\x1f')) == 3}
|
||||
if components != selected:
|
||||
raise ValueError('Value snapshot UID set differs from frozen command')
|
||||
expected_refs = {ref.strip().casefold() for ref in selected.values()}
|
||||
if (not selected or len(expected_refs) != len(selected)
|
||||
or {ref.strip().casefold() for ref in components.values()} != expected_refs):
|
||||
raise ValueError('Value snapshot physical reference set differs from frozen command')
|
||||
values, observations, seen, ordinals = [], [], set(), set()
|
||||
names = {}
|
||||
for line in lines[1:]:
|
||||
@@ -117,14 +133,16 @@ def _validated(root, row, outcome):
|
||||
value_readback_job_id=row['job_id'], project_path=row['project_path'],
|
||||
schematic_name=row.get('schematic_name', ''), sheet_number=row.get('sheet_number', ''),
|
||||
attribute_observations=observations, attribute_ambiguities=ambiguities)
|
||||
binding = dict(command=dict(row), terminal=list(terminal), status_sha256=_digest(status_bytes),
|
||||
binding = dict(command=dict(row), terminal=list(terminal), status_sha256=None if project_commit else _digest(status_bytes),
|
||||
snapshot_sha256=_digest(snapshot_bytes), report_sha256=_digest(raw_bytes))
|
||||
if project_commit is not None:
|
||||
binding['project_commit'] = project_commit
|
||||
return details, binding
|
||||
|
||||
|
||||
def capture_value_readback(root, row, outcome):
|
||||
def capture_value_readback(root, row, outcome, *, project_commit=None):
|
||||
try:
|
||||
details, binding = _validated(root, row, outcome)
|
||||
details, binding = _validated(root, row, outcome, project_commit=project_commit)
|
||||
_, saved, _ = _paths(root, row)
|
||||
write_record(saved, dict(schema=2, binding=binding, details=details))
|
||||
return details
|
||||
@@ -136,9 +154,10 @@ def capture_value_readback(root, row, outcome):
|
||||
|
||||
def load_value_readback(root, row, outcome):
|
||||
try:
|
||||
details, binding = _validated(root, row, outcome)
|
||||
_, saved, _ = _paths(root, row)
|
||||
persisted = json.loads(_read(saved))
|
||||
details, binding = _validated(root, row, outcome,
|
||||
project_commit=persisted.get('binding',{}).get('project_commit'))
|
||||
if persisted != dict(schema=2, binding=binding, details=details):
|
||||
raise ValueError('persisted Value evidence binding changed')
|
||||
return details
|
||||
|
||||
@@ -362,6 +362,7 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
stop_readers = threading.Event()
|
||||
output = [bytearray(), bytearray()]
|
||||
startup_pause = None
|
||||
prewrite_pause = None
|
||||
|
||||
def read_stream(stream, channel):
|
||||
try:
|
||||
@@ -379,7 +380,7 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
stream.close()
|
||||
|
||||
def receive(channel, line):
|
||||
nonlocal startup_pause
|
||||
nonlocal startup_pause, prewrite_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'):
|
||||
@@ -399,6 +400,29 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
'project_path': request[1], 'sequence': watch.sequence}
|
||||
except (OSError, UnicodeError, ValueError):
|
||||
pass
|
||||
elif channel == 0 and line.startswith(b'DX_PREWRITE_PAUSED\t'):
|
||||
try:
|
||||
from .quick_run import _decode_vbs_field
|
||||
from .path_access import canonical_path
|
||||
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')
|
||||
original = session_request.decode('utf-8-sig').strip().split('\t') if session_request else []
|
||||
if (len(fields) == 6 and fields[:3] == ['DX_PREWRITE_PAUSED', token, job_id]
|
||||
and len(request) == 3 and len(original) == 3 and request[:2] == original[:2]
|
||||
and fields[3:5] == [request[0], request[2]] and re.fullmatch('[0-9a-f]{32}', request[0])
|
||||
and re.fullmatch(r'[A-Za-z0-9_.-]{1,128}', request[2])
|
||||
and int(fields[5]) == watch.sequence and watch.sequence > 0
|
||||
and abort_event is not None and abort_event.is_set() and watch.stop_requested):
|
||||
marker = (root / ('project-pause-' + request[0] + '.tsv')).read_bytes()
|
||||
values = marker.decode('utf-8-sig').strip().split('\t')
|
||||
if (len(values) == 4 and values[0] == request[0] and values[2:] == [request[2], 'prewrite_closed']
|
||||
and canonical_path(_decode_vbs_field(values[1])) == canonical_path(request[1])):
|
||||
prewrite_pause = {'monitor_token': token, 'session_token': request[0], 'job_id': request[2],
|
||||
'project_path': request[1], 'sequence': watch.sequence,
|
||||
'request_bytes': request_data, 'marker_bytes': marker}
|
||||
except (OSError, UnicodeError, ValueError):
|
||||
pass
|
||||
elif len(output[channel]) < 1024 * 1024:
|
||||
output[channel].extend(line[:1024 * 1024 - len(output[channel])])
|
||||
|
||||
@@ -545,6 +569,15 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
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)
|
||||
if process.returncode == 75:
|
||||
if (prewrite_pause is None or prewrite_pause['sequence'] != watch.sequence
|
||||
or result.stderr.strip() or not _worker_tree_exited(process, owned)
|
||||
or (root / 'project-session.request').read_bytes() != prewrite_pause['request_bytes']
|
||||
or (root / ('project-pause-' + prewrite_pause['session_token'] + '.tsv')).read_bytes()
|
||||
!= prewrite_pause['marker_bytes']):
|
||||
raise WorkerMonitorError('prewrite pause lacks correlated closed-project acknowledgement or worker exit')
|
||||
result.prewrite_pause = {key: value for key, value in prewrite_pause.items()
|
||||
if key not in {'request_bytes', 'marker_bytes'}} | {'worker_tree_exited': True}
|
||||
return result
|
||||
except Exception as error:
|
||||
if process is not None:
|
||||
|
||||
@@ -9,21 +9,14 @@ from uuid import uuid4
|
||||
from .batch_resources import write_record
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import canonical_path, internal_path
|
||||
from .stop_control import StopControl, protect_interruption
|
||||
from .stop_control import ProjectStopControl, protect_interruption
|
||||
from .project_isolation import write_sources, record_task_outcome, block_dependency, dependency_readmitted
|
||||
|
||||
_LOCK = Lock()
|
||||
_TERMINAL = {'completed', 'failed', 'skipped', 'blocked'}
|
||||
|
||||
|
||||
class _ProjectControl(StopControl):
|
||||
def __init__(self, parent):
|
||||
super().__init__()
|
||||
self.parent = parent
|
||||
if hasattr(parent, 'force_event'):
|
||||
self.force_event = parent.force_event
|
||||
|
||||
def is_set(self):
|
||||
return super().is_set() or self.parent.is_set()
|
||||
_ProjectControl = ProjectStopControl
|
||||
|
||||
|
||||
@contextmanager
|
||||
@@ -68,7 +61,8 @@ def _released_after_recheck(root, task_id, row):
|
||||
journal = json.loads(internal_path(root / 'batch-resources' / batch_id / 'supervisor.json').read_text(encoding='utf-8'))
|
||||
return (valid_journal(journal, batch_id) and journal['task_ids'] == [task_id]
|
||||
and journal['state'] == 'finished' and journal.get('process')
|
||||
and _process_gone(journal['process']) and not pending_resources(root) and not pending_supervisors(root))
|
||||
and _process_gone(journal['process']) and not any(row.get('blocking', True) for row in pending_resources(root))
|
||||
and not any(row.get('blocking', True) for row in pending_supervisors(root)))
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return False
|
||||
|
||||
@@ -88,6 +82,7 @@ def execute_workspace_projects(service, task_ids, *, stop_event, queue_id=None,
|
||||
for rows in projects}) != len(ids):
|
||||
raise TaskCenterError('project_binding', '每个任务必须对应不同的单个工程。')
|
||||
hashes = {item: _plan_hash(children[item], item) for item in ids}
|
||||
sources = {item: write_sources(rows[0].path) for item, rows in zip(ids, projects)}
|
||||
if expected_plan_hashes is not None and hashes != expected_plan_hashes:
|
||||
raise TaskCenterError('assistant_stale', '执行计划已变化,请重新预检。')
|
||||
token = queue_id or checkpoint_id or uuid4().hex
|
||||
@@ -115,6 +110,9 @@ def execute_workspace_projects(service, task_ids, *, stop_event, queue_id=None,
|
||||
for item in ids}}
|
||||
write_record(path, state)
|
||||
|
||||
isolated_sources = state.setdefault('isolated_sources', {})
|
||||
dependency_tasks = state.setdefault('dependency_tasks', {})
|
||||
|
||||
def result(paused=False, current=None):
|
||||
verification = {item: state['entries'][item]['netlist_verification'] for item in ids
|
||||
if state['entries'][item].get('netlist_verification')}
|
||||
@@ -140,17 +138,25 @@ 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)
|
||||
if row['state'] == 'blocked':
|
||||
record_task_outcome(children[item], item, 'blocked', row['message'])
|
||||
isolated_sources.update((source, item) for source in sources[item])
|
||||
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:
|
||||
released = getattr(error, 'resources_released', False) is True
|
||||
from .batch_resources import resource_blockers
|
||||
released = ((getattr(error, 'resources_released', False) is True
|
||||
or getattr(error, 'owned_writers_exited', False) is True)
|
||||
and not resource_blockers(service.pending_batch_resources() if hasattr(service, 'pending_batch_resources') else ()))
|
||||
row.update(state='blocked', message=error.message, released=released)
|
||||
row['supervisor_batch_id'] = getattr(service, '_last_supervisor_batch_id', None)
|
||||
evidence = getattr(getattr(children[item], '_quick_run_preparer', None), 'data_root', root / 'tasks' / item)
|
||||
protect_interruption(Path(evidence) / 'quick-run', 'project_supervisor_failed: ' + error.message)
|
||||
record_task_outcome(children[item], item, 'blocked', error.message)
|
||||
isolated_sources.update((source, item) for source in sources[item])
|
||||
if released:
|
||||
from .batch_supervisor import reconcile_supervisors
|
||||
try:
|
||||
@@ -165,9 +171,31 @@ def execute_workspace_projects(service, task_ids, *, stop_event, queue_id=None,
|
||||
raise
|
||||
|
||||
try:
|
||||
if state['phase'] == 'finished' and any(dependency_readmitted(children[item], item, hashes[item])
|
||||
for item in tuple(dependency_tasks)):
|
||||
state['phase'] = 'primary'
|
||||
if state['phase'] == 'primary':
|
||||
for item in ids:
|
||||
row = state['entries'][item]
|
||||
readmitted = False
|
||||
if item in dependency_tasks:
|
||||
try:
|
||||
readmitted = dependency_readmitted(children[item], item, hashes[item])
|
||||
except TaskCenterError:
|
||||
pass
|
||||
if readmitted:
|
||||
row.update(state='pending', message='共享依赖已核验,恢复未派发原计划。')
|
||||
dependency_tasks.pop(item)
|
||||
conflict = next((isolated_sources[source] for source in sources[item]
|
||||
if source in isolated_sources and isolated_sources[source] != item), None)
|
||||
if conflict is not None and not readmitted and row['state'] not in {'completed', 'failed', 'skipped'}:
|
||||
message = f'与待核验工程 {conflict} 共享写入源,已隔离;未派发替换。'
|
||||
block_dependency(root, children[item], item, conflict,
|
||||
sources[item] & sources[conflict], hashes[item], token)
|
||||
dependency_tasks[item] = conflict
|
||||
row.update(state='blocked', message=message, released=True, problems_done=True)
|
||||
write_record(path, state)
|
||||
continue
|
||||
if row['state'] in _TERMINAL:
|
||||
if row['state'] == 'blocked' and not row['released']:
|
||||
if not _released_after_recheck(root, item, row):
|
||||
|
||||
Reference in new issue
Block a user