fix: resume frozen task queue after verified resource release
Core regression / Python core, intervention UI and release configuration (push) Successful in 5m2s
Core regression / JavaScript syntax (push) Successful in 7s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 5m32s
Core regression / JavaScript syntax (pull_request) Successful in 8s

This commit is contained in:
阿白叔 committed 2026-11-25 10:58:53 +08:00
1 parent d0bbc73da3
commit 6d45ea1fa0
12 files changed
+1259 -14

No files matched your search

+10 -1
View File
@@ -87,10 +87,12 @@ def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, res
else:
journal.begin(run_id, task_ids, report['plan_hashes'], schedule_id=schedule['schedule_id'] if schedule else None)
initialized = True
resource_batch_id = inspected.get('resource_batch_id') if resume else None
result = execute_task_queue(service, tuple(task_ids), stop_event=stop,
expected_plan_hashes=report['plan_hashes'],
queue_id=run_id if resume and resume['queue_available'] else None,
checkpoint_id=None if resume and resume['queue_available'] else run_id)
checkpoint_id=None if resume and resume['queue_available'] else run_id,
**({'resource_batch_id': resource_batch_id} if resource_batch_id else {}))
except Exception as error:
failure = {**(_failure_evidence(service, journal, run_id, baseline) if initialized else {}),
'status': 'interrupted', 'run_id': run_id, 'queue_id': run_id,
@@ -118,6 +120,13 @@ def _finish_execution_run(service, root, task_ids, stop, run_id, result, *, base
'user_pause_requested': bool(stop.is_set()), 'awaiting_user_resume': bool(result.paused and stop.is_set()),
'entries': entries, 'tasks': [], 'reporting_errors': [],
'message': '请按每项实际计数判断;未命中不表示已替换保存。'}
batch_id = getattr(service, '_last_supervisor_batch_id', None)
if result.paused and not stop.is_set() and batch_id:
from ..trial_task_center.task_queue import resource_pause_admitted
run = journal.get(run_id)
if (run and resource_pause_admitted(root, batch_id, tuple(task_ids), run['plan_hashes'],
result, require_released=False)):
receipt['resource_batch_id'] = batch_id
if result.netlist_verification:
receipt['netlist_verification'] = result.netlist_verification
# Persist the executor's known outcome before optional readback/enrichment.
+28 -1
View File
@@ -332,6 +332,31 @@ class RunJournal:
released_primary = {key for key, entry in (queue['entries'].items() if workspace and queue else ())
if entry['released'] and entry['state'] in {'completed', 'failed', 'skipped', 'blocked'}}
isolated = {key for key in released_primary if queue['entries'][key]['state'] == 'blocked'}
resource_batch_id = None
if queue and not workspace:
isolated.update(key for key in queue.get('isolated_tasks', {})
if key in queue['entries'] and queue['entries'][key]['state'] == 'blocked')
receipt = row.get('result') or {}
if (receipt.get('paused') is True and receipt.get('user_pause_requested') is False
and any(entry['state'] == 'blocked' and key not in isolated
for key, entry in queue['entries'].items())):
from ..trial_task_center.task_queue import resource_pause_admitted
pause = queue.get('resource_pause') or {}
known_batch = receipt.get('resource_batch_id') or pause.get('batch_id')
candidates = (known_batch,) if known_batch else (
path.parent.name for path in (self.data_root / 'batch-resources').glob('*/result.json'))
matches = []
for batch_id in candidates:
paused = resource_pause_admitted(self.data_root, batch_id,
tuple(row['task_ids']), row['plan_hashes'])
if paused and paused.queue_id == run_id:
matches.append((batch_id, paused))
if len(matches) > 1:
break
if len(matches) == 1:
resource_batch_id, paused = matches[0]
isolated.add(paused.current_task_id)
released_primary.update(isolated)
safe_continuations = set()
for task_id in row["task_ids"]:
item = {"task_id": task_id, "status": "unknown", "saved_items": 0, "failed_items": 0, "no_match_items": 0}
@@ -380,7 +405,8 @@ class RunJournal:
counters["completed"] = sum(queue["entries"][task_id]["state"] in {"completed", "failed", "skipped"} for task_id in row["task_ids"])
remaining = [task_id for task_id in row["task_ids"] if not queue or queue["entries"][task_id]["state"] not in {"completed", "failed", "skipped"}]
if queue and not workspace and queue.get('phase') in {'primary', 'problems'}:
remaining = [key for key in row['task_ids'] if key in remaining or key in released_primary]
remaining = [key for key in row['task_ids'] if key not in isolated and
(key in remaining or key in released_primary)]
if workspace and queue:
primary_exhausted = all(entry['state'] in {'completed', 'failed', 'skipped', 'blocked'} for entry in queue['entries'].values())
remaining = [key for key in row['task_ids'] if key not in isolated and (
@@ -407,6 +433,7 @@ class RunJournal:
blockers.append("resources_pending")
blockers = list(dict.fromkeys(blockers))
value = {**row, "queue_available": queue is not None, "tasks": tasks, "counters": counters,
'resource_batch_id': resource_batch_id,
'isolated_task_ids': [key for key in row['task_ids'] if key in isolated],
'released_primary_task_ids': [key for key in row['task_ids'] if key in released_primary],
'safe_continuation_task_ids': [key for key in row['task_ids'] if key in safe_continuations],
@@ -6,20 +6,28 @@ import re
from .path_access import canonical_path, internal_path
def write_sources(project):
def write_sources(project, *, strict=False):
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 strict:
definitions = re.findall(r'^[ \t]*KEY[ \t]+iCDBDir\b([^\r\n]*)', text,
re.MULTILINE | re.IGNORECASE)
match = re.fullmatch(r'[ \t]+"([^"\r\n]+)"[ \t]*', definitions[0]) if len(definitions) == 1 else None
if not match:
raise ValueError('The iCDBDir write source must be declared once')
else:
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
if strict:
raise
return sources
@@ -183,9 +183,76 @@ def reconcile_interrupted_queue(root, journal):
_save(path, state)
def resource_pause_admitted(root, batch_id, task_ids, plan_hashes, result=None, *, require_released=True):
"""Bind a completed supervisor's resource pause to the frozen queue."""
from .batch_resources import _process_gone, blocking_resources
from .batch_supervisor import pending_supervisors
from .path_access import canonical_path, internal_path
from .supervisor_protocol import MessageGate, decode, valid_journal
def token(value):
return isinstance(value, str) and len(value) == 32 and all(c in '0123456789abcdef' for c in value)
if not token(batch_id) or not plan_hashes:
return False
root = canonical_path(root)
directory = internal_path(root / 'batch-resources' / batch_id)
try:
journal = json.loads((directory / 'supervisor.json').read_bytes())
if (not valid_journal(journal, batch_id) or journal['state'] not in {'blocked', 'finished'}
or journal['operation'] != 'execute_task_queue' or journal['task_ids'] != list(task_ids)
or not journal['process'] or 'stop_requested_at' in journal
or journal.get('stop_mode') in {'safe', 'forced'} or (directory / 'cancel.json').exists()):
return False
raw_request = (directory / 'request.json').read_bytes()
request = json.loads(raw_request)
arguments = decode(request['arguments'])
if (hashlib.sha256(raw_request).hexdigest() != journal['request_sha256']
or request['batch_id'] != batch_id or request['attempt_id'] != journal['attempt_id']
or request['operation'] != journal['operation'] or canonical_path(request['root']) != root
or list(arguments['task_ids']) != list(task_ids) or arguments['expected_plan_hashes'] != plan_hashes):
return False
message = json.loads((directory / 'result.json').read_bytes())
if not MessageGate(batch_id, journal['attempt_id']).accept(message) or message['type'] != 'result':
return False
payload = message['payload']
recorded = decode(payload['result'])
if (payload['business_succeeded'] is not True or not isinstance(recorded, TaskQueueResult)
or result is not None and recorded != result or not recorded.paused
or not token(recorded.queue_id) or recorded.current_task_id not in task_ids
or (arguments['queue_id'] or arguments['checkpoint_id']) != recorded.queue_id):
return False
result = recorded
checkpoint = internal_path(root / 'task-queues' / (result.queue_id + '.json'))
state = json.loads(checkpoint.read_bytes())
current = result.current_task_id
if (state['version'] != 1 or state['task_ids'] != list(task_ids) or state['plan_hashes'] != plan_hashes
or state['phase'] != 'primary' or set(state['entries']) != set(task_ids)
or list(entry.task_id for entry in result.entries) != list(task_ids)
or any(state['entries'][entry.task_id]['state'] != entry.state for entry in result.entries)
or state['entries'][current]['state'] != 'blocked'
or any(entry.state in {'paused', 'running'} for entry in result.entries)
or not any(state['entries'][item]['state'] == 'pending' for item in task_ids[task_ids.index(current) + 1:])):
return False
if batch_id in state.get('consumed_resource_pauses', {}):
return False
warning = payload.get('resource_warning') or {}
pause = state.get('resource_pause') or {}
intended = ((pause.get('task_id'), pause.get('batch_id')) == (current, batch_id)
and isinstance(pause.get('sources'), dict)
and set(pause['sources']) == set(task_ids)
or not pause and warning.get('state') == 'isolated' and warning.get('owned_writers_exited') is True)
if intended and (not require_released or (journal['state'] == 'finished'
and _process_gone(journal['process']) and not blocking_resources(root) and not pending_supervisors(root))):
return result
return False
except (OSError, ValueError, TypeError, KeyError, AttributeError):
return False
def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
queue_id: str | None = None, runtime=None, expected_plan_hashes=None, checkpoint_id=None,
defer_problem_pass=False) -> TaskQueueResult:
defer_problem_pass=False, resource_batch_id=None) -> TaskQueueResult:
"""Execute the frozen order; uncertain state stops before the next project."""
if runtime is None and getattr(service, '_supervised', False):
# Existing per-project checkpoints keep their original resume owner.
@@ -196,9 +263,30 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
return execute_workspace_projects(service, task_ids, queue_id=queue_id, stop_event=stop_event,
expected_plan_hashes=expected_plan_hashes, checkpoint_id=checkpoint_id,
defer_problem_pass=defer_problem_pass)
return service._supervise('execute_task_queue', {'task_ids': tuple(task_ids),
arguments = {'task_ids': tuple(task_ids),
'queue_id': queue_id, 'expected_plan_hashes': expected_plan_hashes,
'checkpoint_id': checkpoint_id, 'defer_problem_pass': defer_problem_pass}, stop_event=stop_event)
'checkpoint_id': checkpoint_id, 'defer_problem_pass': defer_problem_pass}
if resource_batch_id:
arguments['resource_batch_id'] = resource_batch_id
recovered = set()
while True:
try:
result = service._supervise('execute_task_queue', arguments, stop_event=stop_event)
except TaskCenterError as error:
result = getattr(error, 'completed_result', None)
batch_id = getattr(service, '_last_supervisor_batch_id', None)
if (error.code not in {'batch_resources_pending', 'application_shutdown_failed'}
or stop_event.is_set() or not isinstance(result, TaskQueueResult)
or not resource_pause_admitted(service._logging.root, batch_id, tuple(task_ids),
expected_plan_hashes, result, require_released=False)):
raise
if (not result.paused or stop_event.is_set() or result.current_task_id in recovered
or not resource_pause_admitted(service._logging.root,
batch_id := getattr(service, '_last_supervisor_batch_id', None), tuple(task_ids),
expected_plan_hashes, result)):
return result
recovered.add(result.current_task_id)
arguments = dict(arguments, queue_id=result.queue_id, checkpoint_id=None, resource_batch_id=batch_id)
if runtime is None:
from .batch_runtime import BatchCadRuntime
with BatchCadRuntime(service._logging.root, 'task_queue', stop_event) as owned_runtime:
@@ -213,7 +301,7 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
root = service._logging.root
with _queue_lease(root):
children = {task_id: service.for_project_task(task_id) for task_id in ids}
project_paths = []
project_paths, projects_by_task = [], {}
sources = {}
for task_id, child in children.items():
task = child.get_task(task_id)
@@ -221,9 +309,14 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
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())
projects_by_task[task_id] = projects[0].path
sources[task_id] = write_sources(projects[0].path)
if len(set(project_paths)) != len(ids):
raise TaskCenterError('task_queue_selection', '不能在同一队列重复处理同一个工程。')
try:
frozen_sources = {item: sorted(write_sources(projects_by_task[item], strict=True)) for item in ids}
except (OSError, UnicodeError, ValueError):
frozen_sources = None
runtime.bind_logs(service._logging, ids)
hashes = {task_id: _plan_hash(child, task_id) for task_id, child in children.items()}
if expected_plan_hashes is not None and hashes != expected_plan_hashes:
@@ -260,6 +353,29 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
isolated_tasks = state.setdefault('isolated_tasks', {})
isolated_sources = state.setdefault('isolated_sources', {})
dependency_tasks = state.setdefault('dependency_tasks', {})
if resource_batch_id:
evidence = resource_pause_admitted(root, resource_batch_id, ids, hashes)
if not evidence or evidence.queue_id != queue_id:
raise TaskCenterError('task_queue_state', '原队列的资源释放或阻断回执无法核验。')
item = evidence.current_task_id
if not children[item].has_interrupted_quick_run(item):
raise TaskCenterError('task_queue_state', '阻断工程缺少原待核验证据。')
pause = state.get('resource_pause')
if pause:
known_sources = pause['sources']
else:
before = (state.get('netlist_verification', {}).get(item, {}).get('before') or {})
known = [str(Path(name).resolve()).casefold() for name in before.get('source_hashes', {})
if Path(name).suffix.casefold() == '.prj' or Path(name).name.casefold() == 'icdb.dat']
known_sources = {item: sorted(known)}
if not frozen_sources or any(frozen_sources.get(task) != values for task, values in known_sources.items()):
raise TaskCenterError('task_queue_state', '工程写入源已变化或无法核验,须重新确认。')
sources = {task: set(values) for task, values in frozen_sources.items()}
isolated_tasks[item] = state['entries'][item]['message']
isolated_sources.update((source, item) for source in sources[item])
state.setdefault('consumed_resource_pauses', {})[resource_batch_id] = item
state.pop('resource_pause', None)
_save(path, state)
from .netlist_verification import NetlistVerification
checks = NetlistVerification(root, token, stop_event)
try:
@@ -289,7 +405,8 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
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)
if not resource_batch_id or task_id not in state.get('netlist_verification', {}):
checks.before_task(children[task_id], task_id, existing_only=True)
continue
if stop_event.is_set():
paused = True
@@ -409,6 +526,11 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
execution_summary={key: getattr(progress, key, None)
for key in ('saved_items', 'failed_items', 'no_match_items')})
if paused:
if (entry['state'] == 'blocked' and not stop_event.is_set()
and frozen_sources and hasattr(runtime, 'session_id')):
state['resource_pause'] = {'task_id': task_id, 'batch_id': runtime.session_id,
'sources': frozen_sources}
_save(path, state)
break
if (not paused and stop_event.is_set() and state.get('phase') != 'finished'
and any(entry['state'] == 'failed' for entry in state['entries'].values())):
@@ -122,6 +122,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._batch_stop = None
self._active_quick_run_task_id = None
self._project_queues = {}
self._resource_queue_resume = None
self._execution_after_save = None
self._generation = 0
self._message = ''
@@ -214,6 +215,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._dsh_stall_timer.start()
self._resource_status.changed.connect(self._update_gates)
self._resource_status.changed.connect(self._observe_dsh_resource_blockers)
self._resource_status.changed.connect(self._resume_resource_queue)
self._resource_status.refresh()
self._refresh_task_list()
self._update_gates()
@@ -869,7 +871,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._bind_dsh_context()
self._run_async(execute, done, self.run_panel.quick_run_button, expected_task_id=task_id)
def _execute_project_tasks(self):
def _execute_project_tasks(self, *, resource_resume=False):
if not self.task_list.queue_button.isEnabled():
return
owner_task_id = self._context.task.task_id
@@ -885,7 +887,10 @@ class TrialTaskCenterWindow(MaterialMainWindow):
try:
if token:
from ...dsh.run_journal import resume_preflight
report = resume_preflight(self.service, self._dsh_operations.runs.inspect(self.service, token))
inspected = self._dsh_operations.runs.inspect(self.service, token)
if resource_resume and not inspected.get('resource_batch_id'):
return
report = resume_preflight(self.service, inspected)
else:
report = lifecycle.preflight(self.service, list(ids), allow_completed=True)
except Exception as error:
@@ -895,7 +900,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
return
self._dsh_confirmation_impact = report.get('impact', {})
enabled = report.get('impact', {}).get('enabled_scope', 0)
if not self._quick_run_confirmer('batch', len(ids), enabled):
if not resource_resume and not self._quick_run_confirmer('batch', len(ids), enabled):
return
if not self._confirmed_execution_allowed(owner_task_id, ids, self.task_list.queue_button):
return
@@ -941,9 +946,30 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._show_receipt_verification(receipt)
self._dsh_last_execution = receipt
self._bind_dsh_context()
if (result.paused and receipt.get('resource_batch_id') and not stop.is_set()
and not self._close_pending and not self._closed):
self._resource_queue_resume = (group, result.queue_id, ids)
else:
done(value)
self._run_async(execute, completed, self.task_list.queue_button)
self._run_async(execute, completed, self.task_list.queue_button, on_finished=self._check_resource_queue)
def _check_resource_queue(self):
if self._resource_queue_resume and self._resource_status.blocked and not self._workers:
self._cleanup_batch_resources(automatic=True)
else:
self._resume_resource_queue()
def _resume_resource_queue(self):
pending = self._resource_queue_resume
if (not pending or self._closed or self._close_pending or self._workers or self._loading
or self._resource_status.busy or not self._resource_status.known or self._resource_status.blocked):
return
group, token, ids = pending
if (self._context is None or self._context.task.group_id != group
or self._project_queues.get(group) != (token, ids) or self.plan_panel.has_unsaved_plan(ids)):
return
self._resource_queue_resume = None
self._execute_project_tasks(resource_resume=True)
def _begin_run(self, task_id):
from uuid import uuid4
@@ -1056,6 +1082,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
nonlocal cleanup_finished
cleanup_finished = True
start_force_if_ready()
self._resume_resource_queue()
def forced(remaining):
from ..batch_resources import resource_blockers
self._resource_status.refresh()